Search in sources :

Example 6 with RandomIter

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

the class OmsSurfaceInterpolator method process.

@Execute
public void process() throws Exception {
    checkNull(inGrid);
    gridGeometry = inGrid.getGridGeometry();
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inGrid);
    final int cols = regionMap.getCols();
    int rows = regionMap.getRows();
    coordinatesSpatialTree = new STRtree();
    if (inVector != null) {
        checkNull(fCat);
        GeometryDescriptor geometryDescriptor = inVector.getSchema().getGeometryDescriptor();
        if (!EGeometryType.isPoint(geometryDescriptor)) {
            throw new ModelsIllegalargumentException("The geometry has to be a point geometry.", this, pm);
        }
        SimpleFeatureIterator featureIterator = inVector.features();
        Coordinate[] coordinates = new Coordinate[inVector.size()];
        int index = 0;
        pm.beginTask("Indexing control points...", coordinates.length);
        while (featureIterator.hasNext()) {
            SimpleFeature feature = featureIterator.next();
            Geometry geometry = (Geometry) feature.getDefaultGeometry();
            coordinates[index] = geometry.getCoordinate();
            double value = ((Number) feature.getAttribute(fCat)).doubleValue();
            coordinates[index].z = value;
            Envelope env = new Envelope(coordinates[index]);
            coordinatesSpatialTree.insert(env, coordinates[index]);
            pm.worked(1);
        }
        pm.done();
        pm.message("Indexed control points: " + coordinates.length);
    } else {
        // create it from grid
        pm.beginTask("Indexing control points...", cols);
        RandomIter inIter = CoverageUtilities.getRandomIterator(inGrid);
        int count = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                double value = inIter.getSampleDouble(c, r, 0);
                if (!HMConstants.isNovalue(value)) {
                    Coordinate coordinate = CoverageUtilities.coordinateFromColRow(c, r, gridGeometry);
                    coordinate.z = value;
                    Envelope env = new Envelope(coordinate);
                    coordinatesSpatialTree.insert(env, coordinate);
                    count++;
                }
            }
            pm.worked(1);
        }
        pm.done();
        pm.message("Indexed control points (from input grid): " + count);
    }
    coordinatesSpatialTree.build();
    if (pMode.equals(IDW)) {
        interpolator = new IDWInterpolator(pBuffer);
    } else {
        interpolator = new TPSInterpolator(pBuffer);
    }
    WritableRaster interpolatedWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, HMConstants.doubleNovalue);
    final WritableRandomIter interpolatedIter = RandomIterFactory.createWritable(interpolatedWR, null);
    boolean doMultiThread = pMaxThreads > 1;
    ExecutorService fixedThreadPool = null;
    if (doMultiThread)
        fixedThreadPool = Executors.newFixedThreadPool(pMaxThreads);
    pm.beginTask("Performing interpolation...", rows);
    final double[] eval = new double[1];
    for (int r = 0; r < rows; r++) {
        final int row = r;
        if (doMultiThread) {
            Runnable runner = new Runnable() {

                public void run() {
                    processing(cols, coordinatesSpatialTree, interpolatedIter, eval, row);
                }
            };
            fixedThreadPool.execute(runner);
        } else {
            processing(cols, coordinatesSpatialTree, interpolatedIter, eval, row);
        }
    }
    if (doMultiThread) {
        try {
            fixedThreadPool.shutdown();
            fixedThreadPool.awaitTermination(30, TimeUnit.DAYS);
            fixedThreadPool.shutdownNow();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    pm.done();
    outRaster = CoverageUtilities.buildCoverage("interpolatedraster", interpolatedWR, regionMap, inGrid.getCoordinateReferenceSystem());
}
Also used : RegionMap(org.hortonmachine.gears.utils.RegionMap) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) Envelope(org.locationtech.jts.geom.Envelope) SimpleFeature(org.opengis.feature.simple.SimpleFeature) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) Geometry(org.locationtech.jts.geom.Geometry) GeometryDescriptor(org.opengis.feature.type.GeometryDescriptor) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) Coordinate(org.locationtech.jts.geom.Coordinate) WritableRaster(java.awt.image.WritableRaster) TPSInterpolator(org.hortonmachine.gears.modules.r.interpolation2d.core.TPSInterpolator) ExecutorService(java.util.concurrent.ExecutorService) STRtree(org.locationtech.jts.index.strtree.STRtree) IDWInterpolator(org.hortonmachine.gears.modules.r.interpolation2d.core.IDWInterpolator) Execute(oms3.annotations.Execute)

