Search in sources :

Example 6 with ArrayFloat

use of ucar.ma2.ArrayFloat in project imageio-ext by geosolutions-it.

the class SWANConverter method run.

private void run(String fileNameIn, String fileNameOut) {
    try {
        final File fileIn = new File(fileNameIn);
        final NetcdfFile ncFileIn = NetcdfFile.open(fileNameIn);
        final File fileOut = new File(fileNameOut);
        // keep original name
        final File outputFile = File.createTempFile(fileIn.getName(), ".tmp");
        final NetcdfFileWriteable ncFileOut = NetcdfFileWriteable.createNew(outputFile.getAbsolutePath());
        boolean hasZeta = false;
        // input dimensions
        final Dimension timeDim0 = ncFileIn.findDimension("time");
        final int nTimes = timeDim0.getLength();
        final Dimension latDim0 = ncFileIn.findDimension(NetCDFUtilities.LATITUDE);
        final int nLat = latDim0.getLength();
        final Dimension lonDim0 = ncFileIn.findDimension(NetCDFUtilities.LONGITUDE);
        final int nLon = lonDim0.getLength();
        // input VARIABLES
        final Variable timeOriginalVar = ncFileIn.findVariable("time");
        final Array timeOriginalData = timeOriginalVar.read();
        final Index timeOriginalIndex = timeOriginalData.getIndex();
        final DataType timeDataType = timeOriginalVar.getDataType();
        final Variable lonOriginalVar = ncFileIn.findVariable(NetCDFUtilities.LONGITUDE);
        final DataType lonDataType = lonOriginalVar.getDataType();
        final Variable latOriginalVar = ncFileIn.findVariable(NetCDFUtilities.LATITUDE);
        final DataType latDataType = latOriginalVar.getDataType();
        final Array latOriginalData = latOriginalVar.read();
        final Array lonOriginalData = lonOriginalVar.read();
        // //
        // 
        // Depth related vars
        // 
        // //
        Array levelOriginalData = null;
        int nZeta = 0;
        Array zeta1Data = null;
        Dimension zDim = null;
        DataType zetaDataType = null;
        // Depth
        final Variable levelOriginalVar = ncFileIn.findVariable("z");
        if (levelOriginalVar != null) {
            nZeta = levelOriginalVar.getDimension(0).getLength();
            levelOriginalData = levelOriginalVar.read();
            zetaDataType = levelOriginalVar.getDataType();
            hasZeta = true;
        }
        Dimension timeDim = ncFileOut.addDimension("time", nTimes);
        Dimension latDim = ncFileOut.addDimension(NetCDFUtilities.LAT, nLat);
        Dimension lonDim = ncFileOut.addDimension(NetCDFUtilities.LON, nLon);
        if (hasZeta)
            zDim = ncFileOut.addDimension(NetCDFUtilities.HEIGHT, nZeta);
        NetCDFConverterUtilities.copyGlobalAttributes(ncFileOut, ncFileIn.getGlobalAttributes());
        // Dimensions
        Variable timeVar = ncFileOut.addVariable("time", timeDataType, new Dimension[] { timeDim });
        NetCDFConverterUtilities.setVariableAttributes(timeOriginalVar, ncFileOut, new String[] { "long_name" });
        ncFileOut.addVariableAttribute("time", "long_name", "time");
        ncFileOut.addVariable(NetCDFUtilities.LAT, latDataType, new Dimension[] { latDim });
        NetCDFConverterUtilities.setVariableAttributes(latOriginalVar, ncFileOut, NetCDFUtilities.LAT);
        ncFileOut.addVariable(NetCDFUtilities.LON, lonDataType, new Dimension[] { lonDim });
        NetCDFConverterUtilities.setVariableAttributes(lonOriginalVar, ncFileOut, NetCDFUtilities.LON);
        if (hasZeta) {
            ncFileOut.addVariable(NetCDFUtilities.HEIGHT, zetaDataType, new Dimension[] { zDim });
            NetCDFConverterUtilities.setVariableAttributes(levelOriginalVar, ncFileOut, NetCDFUtilities.HEIGHT, new String[] { "long_name" });
            ncFileOut.addVariableAttribute(NetCDFUtilities.HEIGHT, "positive", "up");
            ncFileOut.addVariableAttribute(NetCDFUtilities.HEIGHT, "long_name", NetCDFUtilities.HEIGHT);
        }
        // lat Variable
        Array lat1Data = NetCDFConverterUtilities.getArray(nLat, latDataType);
        NetCDFConverterUtilities.setData1D(latOriginalData, lat1Data, latDataType, nLat, true);
        // lon Variable
        Array lon1Data = NetCDFConverterUtilities.getArray(nLon, lonDataType);
        NetCDFConverterUtilities.setData1D(lonOriginalData, lon1Data, lonDataType, nLon, false);
        if (hasZeta) {
            // depth level Variable
            zeta1Data = NetCDFConverterUtilities.getArray(nZeta, zetaDataType);
            NetCDFConverterUtilities.setData1D(levelOriginalData, zeta1Data, zetaDataType, nZeta, false);
        }
        // {} Variables
        final ArrayList<String> variables = new ArrayList<String>(5);
        int numVars = 0;
        List<Variable> findVariables = ncFileIn.getVariables();
        for (Variable var : findVariables) {
            if (var != null) {
                String varName = var.getName();
                if (varName.equalsIgnoreCase(NetCDFUtilities.LATITUDE) || varName.equalsIgnoreCase(NetCDFUtilities.LONGITUDE) || varName.equalsIgnoreCase(NetCDFUtilities.TIME) || varName.equalsIgnoreCase(NetCDFUtilities.ZETA))
                    continue;
                variables.add(varName);
                List<Dimension> dims = var.getDimensions();
                boolean hasLocalZeta = false;
                for (Dimension dim : dims) {
                    if (dim.getName().equalsIgnoreCase(NetCDFUtilities.ZETA)) {
                        hasLocalZeta = true;
                        break;
                    }
                }
                if (hasZeta && hasLocalZeta)
                    ncFileOut.addVariable(varName, var.getDataType(), new Dimension[] { timeDim, zDim, latDim, lonDim });
                else
                    ncFileOut.addVariable(varName, var.getDataType(), new Dimension[] { timeDim, latDim, lonDim });
                NetCDFConverterUtilities.setVariableAttributes(var, ncFileOut, new String[] { "missing_value" });
                numVars++;
            }
        }
        // writing bin data ...
        ncFileOut.create();
        ArrayFloat timeData = new ArrayFloat(new int[] { timeDim.getLength() });
        Index timeIndex = timeData.getIndex();
        for (int t = 0; t < timeDim.getLength(); t++) {
            timeData.setFloat(timeIndex.set(t), timeOriginalData.getFloat(timeOriginalIndex.set(t)));
        }
        ncFileOut.write("time", timeData);
        timeVar = ncFileOut.findVariable("time");
        timeDim.addCoordinateVariable(timeVar);
        ncFileOut.write(NetCDFUtilities.LAT, lat1Data);
        ncFileOut.write(NetCDFUtilities.LON, lon1Data);
        if (hasZeta) {
            Variable heightVar = ncFileOut.findVariable(NetCDFUtilities.HEIGHT);
            zDim.addCoordinateVariable(heightVar);
            ncFileOut.write(NetCDFUtilities.HEIGHT, zeta1Data);
        }
        for (int i = 0; i < numVars; i++) {
            String varName = (String) variables.get(i);
            Variable var = ncFileIn.findVariable(varName);
            boolean hasLocalZeta = NetCDFConverterUtilities.hasThisDimension(var, NetCDFUtilities.ZETA);
            Array originalVarArray = var.read();
            DataType varDataType = var.getDataType();
            Array destArray = null;
            int[] dimensions = null;
            if (hasZeta && hasLocalZeta) {
                dimensions = new int[] { timeDim.getLength(), zDim.getLength(), latDim.getLength(), lonDim.getLength() };
            } else {
                dimensions = new int[] { timeDim.getLength(), latDim.getLength(), lonDim.getLength() };
            }
            destArray = NetCDFConverterUtilities.getArray(dimensions, varDataType);
            final boolean setZeta = hasZeta && hasLocalZeta;
            final int[] loopLengths;
            if (setZeta)
                loopLengths = new int[] { nTimes, nZeta, nLat, nLon };
            else
                loopLengths = new int[] { nTimes, nLat, nLon };
            NetCDFConverterUtilities.writeData(ncFileOut, varName, var, originalVarArray, destArray, false, false, loopLengths, true);
        }
        ncFileOut.close();
        outputFile.renameTo(fileOut);
    } catch (Exception e) {
        // something bad happened
        if (NetCDFConverterUtilities.LOGGER.isLoggable(Level.INFO))
            NetCDFConverterUtilities.LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
        JAI.getDefaultInstance().getTileCache().flush();
    }
}
Also used : NetcdfFileWriteable(ucar.nc2.NetcdfFileWriteable) Variable(ucar.nc2.Variable) ArrayList(java.util.ArrayList) Index(ucar.ma2.Index) ArrayFloat(ucar.ma2.ArrayFloat) Dimension(ucar.nc2.Dimension) IOException(java.io.IOException) NetcdfFile(ucar.nc2.NetcdfFile) Array(ucar.ma2.Array) DataType(ucar.ma2.DataType) File(java.io.File) NetcdfFile(ucar.nc2.NetcdfFile)

