Search in sources :

Example 76 with RandomIter

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

the class OmsBasinShape method process.

@Execute
public void process() throws Exception {
    if (!concatOr(outBasins == null, doReset)) {
        return;
    }
    checkNull(inBasins);
    HashMap<String, Double> regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inBasins);
    nCols = regionMap.get(CoverageUtilities.COLS).intValue();
    nRows = regionMap.get(CoverageUtilities.ROWS).intValue();
    // double xRes = regionMap.get(CoverageUtilities.XRES);
    // double yRes = regionMap.get(CoverageUtilities.YRES);
    RenderedImage basinsRI = inBasins.getRenderedImage();
    RenderedImage pitRI = null;
    if (inElev != null)
        pitRI = inElev.getRenderedImage();
    int[] nstream = new int[1];
    // nstream[0] = 1508;
    WritableRaster basinsWR = CoverageUtilities.renderedImage2WritableRaster(basinsRI, true);
    RandomIter basinsRandomIter = RandomIterFactory.create(basinsWR, null);
    for (int j = 0; j < nRows; j++) {
        for (int i = 0; i < nCols; i++) {
            if (!isNovalue(basinsRandomIter.getSampleDouble(i, j, 0)) && basinsRandomIter.getSampleDouble(i, j, 0) > (double) nstream[0]) {
                nstream[0] = (int) basinsRandomIter.getSampleDouble(i, j, 0);
            }
        }
    }
    WritableRaster subbasinsWR = CoverageUtilities.createWritableRaster(basinsRI.getWidth(), basinsRI.getHeight(), null, basinsRI.getSampleModel(), doubleNovalue);
    // create the feature type
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    // set the name
    // $NON-NLS-1$
    b.setName("basinshape");
    // add a geometry property
    // $NON-NLS-1$
    String defaultGeometryName = "the_geom";
    b.setCRS(inBasins.getCoordinateReferenceSystem());
    b.add(defaultGeometryName, MultiPolygon.class);
    // add some properties
    // $NON-NLS-1$
    b.add("area", Float.class);
    // $NON-NLS-1$
    b.add("perimeter", Float.class);
    // $NON-NLS-1$
    b.add(NetworkChannel.NETNUMNAME, Integer.class);
    // $NON-NLS-1$
    b.add("maxelev", Float.class);
    // $NON-NLS-1$
    b.add("minelev", Float.class);
    // $NON-NLS-1$
    b.add("avgelev", Float.class);
    // $NON-NLS-1$
    b.add(NetworkChannel.BARICENTERELEVNAME, Float.class);
    // build the type
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    outBasins = new DefaultFeatureCollection();
    // for each stream correct problems with basins and create geometries
    pm.beginTask("Extracting basins...", nstream[0]);
    for (int num = 1; num <= nstream[0]; num++) {
        Object[] values = new Object[8];
        int nordRow = -1;
        int southRow = 0;
        int eastCol = -1;
        int westCol = nCols;
        int numPixel = 0;
        double minZ = Double.MAX_VALUE;
        double maxZ = Double.MIN_VALUE;
        double averageZ = 0.0;
        if (pitRI != null)
            pitRandomIter = RandomIterFactory.create(pitRI, null);
        WritableRandomIter subbasinIter = RandomIterFactory.createWritable(subbasinsWR, null);
        for (int j = 0; j < nRows; j++) {
            for (int i = 0; i < nCols; i++) {
                double basinId = basinsRandomIter.getSampleDouble(i, j, 0);
                if (isNovalue(basinId)) {
                    continue;
                }
                int basinNum = (int) basinId;
                if (basinNum == num) {
                    if (nordRow == -1) {
                        nordRow = i;
                    }
                    if (i > nordRow) {
                        southRow = i;
                    }
                    if (westCol > j) {
                        westCol = j;
                    }
                    if (eastCol < j) {
                        eastCol = j;
                    }
                    subbasinIter.setSample(i, j, 0, basinNum);
                    if (pitRI != null) {
                        double elevation = pitRandomIter.getSampleDouble(i, j, 0);
                        if (!isNovalue(elevation)) {
                            minZ = elevation < minZ ? elevation : minZ;
                            maxZ = elevation > maxZ ? elevation : maxZ;
                            averageZ = averageZ + elevation;
                        } else {
                            minZ = -1;
                            maxZ = -1;
                            averageZ = 0;
                        }
                    }
                    numPixel++;
                }
            }
        }
        if (numPixel != 0) {
            // min, max and average
            values[3] = num;
            values[4] = maxZ;
            values[5] = minZ;
            values[6] = averageZ / numPixel;
            numPixel = 0;
            for (int i = nordRow; i < southRow + 1; i++) {
                for (int j = westCol; j < eastCol + 1; j++) {
                    if (isNovalue(subbasinIter.getSampleDouble(i, j, 0))) {
                        for (int k = 1; k <= 8; k++) {
                            // index.setFlow(k);
                            // index.getParameters()[
                            int indexI = i + ModelsSupporter.DIR[k][1];
                            // 0];
                            // index.getParameters()[
                            int indexJ = j + ModelsSupporter.DIR[k][0];
                            // 1];
                            if (!isNovalue(subbasinIter.getSampleDouble(indexI, indexJ, 0))) {
                                numPixel++;
                            }
                            k++;
                        }
                        if (numPixel == 4) {
                            subbasinIter.setSample(i, j, 0, num);
                        }
                    }
                    numPixel = 0;
                }
            }
            // extract the feature polygon of that basin number
            OmsVectorizer vectorizer = new OmsVectorizer();
            try {
                vectorizer.inRaster = inBasins;
                vectorizer.pm = pm;
                vectorizer.doReset = true;
                vectorizer.pValue = (double) num;
                vectorizer.process();
            } catch (Exception e) {
                pm.errorMessage(e.getLocalizedMessage());
                continue;
            }
            SimpleFeatureCollection outGeodata = vectorizer.outVector;
            FeatureIterator<SimpleFeature> outGeodataIterator = outGeodata.features();
            List<Polygon> polygons = new ArrayList<Polygon>();
            while (outGeodataIterator.hasNext()) {
                SimpleFeature feature = outGeodataIterator.next();
                polygons.add((Polygon) feature.getDefaultGeometry());
            }
            outGeodataIterator.close();
            MultiPolygon geometry = GeometryUtilities.gf().createMultiPolygon((Polygon[]) polygons.toArray(new Polygon[polygons.size()]));
            values[0] = geometry;
            values[1] = geometry.getArea();
            values[2] = geometry.getLength();
            Point centroid = geometry.getCentroid();
            if (centroid == null || centroid.isEmpty()) {
                pm.errorMessage("Unable to extract basin: " + num);
                continue;
            }
            Coordinate centroidCoords = centroid.getCoordinate();
            GridGeometry2D gridGeometry = inBasins.getGridGeometry();
            GridCoordinates2D worldToGrid = gridGeometry.worldToGrid(new DirectPosition2D(centroidCoords.x, centroidCoords.y));
            int[] rowColPoint = new int[] { worldToGrid.y, worldToGrid.x };
            double centroidElevation = -1;
            ;
            if (pitRI != null) {
                double elev = pitRandomIter.getSampleDouble(rowColPoint[1], rowColPoint[0], 0);
                if (!isNovalue(elev)) {
                    centroidElevation = elev;
                }
            }
            values[7] = centroidElevation;
            subbasinIter.done();
            subbasinsWR = CoverageUtilities.createWritableRaster(nCols, nRows, null, null, doubleNovalue);
            // add the values
            builder.addAll(values);
            // build the feature with provided ID
            SimpleFeature feature = builder.buildFeature(type.getTypeName() + "." + num);
            ((DefaultFeatureCollection) outBasins).add(feature);
        }
        pm.worked(1);
    }
    pm.done();
    basinsRandomIter.done();
    basinsWR = null;
}
Also used : GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) SimpleFeatureTypeBuilder(org.geotools.feature.simple.SimpleFeatureTypeBuilder) ArrayList(java.util.ArrayList) DirectPosition2D(org.geotools.geometry.DirectPosition2D) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) WritableRaster(java.awt.image.WritableRaster) Polygon(org.locationtech.jts.geom.Polygon) MultiPolygon(org.locationtech.jts.geom.MultiPolygon) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) Point(org.locationtech.jts.geom.Point) Point(org.locationtech.jts.geom.Point) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) OmsVectorizer(org.hortonmachine.gears.modules.v.vectorize.OmsVectorizer) MultiPolygon(org.locationtech.jts.geom.MultiPolygon) Coordinate(org.locationtech.jts.geom.Coordinate) GridCoordinates2D(org.geotools.coverage.grid.GridCoordinates2D) RenderedImage(java.awt.image.RenderedImage) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder) Execute(oms3.annotations.Execute)

