Search in sources :

Example 36 with WritableRandomIter

use of javax.media.jai.iterator.WritableRandomIter in project hortonmachine by TheHortonMachine.

the class OmsHackLength method process.

@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);
    }
    int novalue = HMConstants.getIntNovalue(inFlow);
    hacklength(flowIter, novalue, tcaIter, elevIter);
    tcaIter.done();
    flowIter.done();
    if (elevIter != null) {
        elevIter.done();
    }
}
Also used : WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) WritableRaster(java.awt.image.WritableRaster) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) RenderedImage(java.awt.image.RenderedImage) Execute(oms3.annotations.Execute)

Example 37 with WritableRandomIter

use of javax.media.jai.iterator.WritableRandomIter in project hortonmachine by TheHortonMachine.

the class OmsNetDiff method netdif.

/**
 * Calculates the difference map.
 *
 * @return
 */
private WritableRaster netdif() {
    // get rows and cols from the active region
    HashMap<String, Double> regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inFlow);
    int cols = regionMap.get(CoverageUtilities.COLS).intValue();
    int rows = regionMap.get(CoverageUtilities.ROWS).intValue();
    int[] flow = new int[2];
    int[] oldflow = new int[2];
    RandomIter flowIter = CoverageUtilities.getRandomIterator(inFlow);
    RandomIter streamIter = CoverageUtilities.getRandomIterator(inStream);
    RandomIter rasterIter = CoverageUtilities.getRandomIterator(inRaster);
    int[][] dir = ModelsSupporter.DIR_WITHFLOW_ENTERING;
    // create new matrix
    double[][] segna = new double[cols][rows];
    pm.beginTask(msg.message("working") + "h.netdif", 3 * rows);
    // of a link or stream
    for (int j = 0; j < rows; j++) {
        for (int i = 0; i < cols; i++) {
            flow[0] = i;
            flow[1] = j;
            // looks for the source
            if (ModelsEngine.isSourcePixel(flowIter, flow[0], flow[1])) {
                segna[i][j] = 1;
            } else if (!isNovalue(flowIter.getSampleDouble(i, j, 0)) && flowIter.getSampleDouble(i, j, 0) != 10.0) {
                for (int k = 1; k <= 8; k++) {
                    if (flowIter.getSampleDouble(flow[0] + dir[k][1], flow[1] + dir[k][0], 0) == dir[k][2]) {
                        if (streamIter.getSampleDouble(flow[0] + dir[k][1], flow[1] + dir[k][0], 0) == streamIter.getSampleDouble(i, j, 0)) {
                            segna[i][j] = 0;
                            break;
                        } else {
                            segna[i][j] = 1;
                        }
                    }
                }
            }
        }
        pm.worked(1);
    }
    WritableRaster diffImage = CoverageUtilities.createWritableRaster(cols, rows, null, inFlow.getRenderedImage().getSampleModel(), null);
    WritableRandomIter diffIter = RandomIterFactory.createWritable(diffImage, null);
    // point of a link
    for (int j = 0; j < rows; j++) {
        for (int i = 0; i < cols; i++) {
            if (segna[i][j] > 0) {
                flow[0] = i;
                flow[1] = j;
                oldflow[0] = i;
                oldflow[1] = j;
                if (!isNovalue(flowIter.getSampleDouble(flow[0], flow[1], 0))) {
                    // call go_downstream in FluidUtils
                    ModelsEngine.go_downstream(flow, flowIter.getSampleDouble(flow[0], flow[1], 0));
                    while (segna[flow[0]][flow[1]] < 1 && !isNovalue(flowIter.getSampleDouble(flow[0], flow[1], 0)) && flowIter.getSampleDouble(flow[0], flow[1], 0) != 10.0 && streamIter.getSampleDouble(flow[0], flow[1], 0) == streamIter.getSampleDouble(i, j, 0)) {
                        oldflow[0] = flow[0];
                        oldflow[1] = flow[1];
                        if (!ModelsEngine.go_downstream(flow, flowIter.getSampleDouble(flow[0], flow[1], 0)))
                            return null;
                    }
                    diffIter.setSample(i, j, 0, Math.abs(rasterIter.getSampleDouble(i, j, 0) - rasterIter.getSampleDouble(oldflow[0], oldflow[1], 0)));
                    // Assign to any point inside the link the value of the
                    // difference
                    flow[0] = i;
                    flow[1] = j;
                    if (!ModelsEngine.go_downstream(flow, flowIter.getSampleDouble(flow[0], flow[1], 0)))
                        return null;
                    while (!isNovalue(flowIter.getSampleDouble(flow[0], flow[1], 0)) && flowIter.getSampleDouble(flow[0], flow[1], 0) != 10.0 && streamIter.getSampleDouble(flow[0], flow[1], 0) == streamIter.getSampleDouble(i, j, 0)) {
                        diffIter.setSample(flow[0], flow[1], 0, diffIter.getSampleDouble(i, j, 0));
                        if (!ModelsEngine.go_downstream(flow, flowIter.getSampleDouble(flow[0], flow[1], 0)))
                            return null;
                    }
                    if (flowIter.getSampleDouble(flow[0], flow[1], 0) == 10 && streamIter.getSampleDouble(flow[0], flow[1], 0) == streamIter.getSampleDouble(i, j, 0)) {
                        diffIter.setSample(flow[0], flow[1], 0, diffIter.getSampleDouble(i, j, 0));
                    }
                }
            }
        }
        pm.worked(1);
    }
    for (int j = 0; j < rows; j++) {
        for (int i = 0; i < cols; i++) {
            if (isNovalue(streamIter.getSampleDouble(i, j, 0))) {
                diffIter.setSample(i, j, 0, doubleNovalue);
            }
        }
        pm.worked(1);
    }
    pm.done();
    diffIter.done();
    flowIter.done();
    rasterIter.done();
    streamIter.done();
    return diffImage;
}
Also used : WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) WritableRaster(java.awt.image.WritableRaster) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter)

