Search in sources :

Example 1 with ModelsIllegalargumentException

use of org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException in project hortonmachine by TheHortonMachine.

the class Mapurl2MbtilesConverter method process.

@Execute
public void process() throws Exception {
    checkNull(inFile);
    File mapurlFile = new File(inFile);
    HashMap<String, String> metadataMap = FileUtilities.readFileToHashMap(inFile, "=", false);
    String url = metadataMap.get("url");
    if (url == null) {
        throw new ModelsIllegalargumentException("The supplied file doesn't seem to be a valid HortonMachine mapurl file.", this, pm);
    }
    if (url.endsWith("jpg")) {
        format = "jpg";
    } else {
        format = "png";
    }
    File dbFile = FileUtilities.substituteExtention(mapurlFile, "mbtiles");
    String tilesetName = FileUtilities.getNameWithoutExtention(mapurlFile);
    File folderFile = new File(mapurlFile.getParentFile(), tilesetName);
    mbtilesHelper = new MBTilesHelper();
    mbtilesHelper.open(dbFile);
    mbtilesHelper.createTables(false);
    File[] zFolders = folderFile.listFiles();
    List<File> xFolder = new ArrayList<File>();
    for (File zFolder : zFolders) {
        File[] xFiles = zFolder.listFiles();
        for (File xFile : xFiles) {
            if (xFile.isDirectory()) {
                xFolder.add(xFile);
            }
        }
    }
    final GlobalMercator mercator = new GlobalMercator();
    int minZ = 1000;
    int maxZ = -1000;
    EggClock clock = new EggClock("Time check: ", " sec");
    clock.startAndPrint(System.out);
    for (File xFile : xFolder) {
        String zStr = xFile.getParentFile().getName();
        final int z = Integer.parseInt(zStr);
        minZ = min(minZ, z);
        maxZ = max(maxZ, z);
        String xStr = xFile.getName();
        final int x = Integer.parseInt(xStr);
        final File[] yFiles = xFile.listFiles(new FilenameFilter() {

            public boolean accept(File arg0, String name) {
                boolean endsWithPng = name.endsWith("png");
                boolean endsWithJpg = name.endsWith("jpg");
                if (endsWithPng || endsWithJpg) {
                    return true;
                }
                return false;
            }
        });
        for (File yFile : yFiles) {
            String yStr = FileUtilities.getNameWithoutExtention(yFile);
            int y = Integer.parseInt(yStr);
            Envelope wsen = mercator.TileLatLonBounds(x, y, z);
            n = max(n, wsen.getMaxY());
            e = max(e, wsen.getMaxX());
            s = max(s, wsen.getMinY());
            w = max(w, wsen.getMinX());
            try {
                BufferedImage image = ImageIO.read(yFile);
                mbtilesHelper.addTile(x, y, z, image, format);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            if (imageIndex % 1000 == 0) {
                pm.message("Images inserted in db: " + imageIndex);
                clock.printTimePassedInSeconds(System.out);
            }
            imageIndex++;
        }
    }
    mbtilesHelper.fillMetadata((float) n, (float) s, (float) w, (float) e, "tilesetName", format, minZ, maxZ);
    mbtilesHelper.createIndexes();
    mbtilesHelper.close();
}
Also used : ArrayList(java.util.ArrayList) Envelope(org.locationtech.jts.geom.Envelope) BufferedImage(java.awt.image.BufferedImage) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) EggClock(org.hortonmachine.gears.utils.time.EggClock) FilenameFilter(java.io.FilenameFilter) File(java.io.File) Execute(oms3.annotations.Execute)

Example 2 with ModelsIllegalargumentException

use of org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException in project hortonmachine by TheHortonMachine.

the class OmsTmsGenerator method process.