Example 7 with ArrayFloat

use of ucar.ma2.ArrayFloat in project imageio-ext by geosolutions-it.

the class MercatorOceanConverter method run.

private void run(String fileNameIn, String fileNameOut) {
    try {
        final File fileIn = new File(fileNameIn);
        final NetcdfFile ncFileIn = NetcdfFile.open(fileNameIn);
        final File fileOut = new File(fileNameOut);
        // keep original name
        final File outputFile = File.createTempFile(fileIn.getName(), ".tmp");
        final NetcdfFileWriteable ncFileOut = NetcdfFileWriteable.createNew(outputFile.getAbsolutePath());
        // input dimensions
        final Dimension latOriginalDim = ncFileIn.findDimension(NetCDFUtilities.LATITUDE);
        final Dimension lonOriginalDim = ncFileIn.findDimension(NetCDFUtilities.LONGITUDE);
        // input VARIABLES
        // Variable time_0 = ncFileIn.findVariable("time");
        // Array time_0_Data = time_0.read();
        // Index time_0_Index = time_0_Data.getIndex();
        final Variable lonOriginalVar = ncFileIn.findVariable(NetCDFUtilities.LONGITUDE);
        final int nLon = lonOriginalDim.getLength();
        final Variable latOriginalVar = ncFileIn.findVariable(NetCDFUtilities.LATITUDE);
        final int nLat = latOriginalDim.getLength();
        final Array latOriginalData = latOriginalVar.read();
        final Index latOriginalIndex = latOriginalData.getIndex();
        final Array lonOriginalData = lonOriginalVar.read();
        final Index lonOriginalIndex = lonOriginalData.getIndex();
        final Variable depthOriginalVar = ncFileIn.findVariable(// Depth
        NetCDFUtilities.DEPTH);
        final int nLevels = depthOriginalVar.getDimension(0).getLength();
        final Array depthOriginalData = depthOriginalVar.read();
        // Dimension timeDim = ncFileOut.addDimension("time",
        // timeDim0.getLength());
        Dimension latDim = ncFileOut.addDimension(NetCDFUtilities.LAT, nLat);
        Dimension lonDim = ncFileOut.addDimension(NetCDFUtilities.LON, nLon);
        Dimension depthDim = ncFileOut.addDimension(NetCDFUtilities.DEPTH, nLevels);
        Dimension timeDim = ncFileOut.addDimension(NetCDFUtilities.TIME, 1);
        // writing file
        computeMatrixExtremes(latOriginalData, lonOriginalData, nLon, nLat, latOriginalIndex, lonOriginalIndex);
        NetCDFConverterUtilities.copyGlobalAttributes(ncFileOut, ncFileIn.getGlobalAttributes());
        // //
        // 
        // Time requires a special Management
        // 
        // //
        // time Variable
        Variable timeVar = ncFileOut.addVariable(NetCDFUtilities.TIME, DataType.FLOAT, new Dimension[] { timeDim });
        Attribute referenceTime = ncFileIn.findGlobalAttribute(TIME_ORIGIN);
        Attribute forecastDate = ncFileIn.findGlobalAttribute(FORECAST_DAY);
        int numDay = 0;
        if (referenceTime != null && forecastDate != null) {
            numDay = setTime(ncFileOut, referenceTime, forecastDate);
        }
        // final float referenceTime = setTimeVariableAttributes(timeVar,
        // ncFileOut);
        // lat Variable
        ArrayFloat latDestData = new ArrayFloat(new int[] { latOriginalDim.getLength() });
        Index latDestIndex = latDestData.getIndex();
        ncFileOut.addVariable(NetCDFUtilities.LAT, DataType.FLOAT, new Dimension[] { latDim });
        // NOTE: A Strange BUG (I guess)
        // when you copy attributes from old vars to new vars, it overwrite
        // coordvars!!!
        ncFileOut.addVariableAttribute(NetCDFUtilities.LAT, "long_name", NetCDFUtilities.LATITUDE);
        ncFileOut.addVariableAttribute(NetCDFUtilities.LAT, UNITS, latOriginalVar.getUnitsString());
        // new String[] { "long_name", UNITS, "step" , "axis"});
        for (int yPos = 0; yPos < latOriginalDim.getLength(); yPos++) {
            latDestData.setFloat(latDestIndex.set(yPos), new Float(this.ymax - (new Float(yPos).floatValue() * this.periodY)).floatValue());
        }
        // lon Variable
        ArrayFloat lonDestData = new ArrayFloat(new int[] { lonOriginalDim.getLength() });
        Index lonDestIndex = lonDestData.getIndex();
        ncFileOut.addVariable(NetCDFUtilities.LON, DataType.FLOAT, new Dimension[] { lonDim });
        ncFileOut.addVariableAttribute(NetCDFUtilities.LON, "long_name", NetCDFUtilities.LONGITUDE);
        ncFileOut.addVariableAttribute(NetCDFUtilities.LON, UNITS, lonOriginalVar.getUnitsString());
        // new String[] { "long_name", UNITS, "step", "axis"});
        for (int xPos = 0; xPos < lonOriginalDim.getLength(); xPos++) {
            lonDestData.setFloat(lonDestIndex.set(xPos), new Float(this.xmin + (new Float(xPos).floatValue() * this.periodX)).floatValue());
        }
        // depth level Variable
        ArrayFloat depthDestData = new ArrayFloat(new int[] { depthDim.getLength() });
        Index depthDestIndex = depthDestData.getIndex();
        ncFileOut.addVariable(NetCDFUtilities.DEPTH, DataType.FLOAT, new Dimension[] { depthDim });
        ncFileOut.addVariableAttribute(NetCDFUtilities.DEPTH, "long_name", NetCDFUtilities.DEPTH);
        ncFileOut.addVariableAttribute(NetCDFUtilities.DEPTH, UNITS, depthOriginalVar.getUnitsString());
        final Attribute positiveAttrib = depthOriginalVar.findAttribute("positive");
        String positiveValue = "down";
        if (positiveAttrib != null)
            positiveValue = positiveAttrib.getStringValue();
        ncFileOut.addVariableAttribute(NetCDFUtilities.DEPTH, "positive", positiveValue);
        for (int wPos = 0; wPos < depthDim.getLength(); wPos++) {
            depthDestData.setFloat(depthDestIndex.set(wPos), depthOriginalData.getFloat(depthDestIndex));
        }
        int numVars = 0;
        final ArrayList<String> variables = new ArrayList<String>(5);
        // {} Variables
        for (int i = 0; i < NUMVARS; i++) {
            String varName = (String) VARIABLES.get(i);
            Variable var = ncFileIn.findVariable(varName);
            if (var != null) {
                variables.add(varName);
                boolean hasLocalDepth = NetCDFConverterUtilities.hasThisDimension(var, "depth");
                if (hasLocalDepth)
                    ncFileOut.addVariable(varName, var.getDataType(), new Dimension[] { timeDim, depthDim, latDim, lonDim });
                else
                    ncFileOut.addVariable(varName, var.getDataType(), new Dimension[] { timeDim, latDim, lonDim });
                NetCDFConverterUtilities.setVariableAttributes(var, ncFileOut, new String[] { "positions" });
                numVars++;
            }
        }
        // writing bin data ...
        ncFileOut.create();
        ArrayFloat timeData = new ArrayFloat(new int[] { timeDim.getLength() });
        Index timeIndex = timeData.getIndex();
        timeData.setFloat(timeIndex.set(0), numDay);
        ncFileOut.write(NetCDFUtilities.TIME, timeData);
        timeDim.addCoordinateVariable(timeVar);
        Variable latitudeVar = ncFileOut.findVariable(NetCDFUtilities.LAT);
        latDim.addCoordinateVariable(latitudeVar);
        ncFileOut.write(NetCDFUtilities.LAT, latDestData);
        Variable longitudeVar = ncFileOut.findVariable(NetCDFUtilities.LON);
        lonDim.addCoordinateVariable(longitudeVar);
        ncFileOut.write(NetCDFUtilities.LON, lonDestData);
        Variable depthVar = ncFileOut.findVariable(NetCDFUtilities.DEPTH);
        depthDim.addCoordinateVariable(depthVar);
        ncFileOut.write(NetCDFUtilities.DEPTH, depthDestData);
        for (int i = 0; i < numVars; i++) {
            final String varName = (String) variables.get(i);
            final Variable var = ncFileIn.findVariable(varName);
            final boolean hasLocalDepth = NetCDFConverterUtilities.hasThisDimension(var, "depth");
            final Array originalData = var.read();
            Index varIndex = originalData.getIndex();
            final DataType varDataType = var.getDataType();
            final Attribute fv = var.findAttribute("_FillValue");
            float fillValue = Float.NaN;
            if (fv != null) {
                fillValue = (fv.getNumericValue()).floatValue();
            }
            Array destArray = null;
            int[] dimensions = null;
            if (hasLocalDepth) {
                dimensions = new int[] { timeDim.getLength(), depthDim.getLength(), nLat, nLon };
            } else {
                dimensions = new int[] { timeDim.getLength(), nLat, nLon };
            }
            destArray = NetCDFConverterUtilities.getArray(dimensions, varDataType);
            Index destIndex = destArray.getIndex();
            ArrayFloat tempData = new ArrayFloat(new int[] { latOriginalDim.getLength(), lonOriginalDim.getLength() });
            Index tempIndex = tempData.getIndex();
            if (hasLocalDepth) {
                for (int levelPos = 0; levelPos < depthDim.getLength(); levelPos++) {
                    for (int yPos = 0; yPos < latOriginalDim.getLength(); yPos++) {
                        for (int xPos = 0; xPos < lonOriginalDim.getLength(); xPos++) {
                            tempData.setFloat(tempIndex.set(yPos, xPos), originalData.getFloat(varIndex.set(levelPos, yPos, xPos)));
                        }
                    }
                    final WritableRaster outData = Resampler(latOriginalData, lonOriginalData, lonOriginalDim.getLength(), latOriginalDim.getLength(), 2, tempData, fillValue);
                    for (int j = 0; j < latOriginalDim.getLength(); j++) {
                        for (int k = 0; k < lonOriginalDim.getLength(); k++) {
                            float sample = outData.getSampleFloat(k, j, 0);
                            destArray.setFloat(destIndex.set(0, levelPos, j, k), sample);
                        }
                    }
                }
            } else {
                for (int yPos = 0; yPos < latOriginalDim.getLength(); yPos++) {
                    for (int xPos = 0; xPos < lonOriginalDim.getLength(); xPos++) {
                        tempData.setFloat(tempIndex.set(yPos, xPos), originalData.getFloat(varIndex.set(yPos, xPos)));
                    }
                }
                final WritableRaster outData = Resampler(latOriginalData, lonOriginalData, lonOriginalDim.getLength(), latOriginalDim.getLength(), 2, tempData, fillValue);
                for (int j = 0; j < latOriginalDim.getLength(); j++) {
                    for (int k = 0; k < lonOriginalDim.getLength(); k++) {
                        float sample = outData.getSampleFloat(k, j, 0);
                        destArray.setFloat(destIndex.set(0, j, k), sample);
                    }
                }
            }
            // }
            ncFileOut.write(varName, destArray);
        }
        ncFileOut.close();
        outputFile.renameTo(fileOut);
    } catch (Exception e) {
        // something bad happened
        if (LOGGER.isLoggable(Level.INFO))
            LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
        JAI.getDefaultInstance().getTileCache().flush();
    }
}
Also used : NetcdfFileWriteable(ucar.nc2.NetcdfFileWriteable) Variable(ucar.nc2.Variable) Attribute(ucar.nc2.Attribute) ArrayList(java.util.ArrayList) Index(ucar.ma2.Index) ArrayFloat(ucar.ma2.ArrayFloat) Dimension(ucar.nc2.Dimension) ParseException(java.text.ParseException) IOException(java.io.IOException) NetcdfFile(ucar.nc2.NetcdfFile) Array(ucar.ma2.Array) ArrayFloat(ucar.ma2.ArrayFloat) WritableRaster(java.awt.image.WritableRaster) DataType(ucar.ma2.DataType) File(java.io.File) NetcdfFile(ucar.nc2.NetcdfFile)