Example 38 with WritableRandomIter

use of javax.media.jai.iterator.WritableRandomIter in project hortonmachine by TheHortonMachine.

the class OmsNetshape2Flow method process.

@Execute
public void process() throws Exception {
    if (!concatOr(outNet == null, doReset)) {
        return;
    }
    checkNull(inNet, inGrid);
    HashMap<String, Double> regionMap = CoverageUtilities.gridGeometry2RegionParamsMap(inGrid);
    double res = regionMap.get(CoverageUtilities.XRES);
    int cols = regionMap.get(CoverageUtilities.COLS).intValue();
    int rows = regionMap.get(CoverageUtilities.ROWS).intValue();
    WritableRaster flowWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, HMConstants.doubleNovalue);
    WritableRaster netWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, HMConstants.doubleNovalue);
    WritableRandomIter flowIter = RandomIterFactory.createWritable(flowWR, null);
    WritableRandomIter netIter = RandomIterFactory.createWritable(netWR, null);
    int activeFieldPosition = -1;
    // if a field for active reach parts was passed
    SimpleFeatureType simpleFeatureType = inNet.getSchema();
    if (fActive != null) {
        activeFieldPosition = simpleFeatureType.indexOf(fActive);
    }
    int idFieldPosition = -1;
    if (fId != null) {
        idFieldPosition = simpleFeatureType.indexOf(fId);
    }
    int featureNum = inNet.size();
    FeatureIterator<SimpleFeature> featureIterator = inNet.features();
    pm.beginTask("Processing features...", featureNum);
    while (featureIterator.hasNext()) {
        SimpleFeature feature = featureIterator.next();
        // if the reach is not active, do not use it
        if (activeFieldPosition != -1) {
            String attr = (String) feature.getAttribute(activeFieldPosition);
            if (attr == null) {
            // do what? Means to be active or not? For now it is dealt
            // as active.
            } else if (attr.trim().substring(0, 1).equalsIgnoreCase("n")) {
                // reach is not active
                continue;
            }
        }
        // find the id of the reach
        int id = -1;
        if (idFieldPosition == -1) {
            // $NON-NLS-1$
            String[] idSplit = feature.getID().split("\\.");
            id = Integer.parseInt(idSplit[idSplit.length - 1]);
        } else {
            Object attribute = feature.getAttribute(idFieldPosition);
            id = Integer.parseInt(String.valueOf(attribute));
        }
        // if the feature is active, start working on it
        Geometry geometry = (Geometry) feature.getDefaultGeometry();
        Coordinate[] coordinates = geometry.getCoordinates();
        if (coordinates.length < 2) {
            continue;
        }
        // boolean isLastCoordinateOfSegment = false;
        // boolean isSecondLastCoordinateOfSegment = false;
        Coordinate lastCoord = coordinates[coordinates.length - 1];
        GridCoordinates2D lastPointGC = inGrid.worldToGrid(new DirectPosition2D(lastCoord.x, lastCoord.y));
        int[] lastPoint = new int[] { lastPointGC.y, lastPointGC.x };
        for (int i = 0; i < coordinates.length - 1; i++) {
            // if (i == coordinates.length - 2) {
            // isLastCoordinateOfSegment = true;
            // }
            // if (i == coordinates.length - 3) {
            // isSecondLastCoordinateOfSegment = true;
            // }
            Coordinate first = coordinates[i];
            Coordinate second = coordinates[i + 1];
            LineSegment lineSegment = new LineSegment(first, second);
            double segmentLength = lineSegment.getLength();
            double runningLength = 0.0;
            while (runningLength <= segmentLength) {
                Coordinate firstPoint = lineSegment.pointAlong(runningLength / segmentLength);
                // if the resolution is bigger than the length, use the
                // length, i.e. 1
                double perc = (runningLength + res) / segmentLength;
                Coordinate secondPoint = lineSegment.pointAlong(perc > 1.0 ? 1.0 : perc);
                GridCoordinates2D firstPointGC = inGrid.worldToGrid(new DirectPosition2D(firstPoint.x, firstPoint.y));
                int[] firstOnRaster = new int[] { firstPointGC.y, firstPointGC.x };
                GridCoordinates2D secondPointGC = inGrid.worldToGrid(new DirectPosition2D(secondPoint.x, secondPoint.y));
                int[] secondOnRaster = new int[] { secondPointGC.y, secondPointGC.x };
                /*
                     * if there is already a value in that point, and if the point in the output
                     * matrix is an outlet (10), then it is an end of another reach and it is ok to
                     * write over it. 
                     * If it is another value and my actual reach is not at the end,
                     * then jump over it, the outlet is threated after the loop. Let's create
                     * a temporary resource that contains all the problem points. The user will for
                     * now have to change the shapefile to proceed.
                     */
                if (!isNovalue(flowIter.getSampleDouble(firstOnRaster[1], firstOnRaster[0], 0)) && flowIter.getSampleDouble(firstOnRaster[1], firstOnRaster[0], 0) != 10.0) {
                    if (i > coordinates.length - 3) {
                        runningLength = runningLength + res;
                        continue;
                    } else
                        problemPointsList.add(firstPoint);
                }
                /*
                     * if the two analized points are equal, the point will be added at the next
                     * round
                     */
                if (Arrays.equals(firstOnRaster, secondOnRaster)) {
                    runningLength = runningLength + res;
                    continue;
                }
                // find the flowdirection between the point and the one
                // after it
                int rowDiff = secondOnRaster[0] - firstOnRaster[0];
                int colDiff = secondOnRaster[1] - firstOnRaster[1];
                int flowDirection = ModelsEngine.getFlowDirection(rowDiff, colDiff);
                if (isNovalue(flowIter.getSampleDouble(firstOnRaster[1], firstOnRaster[0], 0)) || (lastPoint[0] != secondOnRaster[0] && lastPoint[1] != secondOnRaster[1])) {
                    flowIter.setSample(firstOnRaster[1], firstOnRaster[0], 0, flowDirection);
                }
                /* I have add this if statment in order to preserve the continuity of the main
                    * river.(first problem in the report)
                    */
                if (isNovalue(netIter.getSampleDouble(firstOnRaster[1], firstOnRaster[0], 0)) || (lastPoint[0] != secondOnRaster[0] && lastPoint[1] != secondOnRaster[1])) {
                    netIter.setSample(firstOnRaster[1], firstOnRaster[0], 0, id);
                }
                // increment the distance
                runningLength = runningLength + res;
            }
        /*
                 * note that the last coordinate is always threated when it is the first of the next
                 * segment. That is good, so we are able to threat the last coordinate of the reach
                 * differently.
                 */
        }
        Coordinate lastCoordinate = coordinates[coordinates.length - 1];
        GridCoordinates2D lastCoordinateGC = inGrid.worldToGrid(new DirectPosition2D(lastCoordinate.x, lastCoordinate.y));
        int[] lastOnRaster = new int[] { lastCoordinateGC.y, lastCoordinateGC.x };
        /*
             * the last is 10, but if there is already another value in the grid, then a major reach
             * has already put its value in it. If that is true, then we do not add this reach's
             * outlet, since it is just a confluence
             */
        if (isNovalue(flowIter.getSampleDouble(lastOnRaster[1], lastOnRaster[0], 0))) {
            flowIter.setSample(lastOnRaster[1], lastOnRaster[0], 0, 10.0);
            netIter.setSample(lastOnRaster[1], lastOnRaster[0], 0, id);
        }
        pm.worked(1);
    }
    pm.done();
    flowIter.done();
    netIter.done();
    CoordinateReferenceSystem crs = inNet.getSchema().getCoordinateReferenceSystem();
    outFlownet = CoverageUtilities.buildCoverage("flow", flowWR, regionMap, crs);
    outNet = CoverageUtilities.buildCoverage("networkd", netWR, regionMap, crs);
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    String typeName = "problemslayer";
    b.setName(typeName);
    b.setCRS(inNet.getSchema().getCoordinateReferenceSystem());
    b.add("the_geom", MultiPoint.class);
    b.add("cat", Integer.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    GeometryFactory gf = GeometryUtilities.gf();
    outProblems = new DefaultFeatureCollection();
    for (int i = 0; i < problemPointsList.size(); i++) {
        MultiPoint mPoint = gf.createMultiPoint(new Coordinate[] { problemPointsList.get(i) });
        Object[] values = new Object[] { mPoint, i };
        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(null);
        ((DefaultFeatureCollection) outProblems).add(feature);
    }
}
Also used : MultiPoint(org.locationtech.jts.geom.MultiPoint) SimpleFeatureTypeBuilder(org.geotools.feature.simple.SimpleFeatureTypeBuilder) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) DirectPosition2D(org.geotools.geometry.DirectPosition2D) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) WritableRaster(java.awt.image.WritableRaster) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) LineSegment(org.locationtech.jts.geom.LineSegment) MultiPoint(org.locationtech.jts.geom.MultiPoint) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Geometry(org.locationtech.jts.geom.Geometry) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Coordinate(org.locationtech.jts.geom.Coordinate) GridCoordinates2D(org.geotools.coverage.grid.GridCoordinates2D) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder) Execute(oms3.annotations.Execute)