Example 77 with RandomIter

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

the class OmsRescaledDistance method process.

@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);
    int novalue = HMConstants.getIntNovalue(inFlow);
    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 {
        // $NON-NLS-1$
        pm.beginTask("Find outlets...", rows * cols);
        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, novalue);
            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());
}
Also used : ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) WritableRaster(java.awt.image.WritableRaster) RegionMap(org.hortonmachine.gears.utils.RegionMap) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) RenderedImage(java.awt.image.RenderedImage) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) FlowNode(org.hortonmachine.gears.libs.modules.FlowNode) Execute(oms3.annotations.Execute)

Example 78 with RandomIter

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

the class HMTestCase method checkMatrixEqual.

protected void checkMatrixEqual(Raster image, double[][] matrix) {
    assertEquals("different dimension", image.getHeight(), matrix.length);
    assertEquals("different dimension", image.getWidth(), matrix[0].length);
    RandomIter randomIter = RandomIterFactory.create(image, null);
    int minX = image.getMinX();
    int minY = image.getMinY();
    for (int j = minY; j < minY + image.getHeight(); j++) {
        for (int i = minX; i < minX + image.getWidth(); i++) {
            double expectedResult = matrix[i - minX][j - minY];
            double value = randomIter.getSampleDouble(i, j, 0);
            if (isNovalue(value)) {
                assertTrue("Difference at position: " + i + " " + j, isNovalue(expectedResult));
            } else {
                assertEquals("Difference at position: " + i + " " + j, expectedResult, value);
            }
        }
    }
}
Also used : RandomIter(javax.media.jai.iterator.RandomIter)