Example 8 with ArrayFloat

use of ucar.ma2.ArrayFloat in project imageio-ext by geosolutions-it.

the class NetCDFConverterUtilities method getRangeArray.

public static Array getRangeArray(DataType varDataType) {
    int[] dim = new int[] { 2 };
    if (varDataType == DataType.FLOAT) {
        Array array = new ArrayFloat(dim);
        Index index = array.getIndex();
        array.setFloat(index.set(0), Float.MIN_VALUE);
        array.setFloat(index.set(1), Float.MAX_VALUE);
        return array;
    } else if (varDataType == DataType.DOUBLE) {
        Array array = new ArrayDouble(dim);
        Index index = array.getIndex();
        array.setDouble(index.set(0), Double.MIN_VALUE);
        array.setDouble(index.set(1), Double.MAX_VALUE);
        return array;
    } else if (varDataType == DataType.BYTE) {
        Array array = new ArrayByte(dim);
        Index index = array.getIndex();
        array.setByte(index.set(0), Byte.MIN_VALUE);
        array.setByte(index.set(1), Byte.MAX_VALUE);
        return array;
    } else if (varDataType == DataType.SHORT) {
        Array array = new ArrayShort(dim);
        Index index = array.getIndex();
        array.setShort(index.set(0), Short.MIN_VALUE);
        array.setShort(index.set(1), Short.MAX_VALUE);
        return array;
    } else if (varDataType == DataType.INT) {
        Array array = new ArrayInt(dim);
        Index index = array.getIndex();
        array.setInt(index.set(0), Integer.MIN_VALUE);
        array.setInt(index.set(1), Integer.MAX_VALUE);
        return array;
    }
    throw new IllegalArgumentException("Actually unsupported Datatype");
}
Also used : Array(ucar.ma2.Array) ArrayDouble(ucar.ma2.ArrayDouble) ArrayFloat(ucar.ma2.ArrayFloat) Index(ucar.ma2.Index) ArrayByte(ucar.ma2.ArrayByte) ArrayInt(ucar.ma2.ArrayInt) ArrayShort(ucar.ma2.ArrayShort)