@Execute
public void process() throws Exception {
    try {
        checkNull(inPath, pMinzoom, pMaxzoom, pWest, pEast, pSouth, pNorth);
        if (dataCrs == null) {
            if (pEpsg != null) {
                dataCrs = CrsUtilities.getCrsFromEpsg(pEpsg, null);
            } else {
                String wkt = FileUtilities.readFile(inPrj);
                dataCrs = CRS.parseWKT(wkt);
            }
        }
        String format = null;
        if (doMbtiles) {
            mbtilesHelper = new MBTilesHelper();
            File dbFolder = new File(inPath);
            File dbFile = new File(dbFolder, pName + ".mbtiles");
            ReferencedEnvelope dataBounds = new ReferencedEnvelope(pWest, pEast, pSouth, pNorth, dataCrs);
            MathTransform data2LLTransform = CRS.findMathTransform(dataCrs, DefaultGeographicCRS.WGS84);
            Envelope llEnvelope = JTS.transform(dataBounds, data2LLTransform);
            float n = (float) llEnvelope.getMaxY();
            float s = (float) llEnvelope.getMinY();
            float w = (float) llEnvelope.getMinX();
            float e = (float) llEnvelope.getMaxX();
            format = pImagetype == 0 ? "png" : "jpg";
            mbtilesHelper.open(dbFile);
            mbtilesHelper.createTables(false);
            mbtilesHelper.fillMetadata(n, s, w, e, pName, format, pMinzoom, pMaxzoom);
        }
        int threads = getDefaultThreadsNum();
        String ext = "png";
        if (pImagetype == 1) {
            ext = "jpg";
        }
        checkCancel();
        List<String> inVectors = null;
        if (inVectorFile != null && new File(inVectorFile).exists())
            inVectors = FileUtilities.readFileToLinesList(new File(inVectorFile));
        checkCancel();
        List<String> inRasters = null;
        if (inRasterFile != null && new File(inRasterFile).exists())
            inRasters = FileUtilities.readFileToLinesList(new File(inRasterFile));
        if (inRasters == null && inVectors == null) {
            throw new ModelsIllegalargumentException("No raster and vector input maps available. check your inputs.", this, pm);
        }
        if (dataCrs == null && pEpsg == null && inPrj == null) {
            throw new ModelsIllegalargumentException("No projection info available. check your inputs.", this, pm);
        }
        final CoordinateReferenceSystem mercatorCrs = CrsUtilities.getCrsFromEpsg(EPSG_MERCATOR, null);
        ReferencedEnvelope dataBounds = new ReferencedEnvelope(pWest, pEast, pSouth, pNorth, dataCrs);
        MathTransform data2MercatorTransform = CRS.findMathTransform(dataCrs, mercatorCrs);
        Envelope mercatorEnvelope = JTS.transform(dataBounds, data2MercatorTransform);
        ReferencedEnvelope mercatorBounds = new ReferencedEnvelope(mercatorEnvelope, mercatorCrs);
        checkCancel();
        if (inZoomLimitVector != null) {
            SimpleFeatureCollection zoomLimitVector = OmsVectorReader.readVector(inZoomLimitVector);
            List<Geometry> geoms = FeatureUtilities.featureCollectionToGeometriesList(zoomLimitVector, true, null);
            MultiPolygon multiPolygon = gf.createMultiPolygon(geoms.toArray(GeometryUtilities.TYPE_POLYGON));
            // convert to mercator
            Geometry multiPolygonGeom = JTS.transform(multiPolygon, data2MercatorTransform);
            zoomLimitGeometry = PreparedGeometryFactory.prepare(multiPolygonGeom);
        }
        File inFolder = new File(inPath);
        final File baseFolder = new File(inFolder, pName);
        final ImageGenerator imgGen = new ImageGenerator(pm, mercatorCrs);
        if (inWMS != null) {
            imgGen.setWMS(inWMS);
        }
        String notLoading = "Not loading non-existing file: ";
        if (inRasters != null)
            for (String rasterPath : inRasters) {
                File file = new File(rasterPath);
                if (file.exists()) {
                    imgGen.addCoveragePath(rasterPath);
                } else {
                    pm.errorMessage(notLoading + rasterPath);
                }
            }
        if (inRasterBounds != null)
            for (GridGeometry2D rasterBounds : inRasterBounds) {
                imgGen.addCoverageRegion(rasterBounds);
            }
        if (inVectors != null)
            for (String vectorPath : inVectors) {
                File file = new File(vectorPath);
                if (file.exists()) {
                    imgGen.addFeaturePath(vectorPath, null);
                } else {
                    pm.errorMessage(notLoading + vectorPath);
                }
            }
        imgGen.setLayers();
        double w = mercatorBounds.getMinX();
        double s = mercatorBounds.getMinY();
        double e = mercatorBounds.getMaxX();
        double n = mercatorBounds.getMaxY();
        final GlobalMercator mercator = new GlobalMercator();
        for (int z = pMinzoom; z <= pMaxzoom; z++) {
            checkCancel();
            // get ul and lr tile number
            int[] llTileNumber = mercator.MetersToTile(w, s, z);
            int[] urTileNumber = mercator.MetersToTile(e, n, z);
            int startXTile = llTileNumber[0];
            int startYTile = llTileNumber[1];
            int endXTile = urTileNumber[0];
            int endYTile = urTileNumber[1];
            int tileNum = 0;
            final ReferencedEnvelope levelBounds = new ReferencedEnvelope(mercatorCrs);
            ExecutorService fixedThreadPool = Executors.newFixedThreadPool(threads);
            pm.beginTask("Generating tiles at zoom level: " + z, (endXTile - startXTile + 1) * (endYTile - startYTile + 1));
            for (int i = startXTile; i <= endXTile; i++) {
                checkCancel();
                for (int j = startYTile; j <= endYTile; j++) {
                    checkCancel();
                    double[] bounds = mercator.TileBounds(i, j, z);
                    double west = bounds[0];
                    double south = bounds[1];
                    double east = bounds[2];
                    double north = bounds[3];
                    final ReferencedEnvelope tmpBounds = new ReferencedEnvelope(west, east, south, north, mercatorCrs);
                    levelBounds.expandToInclude(tmpBounds);
                    // if there is a zoom level geometry limitation, apply it
                    if (zoomLimitGeometry != null && z > pZoomLimit) {
                        double safeExtend = tmpBounds.getWidth() > tmpBounds.getHeight() ? tmpBounds.getWidth() : tmpBounds.getHeight();
                        final ReferencedEnvelope tmp = new ReferencedEnvelope(tmpBounds);
                        tmp.expandBy(safeExtend);
                        Polygon polygon = FeatureUtilities.envelopeToPolygon(tmp);
                        if (!zoomLimitGeometry.intersects(polygon)) {
                            pm.worked(1);
                            continue;
                        }
                    }
                    if (mbtilesHelper != null) {
                        final int x = i;
                        final int y = j;
                        final int zz = z;
                        final String fformat = format;
                        tileNum++;
                        Runnable runner = new Runnable() {

                            public void run() {
                                if (!cancelModule) {
                                    try {
                                        checkCancel();
                                        BufferedImage image = imgGen.getImageWithCheck(tmpBounds, TILESIZE, TILESIZE, 0.0, pCheckcolor);
                                        if (image != null) {
                                            mbtilesHelper.addTile(x, y, zz, image, fformat);
                                        }
                                    } catch (Exception e) {
                                        pm.errorMessage(e.getMessage());
                                        cancelModule = true;
                                    }
                                }
                                pm.worked(1);
                            }
                        };
                        fixedThreadPool.execute(runner);
                    } else {
                        File imageFolder = new File(baseFolder, z + "/" + i);
                        if (!imageFolder.exists()) {
                            if (!imageFolder.mkdirs()) {
                                throw new ModelsIOException("Unable to create folder:" + imageFolder, this);
                            }
                        }
                        File ignoreMediaFile = new File(imageFolder, ".nomedia");
                        ignoreMediaFile.createNewFile();
                        final File imageFile = new File(imageFolder, j + "." + ext);
                        if (imageFile.exists()) {
                            pm.worked(1);
                            continue;
                        }
                        tileNum++;
                        final String imagePath = imageFile.getAbsolutePath();
                        final ReferencedEnvelope finalBounds = tmpBounds;
                        Runnable runner = new Runnable() {

                            public void run() {
                                if (!cancelModule) {
                                    try {
                                        if (pImagetype == 1) {
                                            imgGen.dumpJpgImage(imagePath, finalBounds, TILESIZE, TILESIZE, 0.0, pCheckcolor);
                                        } else {
                                            imgGen.dumpPngImage(imagePath, finalBounds, TILESIZE, TILESIZE, 0.0, pCheckcolor);
                                        }
                                        pm.worked(1);
                                    } catch (Exception ex) {
                                        pm.errorMessage(ex.getMessage());
                                        cancelModule = true;
                                    }
                                }
                            }
                        };
                        fixedThreadPool.execute(runner);
                    }
                }
            }
            try {
                fixedThreadPool.shutdown();
                while (!fixedThreadPool.isTerminated()) {
                    Thread.sleep(100);
                }
            } catch (InterruptedException exx) {
                exx.printStackTrace();
            }
            pm.done();
            pm.message("Zoom level: " + z + " has " + tileNum + " tiles.");
        // pm.message("Boundary covered at Zoom level: " + z + ": " + levelBounds);
        // pm.message("Total boundary wanted: " + mercatorBounds);
        }
        if (mbtilesHelper != null) {
            mbtilesHelper.createIndexes();
            mbtilesHelper.close();
        } else {
            CoordinateReferenceSystem latLongCrs = CrsUtilities.getCrsFromEpsg(EPSG_LATLONG, null);
            MathTransform transform = CRS.findMathTransform(mercatorCrs, latLongCrs);
            Envelope latLongBounds = JTS.transform(mercatorBounds, transform);
            Coordinate latLongCentre = latLongBounds.centre();
            StringBuilder properties = new StringBuilder();
            properties.append("url=").append(pName).append("/ZZZ/XXX/YYY.").append(ext).append("\n");
            properties.append("minzoom=").append(pMinzoom).append("\n");
            properties.append("maxzoom=").append(pMaxzoom).append("\n");
            properties.append("center=").append(latLongCentre.y).append(" ").append(latLongCentre.x).append("\n");
            properties.append("type=tms").append("\n");
            File propFile = new File(inFolder, pName + ".mapurl");
            FileUtilities.writeFile(properties.toString(), propFile);
        }
    } catch (ModelsUserCancelException e) {
        pm.errorMessage(ModelsUserCancelException.DEFAULTMESSAGE);
    }
}
Also used : GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) MathTransform(org.opengis.referencing.operation.MathTransform) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.locationtech.jts.geom.Envelope) BufferedImage(java.awt.image.BufferedImage) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) ModelsUserCancelException(org.hortonmachine.gears.libs.exceptions.ModelsUserCancelException) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Polygon(org.locationtech.jts.geom.Polygon) MultiPolygon(org.locationtech.jts.geom.MultiPolygon) ModelsUserCancelException(org.hortonmachine.gears.libs.exceptions.ModelsUserCancelException) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) ModelsIOException(org.hortonmachine.gears.libs.exceptions.ModelsIOException) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) Geometry(org.locationtech.jts.geom.Geometry) MultiPolygon(org.locationtech.jts.geom.MultiPolygon) Coordinate(org.locationtech.jts.geom.Coordinate) ExecutorService(java.util.concurrent.ExecutorService) ImageGenerator(org.hortonmachine.gears.utils.images.ImageGenerator) ModelsIOException(org.hortonmachine.gears.libs.exceptions.ModelsIOException) File(java.io.File) Execute(oms3.annotations.Execute)

