Java Code Examples for javax.media.jai.iterator.RandomIter#done()

The following examples show how to use javax.media.jai.iterator.RandomIter#done() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Transform a rendered image in its array representation.
 * 
 * @param renderedImage the rendered image to transform.
 * @param bandNumber the the number of the band to consider..
 * @return the array holding the data.
 */
public static double[] renderedImage2DoubleArray( RenderedImage renderedImage, int bandNumber ) {
    int width = renderedImage.getWidth();
    int height = renderedImage.getHeight();

    double[] values = new double[width * height];
    RandomIter imageIter = RandomIterFactory.create(renderedImage, null);
    int index = 0;;
    for( int x = 0; x < width; x++ ) {
        for( int y = 0; y < height; y++ ) {
            double sample = imageIter.getSampleDouble(x, y, bandNumber);
            values[index++] = sample;
        }
    }
    imageIter.done();
    return values;
}
 
Example 2
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Replace the current internal novalue with a given value.
 * 
 * @param renderedImage a {@link RenderedImage}.
 * @param newValue the value to put in instead of the novalue.
 * @return the rendered image with the substituted novalue. 
 */
public static WritableRaster replaceNovalue( RenderedImage renderedImage, double newValue ) {
    WritableRaster tmpWR = (WritableRaster) renderedImage.getData();
    RandomIter pitTmpIterator = RandomIterFactory.create(renderedImage, null);

    int height = renderedImage.getHeight();
    int width = renderedImage.getWidth();
    for( int y = 0; y < height; y++ ) {
        for( int x = 0; x < width; x++ ) {
            if (isNovalue(pitTmpIterator.getSampleDouble(x, y, 0))) {
                tmpWR.setSample(x, y, 0, newValue);
            }
        }
    }
    pitTmpIterator.done();
    return tmpWR;
}
 
Example 3
Source File: OmsHillshade.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
protected WritableRaster normalVector( WritableRaster pitWR, double res ) {
    int minX = pitWR.getMinX();
    int minY = pitWR.getMinY();
    int rows = pitWR.getHeight();
    int cols = pitWR.getWidth();

    RandomIter pitIter = RandomIterFactory.create(pitWR, null);
    /*
     * Initialize the Image of the normal vector in the central point of the
     * cells, which have 3 components so the Image have 3 bands..
     */
    SampleModel sm = RasterFactory.createBandedSampleModel(5, cols, rows, 3);
    WritableRaster tmpNormalVectorWR = CoverageUtilities.createWritableRaster(cols, rows, null, sm, 0.0);
    WritableRandomIter tmpNormaIter = RandomIterFactory.createWritable(tmpNormalVectorWR, null);
    /*
     * apply the corripio's formula (is the formula (3) in the article)
     */
    for( int j = minY; j < minX + rows - 1; j++ ) {
        for( int i = minX; i < minX + cols - 1; i++ ) {
            double zij = pitIter.getSampleDouble(i, j, 0);
            double zidxj = pitIter.getSampleDouble(i + 1, j, 0);
            double zijdy = pitIter.getSampleDouble(i, j + 1, 0);
            double zidxjdy = pitIter.getSampleDouble(i + 1, j + 1, 0);
            double firstComponent = 0.5 * res * (zij - zidxj + zijdy - zidxjdy);
            double secondComponent = 0.5 * res * (zij + zidxj - zijdy - zidxjdy);
            double thirthComponent = (res * res);
            double den = Math.sqrt(firstComponent * firstComponent + secondComponent * secondComponent + thirthComponent
                    * thirthComponent);
            tmpNormaIter.setPixel(i, j, new double[]{firstComponent / den, secondComponent / den, thirthComponent / den});

        }
    }
    pitIter.done();

    return tmpNormalVectorWR;

}
 
Example 4
Source File: OmsHackLength.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Execute
public void process() {
    if (!concatOr(outHacklength == null, doReset)) {
        return;
    }
    checkNull(inFlow, inTca);

    regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inFlow);
    nCols = regionMap.getCols();
    nRows = regionMap.getRows();
    xRes = regionMap.getXres();
    yRes = regionMap.getYres();

    RandomIter tcaIter = CoverageUtilities.getRandomIterator(inTca);

    RenderedImage flowRI = inFlow.getRenderedImage();
    WritableRaster flowWR = CoverageUtilities.renderedImage2WritableRaster(flowRI, true);
    WritableRandomIter flowIter = RandomIterFactory.createWritable(flowWR, null);

    // if inElevation isn't null then work in 3d.
    RandomIter elevIter = null;
    if (inElevation != null) {
        elevIter = CoverageUtilities.getRandomIterator(inElevation);
    }

    hacklength(flowIter, tcaIter, elevIter);

    tcaIter.done();
    flowIter.done();
    if (elevIter != null) {
        elevIter.done();
    }

}
 