Example 9 with ArrayFloat

use of ucar.ma2.ArrayFloat in project imageio-ext by geosolutions-it.

the class BaseHDF4ImageReader method read2DVariable.

protected BufferedImage read2DVariable(final int imageIndex, final ImageReadParam param) throws IOException {
    BufferedImage image = null;
    final HDF4DatasetWrapper wrapper = getDatasetWrapper(imageIndex);
    final Variable variable = wrapper.getVariable();
    /*
         * Fetches the parameters that are not already processed by utility
         * methods like 'getDestination' or 'computeRegions' (invoked below).
         */
    final int strideX, strideY;
    final int[] srcBands, dstBands;
    if (param != null) {
        strideX = param.getSourceXSubsampling();
        strideY = param.getSourceYSubsampling();
        srcBands = param.getSourceBands();
        dstBands = param.getDestinationBands();
    } else {
        strideX = 1;
        strideY = 1;
        srcBands = null;
        dstBands = null;
    }
    final int rank = variable.getRank();
    /*
         * Gets the destination image of appropriate size. We create it now
         * since it is a convenient way to get the number of destination bands.
         */
    final int width = wrapper.getWidth();
    final int height = wrapper.getHeight();
    final int numBands = wrapper.getNumBands();
    /*
         * Computes the source region (in the NetCDF file) and the destination
         * region (in the buffered image). Copies those informations into UCAR
         * Range structure.
         */
    final Rectangle srcRegion = new Rectangle();
    final Rectangle destRegion = new Rectangle();
    computeRegions(param, width, height, null, srcRegion, destRegion);
    // flipVertically(param, height, srcRegion);
    int destWidth = destRegion.x + destRegion.width;
    int destHeight = destRegion.y + destRegion.height;
    final List<Range> ranges = new LinkedList<Range>();
    for (int i = 0; i < rank; i++) {
        final int first, length, stride;
        switch(i) {
            case 1:
                {
                    first = srcRegion.x;
                    length = srcRegion.width;
                    stride = strideX;
                    break;
                }
            case 0:
                {
                    first = srcRegion.y;
                    length = srcRegion.height;
                    stride = strideY;
                    break;
                }
            default:
                {
                    first = 0;
                    length = numBands;
                    stride = 1;
                    break;
                }
        }
        try {
            ranges.add(new Range(first, first + length - 1, stride));
        } catch (InvalidRangeException e) {
        // TODO LOGME
        }
    }
    final Section sections = new Section(ranges);
    /*
         * Setting SampleModel and ColorModel.
         */
    final SampleModel sampleModel = wrapper.getSampleModel().createCompatibleSampleModel(destWidth, destHeight);
    final ColorModel colorModel = ImageIOUtilities.createColorModel(sampleModel);
    /*
         * Reads the requested sub-region only.
         */
    final int size = destHeight * destWidth * numBands;
    Array array = null;
    try {
        array = variable.read(sections);
        DataBuffer dataBuffer = null;
        if (array instanceof ArrayByte) {
            dataBuffer = new DataBufferByte((byte[]) array.get1DJavaArray(byte.class), size);
        } else if (array instanceof ArrayShort) {
            dataBuffer = new DataBufferShort((short[]) array.get1DJavaArray(short.class), size);
        } else if (array instanceof ArrayInt) {
            dataBuffer = new DataBufferInt((int[]) array.get1DJavaArray(int.class), size);
        } else if (array instanceof ArrayFloat) {
            dataBuffer = new DataBufferFloat((float[]) array.get1DJavaArray(float.class), size);
        } else if (array instanceof ArrayDouble) {
            dataBuffer = new DataBufferDouble((double[]) array.get1DJavaArray(double.class), size);
        }
        WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuffer, new Point(0, 0));
        image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);
    } catch (InvalidRangeException e) {
    // TODO LOGME
    }
    return image;
}
Also used : DataBufferDouble(java.awt.image.DataBufferDouble) Variable(ucar.nc2.Variable) Rectangle(java.awt.Rectangle) ArrayFloat(ucar.ma2.ArrayFloat) DataBufferInt(java.awt.image.DataBufferInt) DataBufferByte(java.awt.image.DataBufferByte) BufferedImage(java.awt.image.BufferedImage) DataBufferShort(java.awt.image.DataBufferShort) ArrayDouble(ucar.ma2.ArrayDouble) ColorModel(java.awt.image.ColorModel) WritableRaster(java.awt.image.WritableRaster) ArrayByte(ucar.ma2.ArrayByte) ArrayShort(ucar.ma2.ArrayShort) DataBuffer(java.awt.image.DataBuffer) InvalidRangeException(ucar.ma2.InvalidRangeException) Point(java.awt.Point) Range(ucar.ma2.Range) Section(ucar.ma2.Section) Point(java.awt.Point) LinkedList(java.util.LinkedList) Array(ucar.ma2.Array) SampleModel(java.awt.image.SampleModel) BandedSampleModel(java.awt.image.BandedSampleModel) PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) ArrayInt(ucar.ma2.ArrayInt) DataBufferFloat(java.awt.image.DataBufferFloat)