Example 7 with RandomIter

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

the class ModelsEngine method net2ShapeOnly.

/**
 * It create the shape-file of channel network
 *
 * @param flowImage the map of flow direction.
 * @param netNumImage the map of netnumbering.
 * @param gridGeometry the {@link GridGeometry2D} of the flow coverage.
 * @param nstream
 * @param pm the progress monitor.
 * @return the extracted features.
 * @throws IOException
 * @throws TransformException
 */
public static SimpleFeatureCollection net2ShapeOnly(RenderedImage flowImage, WritableRaster netNumImage, GridGeometry2D gridGeometry, List<Integer> nstream, IHMProgressMonitor pm) throws IOException, TransformException {
    int activecols = flowImage.getWidth();
    int activerows = flowImage.getHeight();
    int[] flow = new int[2];
    int[] flow_p = new int[2];
    CoordinateList coordlist = new CoordinateList();
    RandomIter m1RandomIter = RandomIterFactory.create(flowImage, null);
    RandomIter netNumRandomIter = RandomIterFactory.create(netNumImage, null);
    // GEOMETRY
    // creates new LineSting array
    LineString[] newGeometry = new LineString[nstream.size()];
    // creates a vector of geometry
    List<LineString> newGeometryVectorLine = new ArrayList<LineString>();
    GeometryFactory newfactory = new GeometryFactory();
    pm.beginTask(msg.message("utils.extracting_network_geometries"), nstream.size());
    for (int num = 1; num <= nstream.size(); num++) {
        for (int y = 0; y < activerows; y++) {
            for (int x = 0; x < activecols; x++) {
                if (!isNovalue(m1RandomIter.getSampleDouble(x, y, 0))) {
                    flow[0] = x;
                    flow[1] = y;
                    // looks for the source
                    if (netNumRandomIter.getSampleDouble(x, y, 0) == num) {
                        // channel...
                        if (sourcesNet(m1RandomIter, flow, num, netNumRandomIter)) {
                            flow_p[0] = flow[0];
                            flow_p[1] = flow[1];
                            double[] worldPosition = gridGeometry.gridToWorld(new GridCoordinates2D(flow[0], flow[1])).getCoordinate();
                            Coordinate coordSource = new Coordinate(worldPosition[0], worldPosition[1]);
                            // creates new Object Coordinate... SOURCE
                            // POINT...
                            // adds the points to the CoordinateList
                            coordlist.add(coordSource);
                            if (!go_downstream(flow, m1RandomIter.getSampleDouble(flow[0], flow[1], 0)))
                                return null;
                            // continues until the next node...
                            while (!isNovalue(m1RandomIter.getSampleDouble(flow[0], flow[1], 0)) && m1RandomIter.getSampleDouble(flow[0], flow[1], 0) != 10.0 && netNumRandomIter.getSampleDouble(flow[0], flow[1], 0) == num && !isNovalue(netNumRandomIter.getSampleDouble(flow[0], flow[1], 0))) {
                                worldPosition = gridGeometry.gridToWorld(new GridCoordinates2D(flow[0], flow[1])).getCoordinate();
                                Coordinate coordPoint = new Coordinate(worldPosition[0], worldPosition[1]);
                                // creates new Object Coordinate... CHANNEL
                                // POINT...
                                // adds new points to CoordinateList
                                coordlist.add(coordPoint);
                                flow_p[0] = flow[0];
                                flow_p[1] = flow[1];
                                if (!go_downstream(flow, m1RandomIter.getSampleDouble(flow[0], flow[1], 0)))
                                    return null;
                            }
                            worldPosition = gridGeometry.gridToWorld(new GridCoordinates2D(flow[0], flow[1])).getCoordinate();
                            Coordinate coordNode = new Coordinate(worldPosition[0], worldPosition[1]);
                            // creates new Object Coordinate... NODE
                            // POINT...
                            // adds new points to CoordinateList
                            coordlist.add(coordNode);
                        }
                    }
                }
            }
        }
        // when the channel is complete creates one new geometry (new
        // channel of the network)
        newGeometry[num - 1] = newfactory.createLineString(coordlist.toCoordinateArray());
        // adds the new geometry to the vector of geometry
        newGeometryVectorLine.add(newGeometry[num - 1]);
        // it removes every element of coordlist
        coordlist.clear();
        pm.worked(1);
    }
    pm.done();
    // create the feature type
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    // $NON-NLS-1$
    b.setName("network");
    b.setCRS(gridGeometry.getCoordinateReferenceSystem());
    // $NON-NLS-1$
    b.add("the_geom", LineString.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    SimpleFeatureCollection featureCollection = new DefaultFeatureCollection();
    int index = 0;
    for (LineString lineString : newGeometryVectorLine) {
        Object[] values = new Object[] { lineString };
        // add the values
        builder.addAll(values);
        // build the feature with provided ID
        // $NON-NLS-1$
        SimpleFeature feature = builder.buildFeature(type.getTypeName() + "." + index);
        index++;
        ((DefaultFeatureCollection) featureCollection).add(feature);
    }
    return featureCollection;
}
Also used : GeometryFactory(org.locationtech.jts.geom.GeometryFactory) SimpleFeatureTypeBuilder(org.geotools.feature.simple.SimpleFeatureTypeBuilder) CoordinateList(org.locationtech.jts.geom.CoordinateList) ArrayList(java.util.ArrayList) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) MultiLineString(org.locationtech.jts.geom.MultiLineString) LineString(org.locationtech.jts.geom.LineString) Coordinate(org.locationtech.jts.geom.Coordinate) GridCoordinates2D(org.geotools.coverage.grid.GridCoordinates2D) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder)