Example 5
Source File: OmsExtractNetwork.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * this method calculates the network using a threshold value on the
 * contributing areas or on magnitudo
 * @throws Exception 
 */
private WritableRaster extractNetTcaThreshold( RenderedImage tcaRI ) throws Exception {
    RandomIter tcaIter = RandomIterFactory.create(tcaRI, null);
    WritableRaster netWR = CoverageUtilities.createWritableRaster(cols, rows, Short.class, null, shortNovalue);
    WritableRandomIter netIter = RandomIterFactory.createWritable(netWR, null);

    try {
        pm.beginTask(msg.message("extractnetwork.extracting"), rows * cols); //$NON-NLS-1$
        processGrid(cols, rows, false, ( c, r ) -> {
            if (pm.isCanceled()) {
                return;
            }
            int tcaValue = tcaIter.getSample(c, r, 0);
            if (!isNovalue(tcaValue)) {
                if (tcaValue >= pThres) { // FIXME needs power here?
                    netIter.setSample(c, r, 0, NETVALUE);
                }
            }
            pm.worked(1);
        });
        pm.done();
        return netWR;
    } finally {
        netIter.done();
        tcaIter.done();
    }
}
 
Example 6
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Calculates the profile of a raster map between given {@link Coordinate coordinates}.
 * 
 * @param coverage the coverage from which to extract the profile.
 * @param coordinates the coordinates to use to trace the profile.
 * @return the list of {@link ProfilePoint}s.
 * @throws Exception
 */
public static List<ProfilePoint> doProfile( GridCoverage2D coverage, Coordinate... coordinates ) throws Exception {
    GridGeometry2D gridGeometry = coverage.getGridGeometry();
    RenderedImage renderedImage = coverage.getRenderedImage();
    RandomIter iter = RandomIterFactory.create(renderedImage, null);

    List<ProfilePoint> profilePointsList = doProfile(iter, gridGeometry, coordinates);

    iter.done();
    return profilePointsList;
}
 
Example 7
Source File: PrintUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Print data of a {@link GridCoverage2D} as java matrix definition.
 * 
 * @param coverage
 *            the coverage.
 */
public static void printCoverageDataAsMatrix( GridCoverage2D coverage ) {
    printer.println("double[][] matrix = new double[][]{//");
    RenderedImage renderedImage = coverage.getRenderedImage();
    RandomIter renderedImageIterator = RandomIterFactory.create(renderedImage, null);
    int[] colsRows = CoverageUtilities.getRegionColsRows(coverage);
    for( int r = 0; r < colsRows[1]; r++ ) {
        if (r == 0) {
            printer.print("/*    */{");
        } else {
            printer.print("{");
        }
        for( int c = 0; c < colsRows[0]; c++ ) {
            printer.print(renderedImageIterator.getSampleDouble(c, r, 0));
            if (c < colsRows[0] - 1) {
                printer.print(", ");
            }
        }
        if (r < colsRows[1] - 1) {
            printer.println("}, //");
        } else {
            printer.println("} //");
        }
    }
    printer.println("};");
    renderedImageIterator.done();
}
 
Example 8
Source File: OmsNetNumbering.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Execute
public void process() throws Exception {
    if (!concatOr(outNetnum == null, doReset)) {
        return;
    }
    checkNull(inFlow, inNet);
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inFlow);
    int nCols = regionMap.getCols();
    int nRows = regionMap.getRows();

    RenderedImage flowRI = inFlow.getRenderedImage();
    WritableRaster flowWR = CoverageUtilities.renderedImage2IntWritableRaster(flowRI, true);
    WritableRandomIter flowIter = RandomIterFactory.createWritable(flowWR, null);
    RandomIter netIter = CoverageUtilities.getRandomIterator(inNet);

    WritableRandomIter netNumIter = null;
    try {
        WritableRaster netNumWR = ModelsEngine.netNumbering(inFlow, inNet, inTca, pThres, inPoints, pm);

        netNumIter = RandomIterFactory.createWritable(netNumWR, null);
        WritableRaster basinWR = ModelsEngine.extractSubbasins(flowIter, netIter, netNumIter, nRows, nCols, pm);

        outNetnum = CoverageUtilities.buildCoverage("netnum", netNumWR, regionMap, inFlow.getCoordinateReferenceSystem());
        outBasins = CoverageUtilities.buildCoverage("subbasins", basinWR, regionMap, inFlow.getCoordinateReferenceSystem());
    } finally {
        flowIter.done();
        netIter.done();
        if (netNumIter != null)
            netNumIter.done();
    }
}
 