Example 39 with WritableRandomIter

use of javax.media.jai.iterator.WritableRandomIter in project hortonmachine by TheHortonMachine.

the class OmsBaseflowWaterVolume method process.

@Execute
public void process() throws Exception {
    checkNull(inInfiltration, inNetInfiltration, inFlowdirections, inNet);
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inFlowdirections);
    int rows = regionMap.getRows();
    int cols = regionMap.getCols();
    double outNv = HMConstants.doubleNovalue;
    double lsumNv = -1E32;
    WritableRaster outBaseflowWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, outNv);
    WritableRandomIter outBaseflowIter = CoverageUtilities.getWritableRandomIterator(outBaseflowWR);
    WritableRaster outBWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, outNv);
    WritableRandomIter outBIter = CoverageUtilities.getWritableRandomIterator(outBWR);
    WritableRaster outVriWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, outNv);
    WritableRandomIter outVriIter = CoverageUtilities.getWritableRandomIterator(outVriWR);
    RandomIter flowIter = CoverageUtilities.getRandomIterator(inFlowdirections);
    int flowNv = HMConstants.getIntNovalue(inFlowdirections);
    RandomIter netInfiltrationIter = CoverageUtilities.getRandomIterator(inNetInfiltration);
    double netInfNv = HMConstants.getNovalue(inNetInfiltration);
    RandomIter infiltrationIter = CoverageUtilities.getRandomIterator(inInfiltration);
    infNv = HMConstants.getNovalue(inInfiltration);
    RandomIter netIter = CoverageUtilities.getRandomIterator(inNet);
    netNv = HMConstants.getNovalue(inNet);
    List<FlowNode> sourceCells = new ArrayList<>();
    List<FlowNode> exitCells = new ArrayList<>();
    try {
        pm.beginTask("Collect source and exit cells...", rows);
        for (int r = 0; r < rows; r++) {
            if (pm.isCanceled()) {
                return;
            }
            for (int c = 0; c < cols; c++) {
                if (r == 1 && c == 959) {
                    System.out.println();
                }
                FlowNode node = new FlowNode(flowIter, cols, rows, c, r, flowNv);
                // get exit cells
                if (node.isHeadingOutside()) {
                    exitCells.add(node);
                }
                // and source cells on network
                if (node.isSource()) {
                    sourceCells.add(node);
                }
            }
            pm.worked(1);
        }
        pm.done();
        // calculate matrix of cumulated infiltration
        double[][] lSumMatrix = new double[rows][cols];
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                lSumMatrix[row][col] = lsumNv;
            }
        }
        calculateLsumMatrix(sourceCells, lSumMatrix, infiltrationIter, netIter, lsumNv, pm);
        // calculate matrix of cumulated baseflow
        double[][] bSumMatrix = new double[rows][cols];
        pm.beginTask("Calcuate bsum...", exitCells.size());
        for (FlowNode exitCell : exitCells) {
            if (pm.isCanceled()) {
                return;
            }
            walkUpAndProcess(exitCell, bSumMatrix, lSumMatrix, outBaseflowIter, netIter, infiltrationIter, netInfiltrationIter);
            pm.worked(1);
        }
        pm.done();
        double qb = 0;
        int count = 0;
        pm.beginTask("Calculate total baseflow...", rows);
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                double li = infiltrationIter.getSampleDouble(col, row, 0);
                if (!HMConstants.isNovalue(li, infNv)) {
                    qb += li;
                    count++;
                }
            }
            pm.worked(1);
        }
        double qbTmp = qb / count;
        outQb = qbTmp;
        pm.done();
        pm.beginTask("Calculate Vri...", rows);
        double vriSum = 0;
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                double li = infiltrationIter.getSampleDouble(col, row, 0);
                double bSum = outBaseflowIter.getSampleDouble(col, row, 0);
                double lSum = lSumMatrix[row][col];
                if (!HMConstants.isNovalue(li, infNv)) {
                    double vri = li / (qbTmp * count);
                    vriSum += vri;
                    outVriIter.setSample(col, row, 0, vri);
                    double bi = Math.max(bSum * li / lSum, 0);
                    outBIter.setSample(col, row, 0, bi);
                }
            }
            pm.worked(1);
        }
        pm.done();
        outVriSum = vriSum;
        outBaseflow = CoverageUtilities.buildCoverageWithNovalue("baseflow", outBaseflowWR, regionMap, inFlowdirections.getCoordinateReferenceSystem(), outNv);
        outLsum = CoverageUtilities.buildCoverageWithNovalue("lsum", lSumMatrix, regionMap, inFlowdirections.getCoordinateReferenceSystem(), true, lsumNv);
        outB = CoverageUtilities.buildCoverageWithNovalue("b", outBWR, regionMap, inFlowdirections.getCoordinateReferenceSystem(), outNv);
        outVri = CoverageUtilities.buildCoverageWithNovalue("vri", outVriWR, regionMap, inFlowdirections.getCoordinateReferenceSystem(), lsumNv);
    } finally {
        flowIter.done();
        netInfiltrationIter.done();
        infiltrationIter.done();
        netIter.done();
        outBaseflowIter.done();
        outBIter.done();
        outVriIter.done();
    }
}
Also used : WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) WritableRaster(java.awt.image.WritableRaster) RegionMap(org.hortonmachine.gears.utils.RegionMap) ArrayList(java.util.ArrayList) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) FlowNode(org.hortonmachine.gears.libs.modules.FlowNode) Execute(oms3.annotations.Execute)