Example 8 with RandomIter

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

the class ModelsEngine method vectorizeDoubleMatrix.

/**
 * Takes a input raster and vectorializes it.
 *
 * @param input
 * @return
 */
public static double[] vectorizeDoubleMatrix(RenderedImage input) {
    double[] U = new double[input.getWidth() * input.getHeight()];
    RandomIter inputRandomIter = RandomIterFactory.create(input, null);
    int j = 0;
    for (int i = 0; i < input.getHeight() * input.getWidth(); i = i + input.getWidth()) {
        double[] tmp = new double[input.getWidth()];
        for (int k = 0; k < input.getWidth(); k++) {
            tmp[k] = inputRandomIter.getSampleDouble(k, j, 0);
        }
        System.arraycopy(tmp, 0, U, i, input.getWidth());
        j++;
    }
    return U;
}
Also used : RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter)

Example 9 with RandomIter

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

the class ModelsEngine method netNumbering.

/**
 * Calculate the map of netnumbering.
 *
 * @param flowGC the map of flowdirection.
 * @param netGC the map of network.
 * @param tcaGC the optional map of tca.
 * @param tcaThreshold the threshold on the tca.
 * @param pointsFC optional feature collection of points in which to split the net.
 * @param pm the monitor.
 * @return the raster of netnumbering.
 * @throws Exception
 */