Example 79 with RandomIter

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

the class LasOnRasterMapper method process.

@Execute
public void process() throws Exception {
    checkNull(inLas, inDtm, outRaster);
    GridCoverage2D inDtmGC = getRaster(inDtm);
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inDtmGC);
    double north = regionMap.getNorth();
    double south = regionMap.getSouth();
    double east = regionMap.getEast();
    double west = regionMap.getWest();
    if (pXres == null || pYres == null) {
        pXres = regionMap.getXres();
        pYres = regionMap.getYres();
    }
    CoordinateReferenceSystem crs = null;
    Polygon polygon = CoverageUtilities.getRegionPolygon(inDtmGC);
    crs = inDtmGC.getCoordinateReferenceSystem();
    GridGeometry2D dtmGridGeometry = inDtmGC.getGridGeometry();
    final int newRows = (int) round((north - south) / pYres);
    int newCols = (int) round((east - west) / pXres);
    final GridGeometry2D newGridGeometry2D = CoverageUtilities.gridGeometryFromRegionValues(north, south, east, west, newCols, newRows, crs);
    RegionMap newRegionMap = CoverageUtilities.gridGeometry2RegionParamsMap(newGridGeometry2D);
    final WritableRaster newWR = CoverageUtilities.createWritableRaster(newCols, newRows, null, null, HMConstants.doubleNovalue);
    RandomIter dtmIter = CoverageUtilities.getRandomIterator(inDtmGC);
    try (ALasDataManager lasData = ALasDataManager.getDataManager(new File(inLas), null, 0.0, crs)) {
        lasData.open();
        pm.beginTask("Reading points on region...", IHMProgressMonitor.UNKNOWN);
        List<LasRecord> lasPoints = lasData.getPointsInGeometry(polygon, false);
        pm.done();
        pm.beginTask("Setting raster points...", lasPoints.size());
        final Point gridPoint = new Point();
        final Point dtmPoint = new Point();
        for (LasRecord lasRecord : lasPoints) {
            double dotZ = lasRecord.z;
            Coordinate coordinate = new Coordinate(lasRecord.x, lasRecord.y, dotZ);
            CoverageUtilities.colRowFromCoordinate(coordinate, newGridGeometry2D, gridPoint);
            double newRasterValue = newWR.getSampleDouble(gridPoint.x, gridPoint.y, 0);
            CoverageUtilities.colRowFromCoordinate(coordinate, dtmGridGeometry, dtmPoint);
            double dtmValue = dtmIter.getSampleDouble(dtmPoint.x, dtmPoint.y, 0);
            if (doMax) {
                if (HMConstants.isNovalue(newRasterValue) || newRasterValue < dotZ) {
                    if (!HMConstants.isNovalue(dtmValue) && dtmValue > dotZ) {
                        dotZ = dtmValue;
                    }
                    newWR.setSample(gridPoint.x, gridPoint.y, 0, dotZ);
                }
            } else {
                if (HMConstants.isNovalue(newRasterValue) || newRasterValue > dotZ) {
                    if (!HMConstants.isNovalue(dtmValue) && dtmValue > dotZ) {
                        dotZ = dtmValue;
                    }
                    newWR.setSample(gridPoint.x, gridPoint.y, 0, dotZ);
                }
            }
            pm.worked(1);
        }
        pm.done();
    }
    GridCoverage2D outRasterGC = CoverageUtilities.buildCoverage("outraster", newWR, newRegionMap, crs);
    dumpRaster(outRasterGC, outRaster);
    if (pXres != null && pYres != null && outDtm != null) {
        WritableRaster[] holder = new WritableRaster[1];
        GridCoverage2D outDtmGC = CoverageUtilities.createCoverageFromTemplate(outRasterGC, HMConstants.doubleNovalue, holder);
        GridGeometry2D outGridGeometry = outDtmGC.getGridGeometry();
        WritableRandomIter outIter = CoverageUtilities.getWritableRandomIterator(holder[0]);
        RegionMap outRegionMap = CoverageUtilities.getRegionParamsFromGridCoverage(outDtmGC);
        int cols = outRegionMap.getCols();
        int rows = outRegionMap.getRows();
        final Point p = new Point();
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                Coordinate coordinate = CoverageUtilities.coordinateFromColRow(c, r, outGridGeometry);
                CoverageUtilities.colRowFromCoordinate(coordinate, dtmGridGeometry, p);
                double dtmValue = dtmIter.getSampleDouble(p.x, p.y, 0);
                outIter.setSample(c, r, 0, dtmValue);
            }
        }
        outIter.done();
        dumpRaster(outDtmGC, outDtm);
    }
    dtmIter.done();
}
Also used : GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) RegionMap(org.hortonmachine.gears.utils.RegionMap) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) Point(java.awt.Point) Point(java.awt.Point) ALasDataManager(org.hortonmachine.gears.io.las.ALasDataManager) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) LasRecord(org.hortonmachine.gears.io.las.core.LasRecord) Coordinate(org.locationtech.jts.geom.Coordinate) WritableRaster(java.awt.image.WritableRaster) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Polygon(org.locationtech.jts.geom.Polygon) File(java.io.File) Execute(oms3.annotations.Execute)