Example 40 with WritableRandomIter

use of javax.media.jai.iterator.WritableRandomIter in project hortonmachine by TheHortonMachine.

the class OmsInfiltratedWaterVolume method process.

// VARS DOC END
@Execute
public void process() throws Exception {
    checkNull(inPet, inRainfall, inFlowdirections, inNet, inRunoff);
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inFlowdirections);
    int rows = regionMap.getRows();
    int cols = regionMap.getCols();
    // -1E32;// as INVEST HMConstants.doubleNovalue;
    double outNv = -9999;
    WritableRaster outLiWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, outNv);
    WritableRandomIter outLiIter = CoverageUtilities.getWritableRandomIterator(outLiWR);
    WritableRaster outLiAvailableWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, outNv);
    WritableRandomIter outLiAvailableIter = CoverageUtilities.getWritableRandomIterator(outLiAvailableWR);
    WritableRaster outAetWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, outNv);
    WritableRandomIter outAetIter = CoverageUtilities.getWritableRandomIterator(outAetWR);
    RandomIter flowIter = CoverageUtilities.getRandomIterator(inFlowdirections);
    int flowNv = HMConstants.getIntNovalue(inFlowdirections);
    RandomIter petIter = CoverageUtilities.getRandomIterator(inPet);
    double petNv = HMConstants.getNovalue(inPet);
    RandomIter runoffIter = CoverageUtilities.getRandomIterator(inRunoff);
    double runoffNv = HMConstants.getNovalue(inRunoff);
    RandomIter rainIter = CoverageUtilities.getRandomIterator(inRainfall);
    double rainNv = HMConstants.getNovalue(inRainfall);
    RandomIter netIter = CoverageUtilities.getRandomIterator(inNet);
    double netNv = HMConstants.getNovalue(inNet);
    List<FlowNode> sourceCells = new ArrayList<>();
    try {
        pm.beginTask("Collect source cells...", rows);
        for (int r = 0; r < rows; r++) {
            if (pm.isCanceled()) {
                return;
            }
            for (int c = 0; c < cols; c++) {
                FlowNode node = new FlowNode(flowIter, cols, rows, c, r, flowNv);
                if (node.isSource()) {
                    sourceCells.add(node);
                }
            }
            pm.worked(1);
        }
        pm.done();
        double[][] lSumAvailableMatrix = new double[rows][cols];
        for (int r = 0; r < lSumAvailableMatrix.length; r++) {
            for (int c = 0; c < lSumAvailableMatrix[0].length; c++) {
                lSumAvailableMatrix[r][c] = outNv;
            }
        }
        for (FlowNode sourceCell : sourceCells) {
            double pet = sourceCell.getValueFromMap(petIter);
            double runoff = sourceCell.getValueFromMap(runoffIter);
            double rain = sourceCell.getValueFromMap(rainIter);
            double net = sourceCell.getValueFromMap(netIter);
            if (!HMConstants.isNovalue(rain, rainNv) && !HMConstants.isNovalue(runoff, runoffNv)) {
                boolean isPetNv = HMConstants.isNovalue(pet, petNv);
                boolean isStream = !HMConstants.isNovalue(net, netNv) && net != 0.0;
                double initialAet = 0;
                double li = 0;
                if (!isStream) {
                    if (isPetNv) {
                        initialAet = rain - runoff;
                    } else {
                        initialAet = Math.min(pet, rain - runoff);
                    }
                    li = rain - runoff - initialAet;
                }
                double lAvailable = Math.min(pGamma * li, li);
                lSumAvailableMatrix[sourceCell.row][sourceCell.col] = 0;
                sourceCell.setDoubleValueInMap(outLiAvailableIter, lAvailable);
                sourceCell.setDoubleValueInMap(outLiIter, li);
                sourceCell.setDoubleValueInMap(outAetIter, initialAet);
                // go downstream
                FlowNode cell = sourceCell.goDownstream();
                Set<FlowNode> seen = new HashSet<>();
                while (cell != null) {
                    List<FlowNode> upstreamCells = cell.getEnteringNodes();
                    // check if all upstream have a value
                    boolean canProcess = canProcess(outNv, outLiAvailableIter, upstreamCells);
                    if (canProcess) {
                        pet = cell.getDoubleValueFromMap(petIter);
                        isPetNv = HMConstants.isNovalue(pet, petNv);
                        rain = cell.getDoubleValueFromMap(rainIter);
                        runoff = cell.getDoubleValueFromMap(runoffIter);
                        net = cell.getDoubleValueFromMap(netIter);
                        if (!HMConstants.isNovalue(rain, rainNv) && !HMConstants.isNovalue(runoff, runoffNv)) {
                            isStream = !HMConstants.isNovalue(net, netNv) && net != 0.0;
                            double lAvailableUpstream = 0.0;
                            double lSumAvailableUpstream = 0.0;
                            for (FlowNode upstreamCell : upstreamCells) {
                                double upstreamLAvailable = upstreamCell.getValueFromMap(outLiAvailableIter);
                                // infiltratedWaterVolumeState.get(upstreamCell,
                                // Double.class);
                                int x = upstreamCell.col;
                                int y = upstreamCell.row;
                                lSumAvailableUpstream += lSumAvailableMatrix[y][x];
                                lAvailableUpstream += upstreamLAvailable;
                            }
                            double lSumAvailableCurrentCell = lSumAvailableUpstream + lAvailableUpstream;
                            lSumAvailableCurrentCell /= upstreamCells.size();
                            lSumAvailableMatrix[cell.row][cell.col] = lSumAvailableCurrentCell;
                            double aetCC = 0;
                            double liCC = 0;
                            if (!isStream) {
                                if (isPetNv) {
                                    aetCC = rain - runoff + pAlpha * pBeta * lSumAvailableCurrentCell;
                                } else {
                                    aetCC = Math.min(pet, rain - runoff + pAlpha * pBeta * lSumAvailableCurrentCell);
                                }
                                liCC = rain - runoff - aetCC;
                            }
                            double lAvailableCC = Math.min(pGamma * liCC, liCC);
                            cell.setDoubleValueInMap(outLiAvailableIter, lAvailableCC);
                            cell.setDoubleValueInMap(outLiIter, liCC);
                            cell.setDoubleValueInMap(outAetIter, aetCC);
                        } else if (!HMConstants.isNovalue(net, netNv) && net != 0.0 && cell.isValid()) {
                            cell.setDoubleValueInMap(outLiAvailableIter, 0);
                            cell.setDoubleValueInMap(outLiIter, 0);
                            cell.setDoubleValueInMap(outAetIter, 0);
                        }
                        cell = cell.goDownstream();
                        if (cell != null) {
                            if (seen.contains(cell)) {
                                cell = null;
                            } else {
                                seen.add(cell);
                            }
                        }
                    } else {
                        break;
                    }
                }
            }
        }
        outInfiltration = CoverageUtilities.buildCoverageWithNovalue("infiltration", outLiWR, regionMap, inFlowdirections.getCoordinateReferenceSystem(), outNv);
        outNetInfiltration = CoverageUtilities.buildCoverageWithNovalue("netinfiltration", outLiAvailableWR, regionMap, inFlowdirections.getCoordinateReferenceSystem(), outNv);
        outAet = CoverageUtilities.buildCoverageWithNovalue("aet", outAetWR, regionMap, inFlowdirections.getCoordinateReferenceSystem(), outNv);
        outLsumAvailable = CoverageUtilities.buildCoverageWithNovalue("lsum", lSumAvailableMatrix, regionMap, inFlowdirections.getCoordinateReferenceSystem(), true, outNv);
    } finally {
        flowIter.done();
        petIter.done();
        runoffIter.done();
        rainIter.done();
        netIter.done();
        outLiIter.done();
        outLiAvailableIter.done();
        outAetIter.done();
    }
}
Also used : RegionMap(org.hortonmachine.gears.utils.RegionMap) ArrayList(java.util.ArrayList) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) WritableRaster(java.awt.image.WritableRaster) FlowNode(org.hortonmachine.gears.libs.modules.FlowNode) HashSet(java.util.HashSet) Execute(oms3.annotations.Execute)

Aggregations

WritableRandomIter (javax.media.jai.iterator.WritableRandomIter)99 WritableRaster (java.awt.image.WritableRaster)85 RandomIter (javax.media.jai.iterator.RandomIter)60 RegionMap (org.hortonmachine.gears.utils.RegionMap)59 Execute (oms3.annotations.Execute)49 Coordinate (org.locationtech.jts.geom.Coordinate)20 GridCoverage2D (org.geotools.coverage.grid.GridCoverage2D)18 ModelsIllegalargumentException (org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException)18 GridGeometry2D (org.geotools.coverage.grid.GridGeometry2D)17 RenderedImage (java.awt.image.RenderedImage)16 Point (java.awt.Point)11 ArrayList (java.util.ArrayList)11 Geometry (org.locationtech.jts.geom.Geometry)11 GridCoordinates2D (org.geotools.coverage.grid.GridCoordinates2D)10 FlowNode (org.hortonmachine.gears.libs.modules.FlowNode)10 DirectPosition2D (org.geotools.geometry.DirectPosition2D)9 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)8 Envelope (org.locationtech.jts.geom.Envelope)7 DirectPosition (org.opengis.geometry.DirectPosition)7 SampleModel (java.awt.image.SampleModel)6