public static WritableRaster netNumbering(GridCoverage2D flowGC, GridCoverage2D netGC, GridCoverage2D tcaGC, List<Geometry> points, List<NetLink> netLinksList, IHMProgressMonitor pm) throws Exception {
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(flowGC);
    int cols = regionMap.getCols();
    int rows = regionMap.getRows();
    WritableRaster netnumWR = CoverageUtilities.createWritableRaster(cols, rows, Integer.class, null, null);
    WritableRandomIter netnumIter = RandomIterFactory.createWritable(netnumWR, null);
    int flowNv = HMConstants.getIntNovalue(flowGC);
    double netNv = HMConstants.getNovalue(netGC);
    RandomIter flowIter = CoverageUtilities.getRandomIterator(flowGC);
    RandomIter netIter = CoverageUtilities.getRandomIterator(netGC);
    RandomIter tcaIter = null;
    if (tcaGC != null)
        tcaIter = CoverageUtilities.getRandomIterator(tcaGC);
    try {
        /*
             * split nodes are points that create new numbering:
             * - first points upstream on net
             * - confluences
             * - supplied points
             */
        List<FlowNode> splitNodes = new ArrayList<>();
        List<String> fixedNodesColRows = new ArrayList<>();
        // SUPPLIED POINTS
        if (points != null) {
            Envelope envelope = regionMap.toEnvelope();
            GridGeometry2D gridGeometry = flowGC.getGridGeometry();
            // snap points on net if necessary
            for (Geometry point : points) {
                Coordinate pointCoordinate = point.getCoordinate();
                if (envelope.contains(pointCoordinate)) {
                    GridCoordinates2D gridCoordinate = gridGeometry.worldToGrid(new DirectPosition2D(pointCoordinate.x, pointCoordinate.y));
                    GridNode netNode = new GridNode(netIter, cols, rows, -1, -1, gridCoordinate.x, gridCoordinate.y, netNv);
                    FlowNode flowNode = new FlowNode(flowIter, cols, rows, gridCoordinate.x, gridCoordinate.y, flowNv);
                    while (!netNode.isValid()) {
                        flowNode = flowNode.goDownstream();
                        if (flowNode == null)
                            break;
                        netNode = new GridNode(netIter, cols, rows, -1, -1, flowNode.col, flowNode.row, netNv);
                    }
                    if (flowNode != null) {
                        /*
                             * now we need to go one more down. This is necessary, since 
                             * in the later processing the netnumber channel is extracted 
                             * going downstream from the splitnodes, so the supplied point 
                             * would end up being the most upstream point of the basin.
                             * Therefore we move one down, one downstream of teh point 
                             * we want to be the basin outlet.
                             */
                        FlowNode flowNodeTmp = flowNode.goDownstream();
                        if (flowNodeTmp != null) {
                            netNode = new GridNode(netIter, cols, rows, -1, -1, flowNodeTmp.col, flowNodeTmp.row, netNv);
                            if (netNode.isValid) {
                                splitNodes.add(flowNodeTmp);
                                fixedNodesColRows.add(flowNode.col + "_" + flowNode.row);
                            }
                        }
                    }
                }
            }
        }
        // FIND CONFLUENCES AND NETWORK STARTING POINTS (MOST UPSTREAM)
        pm.beginTask("Find confluences...", rows);
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                GridNode netNode = new GridNode(netIter, cols, rows, -1, -1, c, r, netNv);
                if (netNode.isValid()) {
                    List<GridNode> validSurroundingNodes = netNode.getValidSurroundingNodes();
                    FlowNode currentflowNode = new FlowNode(flowIter, cols, rows, c, r, flowNv);
                    int enteringCount = 0;
                    for (GridNode gridNode : validSurroundingNodes) {
                        FlowNode tmpNode = new FlowNode(flowIter, cols, rows, gridNode.col, gridNode.row, flowNv);
                        List<FlowNode> enteringNodes = currentflowNode.getEnteringNodes();
                        if (enteringNodes.contains(tmpNode)) {
                            enteringCount++;
                        }
                    }
                    if (enteringCount != 1) {
                        splitNodes.add(currentflowNode);
                    }
                }
            }
            pm.worked(1);
        }
        pm.done();
        pm.message("Found split points: " + splitNodes.size());
        int channel = 1;
        pm.beginTask("Numbering network...", splitNodes.size());
        for (int i = 0; i < splitNodes.size(); i++) {
            FlowNode splitNode = splitNodes.get(i);
            int startTca = splitNode.getIntValueFromMap(tcaIter);
            setNetNumWithCheck(netnumIter, channel, splitNode);
            FlowNode lastNode = null;
            FlowNode nextNode = splitNode.goDownstream();
            int endTca;
            if (nextNode == null || splitNodes.contains(nextNode)) {
                // it is a one pixel basin
                endTca = startTca;
                lastNode = splitNode;
            } else {
                endTca = intNovalue;
                if (nextNode != null) {
                    do {
                        lastNode = nextNode;
                        endTca = nextNode.getIntValueFromMap(tcaIter);
                        setNetNumWithCheck(netnumIter, channel, nextNode);
                        nextNode = nextNode.goDownstream();
                    } while (nextNode != null && !splitNodes.contains(nextNode));
                }
            }
            int upCol = splitNode.col;
            int upRow = splitNode.row;
            int downCol = lastNode.col;
            int downRow = lastNode.row;
            int downLinkCol = -1;
            int downLinkRow = -1;
            if (nextNode != null) {
                downLinkCol = nextNode.col;
                downLinkRow = nextNode.row;
            }
            boolean isFixedNode = false;
            if (fixedNodesColRows.contains(lastNode.col + "_" + lastNode.row)) {
                isFixedNode = true;
            // System.out.println("Found fixed: " + lastNode);
            }
            NetLink link = new NetLink(channel, upCol, upRow, downCol, downRow, downLinkCol, downLinkRow, isFixedNode);
            link.setTca(endTca);
            netLinksList.add(link);
            channel++;
            pm.worked(1);
        }
        pm.done();
    } finally {
        netnumIter.done();
        flowIter.done();
        netIter.done();
        if (tcaIter != null) {
            tcaIter.done();
        }
    }
    return netnumWR;
}
Also used : GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) RegionMap(org.hortonmachine.gears.utils.RegionMap) ArrayList(java.util.ArrayList) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) MultiLineString(org.locationtech.jts.geom.MultiLineString) LineString(org.locationtech.jts.geom.LineString) Envelope(org.locationtech.jts.geom.Envelope) DirectPosition2D(org.geotools.geometry.DirectPosition2D) Geometry(org.locationtech.jts.geom.Geometry) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) Coordinate(org.locationtech.jts.geom.Coordinate) WritableRaster(java.awt.image.WritableRaster) GridCoordinates2D(org.geotools.coverage.grid.GridCoordinates2D)

Example 10 with RandomIter

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

the class OmsRasterDiff method process.

@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);
    double r1Nv = HMConstants.getNovalue(inRaster1);
    double r2Nv = HMConstants.getNovalue(inRaster2);
    WritableRaster outWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, r1Nv);
    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, r1Nv) && isNovalue(r2, r2Nv)) {
                continue;
            } else if (isNovalue(r1, r1Nv)) {
                diff = r2;
            } else if (isNovalue(r2, r2Nv)) {
                diff = r1;
            } else {
                diff = r1 - r2;
            }
            if (!doNegatives && diff < 0) {
                diff = 0.0;
            // diff = doubleNovalue;
            }
            if (pThreshold != null && diff < thres) {
                diff = r1Nv;
            }
            outIter.setSample(c, r, 0, diff);
        }
        pm.worked(1);
    }
    pm.done();
    r1Iter.done();
    r2Iter.done();
    outIter.done();
    outRaster = CoverageUtilities.buildCoverageWithNovalue("corrected", outWR, regionMap, inRaster1.getCoordinateReferenceSystem(), r1Nv);
}
Also used : 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) Execute(oms3.annotations.Execute)

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