Example 10 with ArrayFloat

use of ucar.ma2.ArrayFloat in project imageio-ext by geosolutions-it.

the class NetCDFCF_CLewis_Converter method run.

private void run(String fileNameIn, String fileNameOut) {
    try {
        NetcdfFile ncFileIn = NetcdfFile.open(fileNameIn);
        ncFileIn.writeCDL(System.out, true);
        NetcdfFileWriteable ncFileOut = NetcdfFileWriteable.createNew(fileNameOut);
        // input dimensions
        Dimension timeDim0 = ncFileIn.findDimension("time");
        Dimension latDim0 = ncFileIn.findDimension("lat");
        Dimension lonDim0 = ncFileIn.findDimension("lon");
        // input variables
        Variable time_0 = ncFileIn.findVariable("time");
        Array time_0_Data = time_0.read();
        Index time_0_Index = time_0_Data.getIndex();
        Variable lon_0 = ncFileIn.findVariable("lon");
        final int nLon = lon_0.getDimension(0).getLength();
        Variable lat_0 = ncFileIn.findVariable("lat");
        final int nLat = lat_0.getDimension(0).getLength();
        Array lat_0_Data = lat_0.read();
        Index lat_0_Index = lat_0_Data.getIndex();
        Array lon_0_Data = lon_0.read();
        Index lon_0_Index = lon_0_Data.getIndex();
        // Depth
        Variable z_0 = ncFileIn.findVariable("z");
        final int nLevels = z_0.getDimension(0).getLength();
        Array z_0_Data = z_0.read();
        Index z_0_Index = z_0_Data.getIndex();
        Dimension timeDim = ncFileOut.addDimension("time", timeDim0.getLength());
        Dimension latDim = ncFileOut.addDimension(NetCDFUtilities.LAT, latDim0.getLength());
        Dimension lonDim = ncFileOut.addDimension(NetCDFUtilities.LON, lonDim0.getLength());
        Dimension depthDim = ncFileOut.addDimension(NetCDFUtilities.DEPTH, nLevels);
        // writing file
        this.computeMatrixExtremes(lat_0_Data, lon_0_Data, lonDim0.getLength(), latDim0.getLength(), lat_0_Index, lon_0_Index);
        NetCDFConverterUtilities.copyGlobalAttributes(ncFileOut, ncFileIn.getGlobalAttributes());
        // //
        // 
        // Time requires a special Management
        // 
        // //
        // time Variable
        ncFileOut.addVariable("time", DataType.FLOAT, new Dimension[] { timeDim });
        // ncFileOut.addVariableAttribute("Time", "long_name", "Time");
        final float referenceTime = setTimeVariableAttributes(time_0, ncFileOut);
        // lat Variable
        ArrayFloat lat_1_Data = new ArrayFloat(new int[] { latDim0.getLength() });
        Index lat_1_Index = lat_1_Data.getIndex();
        ncFileOut.addVariable(NetCDFUtilities.LAT, DataType.FLOAT, new Dimension[] { latDim });
        ncFileOut.addVariableAttribute(NetCDFUtilities.LAT, "long_name", NetCDFUtilities.LATITUDE);
        ncFileOut.addVariableAttribute(NetCDFUtilities.LAT, UNITS, lat_0.getUnitsString());
        for (int yPos = 0; yPos < latDim0.getLength(); yPos++) {
            lat_1_Data.setFloat(lat_1_Index.set(yPos), new Float(this.ymax - (new Float(yPos).floatValue() * this.periodY)).floatValue());
        // new Float(
        // this.ymin
        // + (new Float(yPos)
        // .floatValue() * this.periodY))
        // .floatValue());
        }
        // lon Variable
        ArrayFloat lon_1_Data = new ArrayFloat(new int[] { lonDim0.getLength() });
        Index lon_1_Index = lon_1_Data.getIndex();
        ncFileOut.addVariable(NetCDFUtilities.LON, DataType.FLOAT, new Dimension[] { lonDim });
        ncFileOut.addVariableAttribute(NetCDFUtilities.LON, "long_name", NetCDFUtilities.LONGITUDE);
        ncFileOut.addVariableAttribute(NetCDFUtilities.LON, UNITS, lon_0.getUnitsString());
        for (int xPos = 0; xPos < lonDim0.getLength(); xPos++) {
            lon_1_Data.setFloat(lon_1_Index.set(xPos), new Float(this.xmin + (new Float(xPos).floatValue() * this.periodX)).floatValue());
        }
        // depth level Variable
        ArrayFloat depthlevelDim_1_Data = new ArrayFloat(new int[] { depthDim.getLength() });
        Index depthlevelDim_1_Index = depthlevelDim_1_Data.getIndex();
        ncFileOut.addVariable(NetCDFUtilities.DEPTH, DataType.FLOAT, new Dimension[] { depthDim });
        ncFileOut.addVariableAttribute(NetCDFUtilities.DEPTH, "long_name", NetCDFUtilities.DEPTH);
        ncFileOut.addVariableAttribute(NetCDFUtilities.DEPTH, UNITS, z_0.getUnitsString());
        ncFileOut.addVariableAttribute(NetCDFUtilities.DEPTH, "positive", "up");
        for (int wPos = 0; wPos < depthDim.getLength(); wPos++) {
            depthlevelDim_1_Data.setFloat(depthlevelDim_1_Index.set(wPos), z_0_Data.getFloat(depthlevelDim_1_Index));
        }
        // {} Variables
        for (int i = 0; i < NUMVARS; i++) {
            String varName = variables.get(i);
            Variable var = ncFileIn.findVariable(varName);
            ncFileOut.addVariable(varName, var.getDataType(), new Dimension[] { timeDim, depthDim, latDim, lonDim });
            NetCDFConverterUtilities.setVariableAttributes(var, ncFileOut, new String[] { "positions" });
        }
        // writing bin data ...
        ncFileOut.create();
        ArrayFloat timeData = new ArrayFloat(new int[] { timeDim.getLength() });
        Index timeIndex = timeData.getIndex();
        for (int t = 0; t < timeDim.getLength(); t++) {
            float julianTime = time_0_Data.getFloat(time_0_Index.set(t)) - referenceTime;
            timeData.setFloat(timeIndex.set(t), julianTime);
        }
        ncFileOut.write("time", timeData);
        Variable timeVar = ncFileOut.findVariable("time");
        timeDim.addCoordinateVariable(timeVar);
        ncFileOut.write(NetCDFUtilities.LAT, lat_1_Data);
        ncFileOut.write(NetCDFUtilities.LON, lon_1_Data);
        Variable depthVar = ncFileOut.findVariable("depth");
        depthDim.addCoordinateVariable(depthVar);
        ncFileOut.write(NetCDFUtilities.DEPTH, depthlevelDim_1_Data);
        // TODO: AutoApply MASK?
        ArrayFloat maskMatrix = new ArrayFloat.D2(latDim.getLength(), lonDim.getLength());
        Index maskIma = maskMatrix.getIndex();
        if (APPLY_MASK) {
            Variable mask = ncFileIn.findVariable("mask");
            Array maskData = mask.read();
            Index maskIndex = maskData.getIndex();
            ArrayFloat tempData = new ArrayFloat(new int[] { latDim0.getLength(), lonDim0.getLength() });
            Index tempIndex = tempData.getIndex();
            for (int yPos = 0; yPos < latDim0.getLength(); yPos++) {
                for (int xPos = 0; xPos < lonDim0.getLength(); xPos++) {
                    tempData.setFloat(tempIndex.set(yPos, xPos), maskData.getFloat(maskIndex.set(yPos, xPos)));
                }
            }
            WritableRaster outData = this.Resampler(lat_0_Data, lon_0_Data, lonDim0.getLength(), latDim0.getLength(), 2, tempData, -1);
            for (int j = 0; j < latDim0.getLength(); j++) {
                for (int k = 0; k < lonDim0.getLength(); k++) {
                    float sample = outData.getSampleFloat(k, j, 0);
                    maskMatrix.setFloat(maskIma.set(j, k), sample);
                }
            }
        }
        for (int i = 0; i < NUMVARS; i++) {
            String varName = variables.get(i);
            Variable var = ncFileIn.findVariable(varName);
            Array originalVarData = var.read();
            Index varIndex = originalVarData.getIndex();
            Attribute fv = var.findAttribute("_FillValue");
            float fillValue = Float.NaN;
            if (fv != null) {
                fillValue = (fv.getNumericValue()).floatValue();
            }
            ArrayFloat T_tmp_Data = new ArrayFloat(new int[] { latDim0.getLength(), lonDim0.getLength() });
            Index T_tmp_Index = T_tmp_Data.getIndex();
            ArrayFloat Tmatrix = new ArrayFloat.D4(timeDim.getLength(), depthDim.getLength(), latDim.getLength(), lonDim.getLength());
            Index Tima = Tmatrix.getIndex();
            for (int tPos = 0; tPos < timeDim0.getLength(); tPos++) {
                for (int levelPos = 0; levelPos < depthDim.getLength(); levelPos++) {
                    for (int yPos = 0; yPos < latDim0.getLength(); yPos++) {
                        for (int xPos = 0; xPos < lonDim0.getLength(); xPos++) {
                            T_tmp_Data.setFloat(T_tmp_Index.set(yPos, xPos), originalVarData.getFloat(varIndex.set(tPos, yPos, xPos, levelPos)));
                        }
                    }
                    WritableRaster outData = this.Resampler(lat_0_Data, lon_0_Data, lonDim0.getLength(), latDim0.getLength(), 2, T_tmp_Data, fillValue);
                    for (int j = 0; j < latDim0.getLength(); j++) {
                        for (int k = 0; k < lonDim0.getLength(); k++) {
                            float sample = outData.getSampleFloat(k, j, 0);
                            if (APPLY_MASK) {
                                float maskValue = maskMatrix.getFloat(maskIma.set(j, k));
                                if (maskValue == 0)
                                    sample = fillValue;
                            }
                            Tmatrix.setFloat(Tima.set(tPos, levelPos, j, k), sample);
                        }
                    }
                }
            }
            ncFileOut.write(varName, Tmatrix);
        }
        ncFileOut.close();
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}
Also used : NetcdfFileWriteable(ucar.nc2.NetcdfFileWriteable) Variable(ucar.nc2.Variable) Attribute(ucar.nc2.Attribute) Index(ucar.ma2.Index) ArrayFloat(ucar.ma2.ArrayFloat) Dimension(ucar.nc2.Dimension) IOException(java.io.IOException) NetcdfFile(ucar.nc2.NetcdfFile) Array(ucar.ma2.Array) ArrayFloat(ucar.ma2.ArrayFloat) WritableRaster(java.awt.image.WritableRaster)

Aggregations

Array (ucar.ma2.Array)10 ArrayFloat (ucar.ma2.ArrayFloat)10 Variable (ucar.nc2.Variable)9 Index (ucar.ma2.Index)8 WritableRaster (java.awt.image.WritableRaster)7 IOException (java.io.IOException)7 Dimension (ucar.nc2.Dimension)7 NetcdfFile (ucar.nc2.NetcdfFile)7 NetcdfFileWriteable (ucar.nc2.NetcdfFileWriteable)7 Attribute (ucar.nc2.Attribute)6 File (java.io.File)5 ArrayList (java.util.ArrayList)4 ArrayInt (ucar.ma2.ArrayInt)4 ArrayShort (ucar.ma2.ArrayShort)4 ArrayByte (ucar.ma2.ArrayByte)3 ArrayDouble (ucar.ma2.ArrayDouble)3 DataType (ucar.ma2.DataType)3 Point (java.awt.Point)2 Rectangle (java.awt.Rectangle)2 BandedSampleModel (java.awt.image.BandedSampleModel)2