Example 3 with ModelsIllegalargumentException

use of org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException in project hortonmachine by TheHortonMachine.

the class TmsWms2Geotiff method process.

@Execute
public void process() throws Exception {
    checkNull(inServiceUrl, outRaster, inRoiPath);
    CoordinateReferenceSystem mercatorCrs = CrsUtilities.getCrsFromEpsg(EPSG_MERCATOR, null);
    CoordinateReferenceSystem latLongCrs = DefaultGeographicCRS.WGS84;
    SimpleFeatureCollection inRoi = getVector(inRoiPath);
    ReferencedEnvelope inBounds = inRoi.getBounds();
    ReferencedEnvelope latLongBounds = inBounds.transform(latLongCrs, true);
    double w = latLongBounds.getMinX();
    double s = latLongBounds.getMinY();
    double e = latLongBounds.getMaxX();
    double n = latLongBounds.getMaxY();
    int z = 18;
    if (pZoomlevel != null) {
        z = pZoomlevel;
    }
    GlobalMercator gm = new GlobalMercator();
    int[] llTileXY = gm.GoogleTile(s, w, z);
    int[] urTileXY = gm.GoogleTile(n, e, z);
    int startXTile = Math.min(llTileXY[0], urTileXY[0]);
    int endXTile = Math.max(llTileXY[0], urTileXY[0]);
    int startYTile = Math.min(llTileXY[1], urTileXY[1]);
    int endYTile = Math.max(llTileXY[1], urTileXY[1]);
    if (pSchemaType.equals(OGC_TMS)) {
        llTileXY = gm.TMSTileFromGoogleTile(llTileXY[0], llTileXY[1], z);
        urTileXY = gm.TMSTileFromGoogleTile(urTileXY[0], urTileXY[1], z);
    }
    startXTile = Math.min(llTileXY[0], urTileXY[0]);
    endXTile = Math.max(llTileXY[0], urTileXY[0]);
    startYTile = Math.min(llTileXY[1], urTileXY[1]);
    endYTile = Math.max(llTileXY[1], urTileXY[1]);
    int tilesCountX = endXTile - startXTile + 1;
    int tilesCountY = endYTile - startYTile + 1;
    int width = tilesCountX * tileSize;
    int height = tilesCountY * tileSize;
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) img.getGraphics();
    int tileNum = 0;
    final ReferencedEnvelope finalMercatorBounds = new ReferencedEnvelope(mercatorCrs);
    pm.beginTask("Getting tiles at zoom level: " + z, (endXTile - startXTile + 1));
    int runningXPix = 0;
    int runningYPix = 0;
    for (int x = startXTile; x <= endXTile; x++) {
        for (int y = startYTile; y <= endYTile; y++) {
            tileNum++;
            int yy = y;
            if (pSchemaType.equalsIgnoreCase(GOOGLE))
                yy = (int) ((Math.pow(2, z) - 1) - y);
            double[] bounds = gm.TileBounds(x, yy, z);
            double west = bounds[0];
            double south = bounds[1];
            double east = bounds[2];
            double north = bounds[3];
            final ReferencedEnvelope tmpBounds = new ReferencedEnvelope(west, east, south, north, mercatorCrs);
            finalMercatorBounds.expandToInclude(tmpBounds);
            String tmp = "";
            if (pSourceType.equals(TMS)) {
                tmp = inServiceUrl.replaceFirst("ZZZ", String.valueOf(z));
                tmp = tmp.replaceFirst("XXX", String.valueOf(x));
                tmp = tmp.replaceFirst("YYY", String.valueOf(y));
            } else if (pSourceType.equals(WMS)) {
                ReferencedEnvelope llTB = tmpBounds.transform(latLongCrs, true);
                tmp = inServiceUrl.replaceFirst("SSS", String.valueOf(llTB.getMinY()));
                tmp = tmp.replaceFirst("NNN", String.valueOf(llTB.getMaxY()));
                tmp = tmp.replaceFirst("WWW", String.valueOf(llTB.getMinX()));
                tmp = tmp.replaceFirst("EEE", String.valueOf(llTB.getMaxX()));
            } else {
                throw new ModelsIllegalargumentException("Source Type can be only 0 or 1.", this);
            }
            // System.out.println(x + "/" + y + ": " + tmp);
            URL url = new URL(tmp);
            try (InputStream imgStream = url.openStream()) {
                BufferedImage tileImg = ImageIO.read(imgStream);
                g2d.drawImage(tileImg, runningXPix, runningYPix, null);
                if (doDebug) {
                    g2d.setColor(Color.RED);
                    g2d.drawRect(runningXPix, runningYPix, tileSize, tileSize);
                    String tileDescr = x + "/" + y + "/" + z;
                    g2d.drawString(tileDescr, runningXPix + 10, runningYPix + 20);
                }
            } catch (Exception ex) {
                pm.errorMessage("Unable to get image: " + tmp);
            }
            runningYPix += tileSize;
        }
        runningXPix += tileSize;
        runningYPix = 0;
        pm.worked(1);
    }
    pm.done();
    pm.message("Zoom level: " + z + " has " + tileNum + " tiles.");
    double ww = finalMercatorBounds.getMinX();
    double ss = finalMercatorBounds.getMinY();
    double ee = finalMercatorBounds.getMaxX();
    double nn = finalMercatorBounds.getMaxY();
    double xres = (ee - ww) / width;
    double yres = (nn - ss) / height;
    RegionMap envelopeParams = new RegionMap();
    envelopeParams.put(CoverageUtilities.NORTH, nn);
    envelopeParams.put(CoverageUtilities.SOUTH, ss);
    envelopeParams.put(CoverageUtilities.WEST, ww);
    envelopeParams.put(CoverageUtilities.EAST, ee);
    envelopeParams.put(CoverageUtilities.XRES, xres);
    envelopeParams.put(CoverageUtilities.YRES, yres);
    envelopeParams.put(CoverageUtilities.ROWS, (double) height);
    envelopeParams.put(CoverageUtilities.COLS, (double) width);
    GridCoverage2D coverage = CoverageUtilities.buildCoverage("tmsraster", img, envelopeParams, mercatorCrs);
    OmsRasterWriter.writeRaster(outRaster, coverage);
}
Also used : GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) InputStream(java.io.InputStream) RegionMap(org.hortonmachine.gears.utils.RegionMap) BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Graphics2D(java.awt.Graphics2D) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Execute(oms3.annotations.Execute)