Example 9
Source File: PrintUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Print data from a {@link Raster}.
 * 
 * @param raster
 *            the image.
 */
public static void printWritableRasterData( Raster raster ) {
    RandomIter iter = RandomIterFactory.create(raster, null);
    int cols = raster.getWidth();
    int rows = raster.getHeight();
    for( int r = 0; r < rows; r++ ) {
        for( int c = 0; c < cols; c++ ) {
            printer.print(iter.getSampleDouble(c, r, 0));
            printer.print(separator);
        }
        printer.println();
    }
    iter.done();
}
 
Example 10
Source File: HMModelIM.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private void freeIterators() {
    for( RandomIter inRasterIterator : inRasterIterators ) {
        if (inRasterIterator != null)
            inRasterIterator.done();
    }
    for( RandomIter outRasterIterator : outRasterIterators ) {
        if (outRasterIterator != null)
            outRasterIterator.done();
    }
}
 
Example 11
Source File: OmsRasterReader.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private void checkNovalues() {
    // TODO make this nice, this can't be the way
    if (fileNovalue == null || geodataNovalue == null) {
        return;
    }
    if (isNovalue(internalFileNovalue) && isNovalue(internalGeodataNovalue)) {
        return;
    }
    if (!NumericsUtilities.dEq(internalFileNovalue, internalGeodataNovalue)) {
        HashMap<String, Double> params = getRegionParamsFromGridCoverage(outRaster);
        int height = params.get(ROWS).intValue();
        int width = params.get(COLS).intValue();
        WritableRaster tmpWR = createWritableRaster(width, height, null, null, null);
        WritableRandomIter tmpIter = RandomIterFactory.createWritable(tmpWR, null);
        RenderedImage readRI = outRaster.getRenderedImage();
        RandomIter readIter = RandomIterFactory.create(readRI, null);
        int minX = readRI.getMinX();
        int minY = readRI.getMinY();
        for( int r = 0; r < height; r++ ) {
            for( int c = 0; c < width; c++ ) {
                double value = readIter.getSampleDouble(c + minX, r + minY, 0);
                if (isNovalue(value) || value == internalFileNovalue || value == -Float.MAX_VALUE
                        || value == Float.MAX_VALUE) {
                    tmpIter.setSample(c, r, 0, internalGeodataNovalue);
                } else {
                    tmpIter.setSample(c, r, 0, value);
                }
            }
        }
        readIter.done();
        tmpIter.done();
        outRaster = buildCoverage(new File(file).getName(), tmpWR, params, outRaster.getCoordinateReferenceSystem());
    }
}
 
Example 12
Source File: OmsAb.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    if (!concatOr(outAb == null, doReset)) {
        return;
    }
    checkNull(inTca, inPlan);
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inTca);
    int nCols = regionMap.getCols();
    int nRows = regionMap.getRows();
    double xRes = regionMap.getXres();

    RandomIter tcaIter = CoverageUtilities.getRandomIterator(inTca);
    RandomIter planIter = CoverageUtilities.getRandomIterator(inPlan);

    WritableRaster alungWR = CoverageUtilities.createWritableRaster(nCols, nRows, null, null, null);
    WritableRandomIter alungIter = RandomIterFactory.createWritable(alungWR, null);
    WritableRaster bWR = CoverageUtilities.createWritableRaster(nCols, nRows, null, null, null);
    WritableRandomIter bIter = RandomIterFactory.createWritable(bWR, null);

    try {
        pm.beginTask(msg.message("ab.calculating"), nRows * nCols);
        processGrid(nCols, nRows, ( c, r ) -> {
            if (pm.isCanceled()) {
                return;
            }

            double planSample = planIter.getSampleDouble(c, r, 0);
            if (!isNovalue(planSample) && planSample != 0.0) {
                if (xRes > 1 / planSample && planSample >= 0.0) {
                    bIter.setSample(c, r, 0, 0.1 * xRes);
                } else if (xRes > Math.abs(1 / planSample) && planSample < 0.0) {
                    bIter.setSample(c, r, 0, xRes + 0.9 * xRes);
                } else {
                    double bSample = 2 * Math.asin(xRes / (2 * (1 / planSample))) * (1 / planSample - xRes);
                    bIter.setSample(c, r, 0, bSample);
                    if (planSample >= 0.0 && bSample < 0.1 * xRes) {
                        bIter.setSample(c, r, 0, 0.1 * xRes);
                    }
                    if (planSample < 0.0 && bSample > (xRes + 0.9 * xRes)) {
                        bIter.setSample(c, r, 0, xRes + 0.9 * xRes);
                    }
                }
            }
            if (planSample == 0.0) {
                bIter.setSample(c, r, 0, xRes);
            }
            alungIter.setSample(c, r, 0, tcaIter.getSample(c, r, 0) * xRes * xRes / bIter.getSampleDouble(c, r, 0));
            if (isNovalue(planSample)) {
                alungIter.setSample(c, r, 0, doubleNovalue);
                bIter.setSample(c, r, 0, doubleNovalue);
            }

            pm.worked(1);
        });
        pm.done();
    } finally {
        tcaIter.done();
        planIter.done();
        alungIter.done();
        bIter.done();
    }
    outAb = CoverageUtilities.buildCoverage("alung", alungWR, regionMap, inTca.getCoordinateReferenceSystem());
    outB = CoverageUtilities.buildCoverage("b", bWR, regionMap, inTca.getCoordinateReferenceSystem());
}
 