Example 80 with RandomIter

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

the class HMTestCase method checkMatrixEqual.

protected void checkMatrixEqual(Raster image, double[][] matrix) {
    assertEquals("different dimension", image.getHeight(), matrix.length);
    assertEquals("different dimension", image.getWidth(), matrix[0].length);
    RandomIter randomIter = RandomIterFactory.create(image, null);
    int minX = image.getMinX();
    int minY = image.getMinY();
    for (int j = minY; j < minY + image.getHeight(); j++) {
        for (int i = minX; i < minX + image.getWidth(); i++) {
            double expectedResult = matrix[i - minX][j - minY];
            double value = randomIter.getSampleDouble(i, j, 0);
            if (isNovalue(value)) {
                assertTrue("Difference at position: " + i + " " + j, isNovalue(expectedResult));
            } else {
                assertEquals("Difference at position: " + i + " " + j, expectedResult, value);
            }
        }
    }
}
Also used : RandomIter(javax.media.jai.iterator.RandomIter)

Aggregations

RandomIter (javax.media.jai.iterator.RandomIter)126 WritableRandomIter (javax.media.jai.iterator.WritableRandomIter)79 WritableRaster (java.awt.image.WritableRaster)71 RegionMap (org.hortonmachine.gears.utils.RegionMap)62 Execute (oms3.annotations.Execute)57 RenderedImage (java.awt.image.RenderedImage)29 GridGeometry2D (org.geotools.coverage.grid.GridGeometry2D)29 Coordinate (org.locationtech.jts.geom.Coordinate)26 GridCoverage2D (org.geotools.coverage.grid.GridCoverage2D)22 Point (java.awt.Point)17 ArrayList (java.util.ArrayList)17 ModelsIllegalargumentException (org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException)16 SimpleFeature (org.opengis.feature.simple.SimpleFeature)16 DefaultFeatureCollection (org.geotools.feature.DefaultFeatureCollection)15 Geometry (org.locationtech.jts.geom.Geometry)15 Point (org.locationtech.jts.geom.Point)14 GridCoordinates2D (org.geotools.coverage.grid.GridCoordinates2D)12 GridNode (org.hortonmachine.gears.libs.modules.GridNode)12 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)10 FlowNode (org.hortonmachine.gears.libs.modules.FlowNode)9