Example 4 with ModelsIllegalargumentException

use of org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException 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 5 with ModelsIllegalargumentException

use of org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException in project hortonmachine by TheHortonMachine.

the class OmsMapcalc method process.

@SuppressWarnings("nls")
@Execute
public void process() throws Exception {
    if (!concatOr(outRaster == null, doReset)) {
        return;
    }
    String script = pFunction;
    script = script.trim();
    Jiffle jiffle = new Jiffle();
    jiffle.setScript(script);
    jiffle.compile();
    JiffleDirectRuntime jiffleRuntime = jiffle.getRuntimeInstance();
    CoordinateTransform jiffleCRS = null;
    // gather maps
    for (GridCoverage2D mapGC : inRasters) {
        if (regionParameters == null) {
            regionParameters = CoverageUtilities.getRegionParamsFromGridCoverage(mapGC);
            crs = mapGC.getCoordinateReferenceSystem();
            worldBounds = mapGC.getEnvelope2D().getBounds2D();
            Rectangle gridBounds = mapGC.getGridGeometry().getGridRange2D().getBounds();
            jiffleCRS = getTransform(worldBounds, gridBounds);
            double xRes = regionParameters.get(CoverageUtilities.XRES).doubleValue();
            double yRes = regionParameters.get(CoverageUtilities.YRES).doubleValue();
            jiffleRuntime.setWorldByResolution(worldBounds, xRes, yRes);
        }
        RenderedImage renderedImage = mapGC.getRenderedImage();
        // add map
        String name = mapGC.getName().toString();
        jiffleRuntime.setSourceImage(name, renderedImage, jiffleCRS);
    }
    if (regionParameters == null) {
        throw new ModelsIllegalargumentException("No map has been supplied.", this.getClass().getSimpleName(), pm);
    }
    int nCols = regionParameters.get(CoverageUtilities.COLS).intValue();
    int nRows = regionParameters.get(CoverageUtilities.ROWS).intValue();
    long pixelsNum = (long) nCols * nRows;
    if (pixelsNum < totalCount) {
        totalCount = pixelsNum;
    }
    updateInterval = pixelsNum / totalCount;
    String destName = jiffleRuntime.getDestinationVarNames()[0];
    WritableRenderedImage destImg = ImageUtils.createConstantImage(nCols, nRows, 0d);
    jiffleRuntime.setDestinationImage(destName, destImg, jiffleCRS);
    jiffleRuntime.evaluateAll(new NullProgressListener());
    outRaster = CoverageUtilities.buildCoverage(destName, destImg, regionParameters, crs);
// // create the executor
// JiffleExecutor executor = new JiffleExecutor();
// JiffleEventListener listener = new JiffleEventListener(){
// 
// @Override
// public void onFailureEvent( JiffleEvent event ) {
// 
// }
// 
// @Override
// public void onCompletionEvent( JiffleEvent event ) {
// JiffleExecutorResult result = event.getResult();
// Map<String, RenderedImage> imgMap = result.getImages();
// RenderedImage destImage = imgMap.get(destName);
// outRaster = CoverageUtilities.buildCoverage(destName, destImage, regionParameters, crs);
// executor.shutdown();
// }
// };
// executor.addEventListener(listener);
// 
// executor.submit(jiffleRuntime, new JiffleProgressListener(){
// private long count = 0;
// public void update( long done ) {
// if (count == done) {
// pm.worked(1);
// count = count + updateInterval;
// }
// }
// 
// public void start() {
// pm.beginTask("Processing maps...", (int) totalCount);
// }
// 
// public void setUpdateInterval( double propPixels ) {
// }
// 
// public void setUpdateInterval( long numPixels ) {
// }
// 
// public void setTaskSize( long numPixels ) {
// count = updateInterval;
// }
// 
// public long getUpdateInterval() {
// if (updateInterval == 0) {
// return 1;
// }
// return updateInterval;
// }
// 
// public void finish() {
// pm.done();
// }
// });
}
Also used : GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) Jiffle(it.geosolutions.jaiext.jiffle.Jiffle) Rectangle(java.awt.Rectangle) JiffleDirectRuntime(it.geosolutions.jaiext.jiffle.runtime.JiffleDirectRuntime) WritableRenderedImage(java.awt.image.WritableRenderedImage) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) NullProgressListener(it.geosolutions.jaiext.jiffle.runtime.NullProgressListener) WritableRenderedImage(java.awt.image.WritableRenderedImage) RenderedImage(java.awt.image.RenderedImage) CoordinateTransform(it.geosolutions.jaiext.jiffle.runtime.CoordinateTransform) AffineCoordinateTransform(it.geosolutions.jaiext.jiffle.runtime.AffineCoordinateTransform) Execute(oms3.annotations.Execute)

Aggregations

ModelsIllegalargumentException (org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException)99 Execute (oms3.annotations.Execute)75 ArrayList (java.util.ArrayList)31 File (java.io.File)30 SimpleFeature (org.opengis.feature.simple.SimpleFeature)29 Geometry (org.locationtech.jts.geom.Geometry)28 DefaultFeatureCollection (org.geotools.feature.DefaultFeatureCollection)27 Coordinate (org.locationtech.jts.geom.Coordinate)27 RegionMap (org.hortonmachine.gears.utils.RegionMap)25 WritableRaster (java.awt.image.WritableRaster)24 WritableRandomIter (javax.media.jai.iterator.WritableRandomIter)20 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)19 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)18 RandomIter (javax.media.jai.iterator.RandomIter)16 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)16 Point (org.locationtech.jts.geom.Point)14 GridGeometry2D (org.geotools.coverage.grid.GridGeometry2D)13 SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)13 LineString (org.locationtech.jts.geom.LineString)13 GridCoverage2D (org.geotools.coverage.grid.GridCoverage2D)12