Example 13
Source File: OmsExtractBasin.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    if (!concatOr(outBasin == null, doReset)) {
        return;
    }
    checkNull(inFlow);

    crs = inFlow.getCoordinateReferenceSystem();

    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inFlow);
    ncols = regionMap.getCols();
    nrows = regionMap.getRows();
    double xRes = regionMap.getXres();
    double yRes = regionMap.getYres();
    double north = regionMap.getNorth();
    double west = regionMap.getWest();
    double south = regionMap.getSouth();
    double east = regionMap.getEast();

    if (pNorth == -1 || pEast == -1) {
        throw new ModelsIllegalargumentException("No outlet coordinates were supplied.", this.getClass().getSimpleName(), pm);
    }
    if (pNorth > north || pNorth < south || pEast > east || pEast < west) {
        throw new ModelsIllegalargumentException("The outlet point lies outside the map region.",
                this.getClass().getSimpleName(), pm);
    }

    Coordinate snapOutlet = snapOutlet();
    if (snapOutlet != null) {
        pEast = snapOutlet.x;
        pNorth = snapOutlet.y;
    }

    RandomIter flowIter = CoverageUtilities.getRandomIterator(inFlow);
    WritableRaster basinWR = CoverageUtilities.createWritableRaster(ncols, nrows, Short.class, null, shortNovalue);
    WritableRandomIter basinIter = RandomIterFactory.createWritable(basinWR, null);

    try {
        Coordinate outlet = new Coordinate(pEast, pNorth);

        int[] outletColRow = CoverageUtilities.colRowFromCoordinate(outlet, inFlow.getGridGeometry(), null);

        int outletFlow = flowIter.getSample(outletColRow[0], outletColRow[1], 0);
        if (isNovalue(outletFlow)) {
            throw new IllegalArgumentException("The chosen outlet point doesn't have a valid value.");
        }

        FlowNode runningNode = new FlowNode(flowIter, ncols, nrows, outletColRow[0], outletColRow[1]);
        runningNode.setIntValueInMap(basinIter, 1);
        outArea++;

        ConcurrentLinkedQueue<FlowNode> enteringNodes = new ConcurrentLinkedQueue<>(runningNode.getEnteringNodes());
        pm.beginTask(msg.message("wateroutlet.extracting"), -1);
        while( enteringNodes.size() > 0 ) {
            if (pm.isCanceled()) {
                return;
            }

            ConcurrentLinkedQueue<FlowNode> newEnteringNodes = new ConcurrentLinkedQueue<>();
            enteringNodes.parallelStream().forEach(flowNode -> {
                if (pm.isCanceled()) {
                    return;
                }
                if (!alreadyWarned && flowNode.touchesBound()) {
                    pm.errorMessage(MessageFormat.format(
                            "WARNING: touched boundaries in col/row = {0}/{1}. You might consider to review your processing region.",
                            flowNode.col, flowNode.row));
                    alreadyWarned = true;
                }
                flowNode.setIntValueInMap(basinIter, 1);
                outArea++;

                List<FlowNode> newEntering = flowNode.getEnteringNodes();
                newEnteringNodes.addAll(newEntering);
            });
            enteringNodes = newEnteringNodes;
        }
        pm.done();

        outArea = outArea * xRes * yRes;
        outBasin = CoverageUtilities.buildCoverage("basin", basinWR, regionMap, crs);

        extractVectorBasin();
    } finally {
        flowIter.done();
        basinIter.done();
    }
}
 
Example 14
Source File: OmsTc.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    if (!concatOr(outTc3 == null, outTc9 == null, doReset)) {
        return;
    }

    checkNull(inProf, inTan);

    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inProf);
    int cols = regionMap.getCols();
    int rows = regionMap.getRows();

    WritableRaster tc3WR = CoverageUtilities.createWritableRaster(cols, rows, null, null, doubleNovalue);
    WritableRaster tc9WR = CoverageUtilities.createWritableRaster(cols, rows, null, null, doubleNovalue);
    WritableRandomIter tc3Iter = RandomIterFactory.createWritable(tc3WR, null);
    WritableRandomIter tc9Iter = RandomIterFactory.createWritable(tc9WR, null);
    
    RandomIter profIter = CoverageUtilities.getRandomIterator(inProf);
    RandomIter tangIter = CoverageUtilities.getRandomIterator(inTan);

    // calculate ...
    pm.beginTask(msg.message("working") + "tc9...", rows); //$NON-NLS-1$ //$NON-NLS-2$
    for( int j = 0; j < rows; j++ ) {
        for( int i = 0; i < cols; i++ ) {
            double tangValue = tangIter.getSampleDouble(i, j, 0);
            if (isNovalue(tangValue)) {
                tc9Iter.setSample(i, j, 0, HMConstants.doubleNovalue);
            } else {
                double profValue = profIter.getSampleDouble(i, j, 0);
                if (Math.abs(tangValue) <= pTanthres) {
                    if (Math.abs(profValue) <= pProfthres) {
                        tc9Iter.setSample(i, j, 0, 10);
                    } else if (profValue < -pProfthres) {
                        tc9Iter.setSample(i, j, 0, 20);
                    } else if (profValue > pProfthres) {
                        tc9Iter.setSample(i, j, 0, 30);
                    }
                } else if (tangValue < -pTanthres) {
                    if (Math.abs(profValue) <= pProfthres) {
                        tc9Iter.setSample(i, j, 0, 40);
                    } else if (profValue < -pProfthres) {
                        tc9Iter.setSample(i, j, 0, 50);
                    } else if (profValue > pProfthres) {
                        tc9Iter.setSample(i, j, 0, 60);
                    }
                } else if (tangValue > pTanthres) {
                    if (Math.abs(profValue) <= pProfthres) {
                        tc9Iter.setSample(i, j, 0, 70);
                    } else if (profValue < -pProfthres) {
                        tc9Iter.setSample(i, j, 0, 80);
                    } else if (profValue > pProfthres) {
                        tc9Iter.setSample(i, j, 0, 90);
                    }
                }
            }
        }
        pm.worked(1);
    }
    pm.done();
    
    profIter.done();
    tangIter.done();

    pm.beginTask(msg.message("working") + "tc3...", rows); //$NON-NLS-1$ //$NON-NLS-2$
    for( int j = 0; j < rows; j++ ) {
        for( int i = 0; i < cols; i++ ) {
            double cp9Value = tc9Iter.getSampleDouble(i, j, 0);
            if (!isNovalue(cp9Value)) {
                if (cp9Value == 70 || cp9Value == 90 || cp9Value == 30) {
                    tc3Iter.setSample(i, j, 0, 15);
                } else if (cp9Value == 10) {
                    tc3Iter.setSample(i, j, 0, 25);
                } else {
                    tc3Iter.setSample(i, j, 0, 35);
                }
            } else {
                tc3Iter.setSample(i, j, 0, cp9Value);
            }
        }
        pm.worked(1);
    }
    pm.done();

    outTc3 = CoverageUtilities.buildCoverage("tc3", tc3WR, regionMap, inProf.getCoordinateReferenceSystem()); //$NON-NLS-1$
    outTc9 = CoverageUtilities.buildCoverage("tc9", tc9WR, regionMap, inProf.getCoordinateReferenceSystem()); //$NON-NLS-1$

}
 
Example 15
Source File: OmsH2cA.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() {
    if (!concatOr(outAttribute == null, doReset)) {
        return;
    }
    checkNull(inFlow, inNet, inAttribute);

    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inFlow);
    int cols = regionMap.getCols();
    int rows = regionMap.getRows();

    RenderedImage flowRI = inFlow.getRenderedImage();
    WritableRaster flowWR = CoverageUtilities.renderedImage2WritableRaster(flowRI, true);
    WritableRandomIter flowIter = RandomIterFactory.createWritable(flowWR, null);
    RandomIter attributeIter = CoverageUtilities.getRandomIterator(inAttribute);
    RandomIter netIter = CoverageUtilities.getRandomIterator(inNet);

    pm.beginTask("Marking the network...", rows); //$NON-NLS-1$
    /*
     * mark network as outlet, in order to easier stop on the net 
     * while going downstream
     */
    for( int j = 0; j < rows; j++ ) {
        for( int i = 0; i < cols; i++ ) {
            if (netIter.getSampleDouble(i, j, 0) == FlowNode.NETVALUE)
                flowIter.setSample(i, j, 0, FlowNode.OUTLET);
        }
        pm.worked(1);
    }
    pm.done();
    netIter.done();

    WritableRaster h2caWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, doubleNovalue);
    WritableRandomIter h2caIter = RandomIterFactory.createWritable(h2caWR, null);

    ModelsEngine.markHillSlopeWithLinkValue(flowIter, attributeIter, h2caIter, cols, rows, pm);

    h2caIter.done();
    attributeIter.done();
    flowIter.done();

    outAttribute = CoverageUtilities.buildCoverage("h2ca", h2caWR, regionMap, inFlow.getCoordinateReferenceSystem());

}
 
Example 16
Source File: OmsTca.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    if (!concatOr(outTca == null, doReset)) {
        return;
    }
    checkNull(inFlow);

    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inFlow);
    int cols = regionMap.getCols();
    int rows = regionMap.getRows();

    RenderedImage flowRI = inFlow.getRenderedImage();
    WritableRaster tcaWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, doubleNovalue);

    RandomIter flowIter = RandomIterFactory.create(flowRI, null);
    WritableRandomIter tcaIter = RandomIterFactory.createWritable(tcaWR, null);

    pm.beginTask("Calculating tca...", rows); //$NON-NLS-1$
    for( int r = 0; r < rows; r++ ) {
        for( int c = 0; c < cols; c++ ) {
            FlowNode flowNode = new FlowNode(flowIter, cols, rows, c, r);
            if (flowNode.isSource()) {
                double previousTcaValue = 0.0;
                while( flowNode != null && flowNode.isValid() ) {
                    int col = flowNode.col;
                    int row = flowNode.row;
                    double tmpTca = tcaIter.getSampleDouble(col, row, 0);
                    double newTcaValue;
                    /*
                     * cumulate only if first time passing, else
                     * just propagate 
                     */
                    if (isNovalue(tmpTca)) {
                        tmpTca = 1.0;
                        newTcaValue = tmpTca + previousTcaValue;
                        previousTcaValue = newTcaValue;
                    } else {
                        newTcaValue = tmpTca + previousTcaValue;
                    }
                    tcaIter.setSample(col, row, 0, newTcaValue);
                    flowNode = flowNode.goDownstream();
                }
            }
        }
        pm.worked(1);
    }
    pm.done();
    flowIter.done();
    tcaIter.done();

    outTca = CoverageUtilities.buildCoverage("tca", tcaWR, regionMap, inFlow.getCoordinateReferenceSystem());
}
 
Example 17
Source File: OmsRescaledDistance.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    if (!concatOr(outRescaled == null, doReset)) {
        return;
    }
    checkNull(inFlow, inNet);
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inFlow);
    int cols = regionMap.getCols();
    int rows = regionMap.getRows();
    xRes = regionMap.getXres();
    yRes = regionMap.getYres();

    RenderedImage flowRI = inFlow.getRenderedImage();
    RandomIter flowIter = RandomIterFactory.create(flowRI, null);

    RenderedImage netRI = inNet.getRenderedImage();
    RandomIter netIter = RandomIterFactory.create(netRI, null);

    if (inElev != null) {
        RenderedImage elevRI = inElev.getRenderedImage();
        elevIter = RandomIterFactory.create(elevRI, null);
    }

    WritableRaster rescaledWR = CoverageUtilities.createWritableRaster(cols, rows, Float.class, null, floatNovalue);
    WritableRandomIter rescaledIter = RandomIterFactory.createWritable(rescaledWR, null);

    try {
        pm.beginTask("Find outlets...", rows * cols); //$NON-NLS-1$
        ConcurrentLinkedQueue<FlowNode> exitsList = new ConcurrentLinkedQueue<>();
        processGrid(cols, rows, ( c, r ) -> {
            if (pm.isCanceled())
                return;
            int netValue = netIter.getSample(c, r, 0);
            if (isNovalue(netValue)) {
                // we make sure that we pick only outlets that are on the net
                return;
            }
            FlowNode flowNode = new FlowNode(flowIter, cols, rows, c, r);
            if (flowNode.isHeadingOutside()) {
                exitsList.add(flowNode);
            }
            pm.worked(1);
        });
        pm.done();

        if (exitsList.size() == 0) {
            throw new ModelsIllegalargumentException("No exits found in the map of flowdirections.", this);
        }

        pm.beginTask("Calculate rescaled distance...", exitsList.size());
        exitsList.parallelStream().forEach(exitNode -> {
            if (pm.isCanceled())
                return;
            calculateRescaledDistance(exitNode, (float) xRes, rescaledIter, elevIter, netIter);
            pm.worked(1);
        });
        pm.done();
    } finally {
        rescaledIter.done();
        netIter.done();
        if (elevIter != null)
            elevIter.done();
    }

    outRescaled = CoverageUtilities.buildCoverage("OmsRescaledDistance", rescaledWR, regionMap,
            inFlow.getCoordinateReferenceSystem());
}
 
Example 18
Source File: OmsRasterDiff.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
    public void process() throws Exception {
        checkNull(inRaster1, inRaster2);

        double thres = 0.0;
        if (pThreshold != null) {
            thres = pThreshold;
        }

        RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inRaster1);
        int cols = regionMap.getCols();
        int rows = regionMap.getRows();

        RandomIter r1Iter = CoverageUtilities.getRandomIterator(inRaster1);
        RandomIter r2Iter = CoverageUtilities.getRandomIterator(inRaster2);

        WritableRaster outWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, doubleNovalue);
        WritableRandomIter outIter = RandomIterFactory.createWritable(outWR, null);

        pm.beginTask("Subtracting raster...", cols);
        for( int r = 0; r < rows; r++ ) {
            for( int c = 0; c < cols; c++ ) {
                double r1 = r1Iter.getSampleDouble(c, r, 0);
                double r2 = r2Iter.getSampleDouble(c, r, 0);
                double diff;
                if (isNovalue(r1) && isNovalue(r2)) {
                    continue;
                } else if (isNovalue(r1)) {
                    diff = r2;
                } else if (isNovalue(r2)) {
                    diff = r1;
                } else {
                    diff = r1 - r2;
                }
                if (!doNegatives && diff < 0) {
                    diff = 0.0;
//                    diff = doubleNovalue;
                }
                if (pThreshold != null && diff < thres) {
                    diff = doubleNovalue;
                }
                outIter.setSample(c, r, 0, diff);
            }
            pm.worked(1);
        }
        pm.done();

        r1Iter.done();
        r2Iter.done();
        outIter.done();

        outRaster = CoverageUtilities.buildCoverage("corrected", outWR, regionMap, inRaster1.getCoordinateReferenceSystem());
    }
 
Example 19
Source File: OmsHoughCirclesRasterCleaner.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Execute
public void process() throws Exception {
    checkNull(inVector, pMaxOverlap, inRaster);

    RandomIter rasterIter = CoverageUtilities.getRandomIterator(inRaster);
    GridGeometry2D gridGeometry = inRaster.getGridGeometry();
    double[] tm_utm_tac = new double[3];

    STRtree circlesTree = FeatureUtilities.featureCollectionToSTRtree(inVector);
    List<SimpleFeature> circlesList = FeatureUtilities.featureCollectionToList(inVector);

    DefaultFeatureCollection outFC = new DefaultFeatureCollection();

    for( SimpleFeature circleFeature : circlesList ) {
        Geometry geometry = (Geometry) circleFeature.getDefaultGeometry();
        Polygon circle = (Polygon) geometry.getGeometryN(0);
        PreparedGeometry preparedCircle = PreparedGeometryFactory.prepare(circle);

        List<SimpleFeature> circlesAround = circlesTree.query(circle.getEnvelopeInternal());
        List<Geometry> intersectedCircles = new ArrayList<Geometry>();
        for( SimpleFeature circleAround : circlesAround ) {
            if (circleAround.equals(circleFeature)) {
                continue;
            }
            Geometry circleAroundGeometry = (Geometry) circleAround.getDefaultGeometry();
            if (preparedCircle.intersects(circleAroundGeometry)) {
                intersectedCircles.add(circleAroundGeometry);
            }
        }

        Point centroid = circle.getCentroid();
        int intersectionsCount = intersectedCircles.size();
        if (intersectionsCount != 0) {
            // check how many circles overlapped
            if (intersectionsCount > pMaxOverlapCount) {
                continue;
            }
            // check if the circles overlap too much, i.e. cover their baricenter
            boolean intersected = false;
            for( Geometry intersectedCircle : intersectedCircles ) {
                if (intersectedCircle.intersects(centroid)) {
                    intersected = true;
                    break;
                }
            }
            if (intersected) {
                continue;
            }
        }
        // check if the center has a raster value, i.e. is not empty
        double value = CoverageUtilities.getValue(inRaster, centroid.getCoordinate());
        if (!HMConstants.isNovalue(value)) {
            continue;
        }

        // check if the inner part of the circle is indeed rather empty

        // min, max, mean, var, sdev, activeCellCount, passiveCellCount
        double[] stats = OmsZonalStats.polygonStats(circle, gridGeometry, rasterIter, false, tm_utm_tac, 0, pm);
        // if we have many more active cells than passive cells, that is not a circle
        double activeCells = stats[5];
        double novalues = stats[6];
        if (activeCells * 1.5 > novalues) {
            continue;
        }

        // take it as valid circle
        outFC.add(circleFeature);
    }
    outCircles = outFC;

    rasterIter.done();
}
 
Example 20
Source File: OmsCarver.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
private void simpleMode() throws Exception {
    int cols = regionMap.getCols();
    int rows = regionMap.getRows();

    GridCoverage2D depthLinesRaster = null;
    GridCoverage2D depthPolygonsRaster = null;

    if (inCarverLines != null) {
        OmsLinesRasterizer lr = new OmsLinesRasterizer();
        lr.fCat = fDepthLines;
        lr.pCat = pDepthLines;
        lr.inVector = inCarverLines;
        lr.pNorth = regionMap.getNorth();
        lr.pSouth = regionMap.getSouth();
        lr.pEast = regionMap.getEast();
        lr.pWest = regionMap.getWest();
        lr.pRows = rows;
        lr.pCols = cols;
        lr.pm = pm;
        lr.process();
        depthLinesRaster = lr.outRaster;
    }
    if (inCarverPolygons != null) {
        OmsScanLineRasterizer raster = new OmsScanLineRasterizer();
        raster.inVector = inCarverPolygons;
        raster.pNorth = regionMap.getNorth();
        raster.pSouth = regionMap.getSouth();
        raster.pEast = regionMap.getEast();
        raster.pWest = regionMap.getWest();
        raster.pRows = rows;
        raster.pCols = cols;
        raster.fCat = fDepthLines;
        raster.pValue = pDepthLines;
        raster.pm = pm;
        raster.process();

        depthPolygonsRaster = raster.outRaster;
    }

    GridCoverage2D finalCarveGC = null;
    if (depthLinesRaster != null && depthPolygonsRaster != null) {
        finalCarveGC = CoverageUtilities.mergeCoverages(depthPolygonsRaster, depthLinesRaster);
    } else if (depthLinesRaster == null && depthPolygonsRaster != null) {
        finalCarveGC = depthPolygonsRaster;
    } else if (depthLinesRaster != null && depthPolygonsRaster == null) {
        finalCarveGC = depthLinesRaster;
    } else {
        throw new ModelsIllegalargumentException("At least one lines or one polygon carving layer needs to be supplied.",
                this, pm);
    }

    RandomIter dtmIter = CoverageUtilities.getRandomIterator(inRaster);
    RandomIter depthIter = CoverageUtilities.getRandomIterator(finalCarveGC);

    WritableRaster outWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, HMConstants.doubleNovalue);
    WritableRandomIter outIter = RandomIterFactory.createWritable(outWR, null);

    try {
        for( int y = 0; y < rows; y++ ) {
            for( int x = 0; x < cols; x++ ) {
                double dtmValue = dtmIter.getSampleDouble(x, y, 0);
                if (HMConstants.isNovalue(dtmValue)) {
                    continue;
                }
                double depthValue = depthIter.getSampleDouble(x, y, 0);
                double newValue;
                if (HMConstants.isNovalue(depthValue)) {
                    newValue = dtmValue;
                } else {
                    newValue = dtmValue - depthValue;
                }
                outIter.setSample(x, y, 0, newValue);
            }
        }
    } finally {
        dtmIter.done();
        depthIter.done();
        outIter.done();
    }

    outRaster = CoverageUtilities.buildCoverage("outraster", outWR, regionMap, inRaster.getCoordinateReferenceSystem());

}