use of org.hortonmachine.gears.libs.monitor.IHMProgressMonitor in project hortonmachine by TheHortonMachine.
the class SqlTemplatesAndActions method doTiles.
private static void doTiles(GuiBridgeHandler guiBridge, DatabaseViewer databaseViewer, boolean isRaster) {
try {
String label = isRaster ? "raster" : "vector";
FileFilter fileFilter = isRaster ? HMConstants.rasterFileFilter : HMConstants.vectorFileFilter;
String title = "Open " + label + " file";
File[] openFiles = GuiUtilities.showOpenFilesDialog(databaseViewer, title, true, PreferencesHandler.getLastFile(), fileFilter);
if (openFiles != null && openFiles.length > 0) {
try {
PreferencesHandler.setLastPath(openFiles[0].getAbsolutePath());
} catch (Exception e1) {
logger.insertError("SqlTemplatesAndActions", "ERROR", e1);
}
} else {
return;
}
try {
String targetEpsg = "epsg:" + GeopackageCommonDb.MERCATOR_SRID;
CoordinateReferenceSystem mercatorCrs = CrsUtilities.getCrsFromEpsg(targetEpsg, null);
GeopackageCommonDb db = (GeopackageCommonDb) databaseViewer.currentConnectedSqlDatabase;
List<FeatureEntry> features4326 = db.features();
PreparedGeometry limitsGeom3857 = null;
if (features4326.size() > 0) {
List<String> names = features4326.stream().map(f -> f.getTableName()).collect(Collectors.toList());
String selectedTable = GuiUtilities.showComboDialog(databaseViewer, "Area of interest", "It is possible to use one of the vector tables as area of interest. Tiles outside the area will be ignored.", names.toArray(new String[0]), "");
if (selectedTable != null) {
SqlName tName = SqlName.m(selectedTable);
GeometryColumn gc = db.getGeometryColumnsForTable(tName);
List<Geometry> geometries = db.getGeometriesIn(tName, (Envelope) null, (String[]) null);
int dataSrid = db.feature(tName).getSrid();
List<Geometry> geometries3857;
if (dataSrid == GeopackageCommonDb.MERCATOR_SRID) {
geometries3857 = geometries;
} else {
String sourceEpsg = "epsg:" + dataSrid;
CoordinateReferenceSystem sourceCRS = CrsUtilities.getCrsFromEpsg(sourceEpsg, null);
;
MathTransform transform = CRS.findMathTransform(sourceCRS, mercatorCrs);
geometries3857 = geometries.stream().map(g -> {
try {
return JTS.transform(g, transform);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}).collect(Collectors.toList());
}
if (gc.geometryType.isPolygon()) {
// use polygons
Geometry union = CascadedPolygonUnion.union(geometries3857);
limitsGeom3857 = PreparedGeometryFactory.prepare(union);
} else {
// use envelopes
Envelope env = new Envelope();
for (Geometry geometry : geometries3857) {
env.expandToInclude(geometry.getEnvelopeInternal());
}
Polygon polyEnv = GeometryUtilities.createPolygonFromEnvelope(env);
limitsGeom3857 = PreparedGeometryFactory.prepare(polyEnv);
}
}
}
String nameForTable = FileUtilities.getNameWithoutExtention(openFiles[0]);
String[] zoomLevels = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" };
HashMap<String, String[]> fields2ValuesMap = new HashMap<>();
String newTableLabel = "name of the new table";
String minZoomLevelLabel = "min zoom level";
String maxZoomLevelLabel = "max zoom level";
fields2ValuesMap.put(minZoomLevelLabel, zoomLevels);
fields2ValuesMap.put(maxZoomLevelLabel, zoomLevels);
String[] result = //
GuiUtilities.showMultiInputDialog(//
databaseViewer, //
"Select parameters", //
new String[] { newTableLabel, minZoomLevelLabel, maxZoomLevelLabel }, //
new String[] { nameForTable, "8", "16" }, null);
if (result == null) {
return;
}
PreparedGeometry _limitsGeom3857 = limitsGeom3857;
final LogConsoleController logConsole = new LogConsoleController(null);
IHMProgressMonitor pm = logConsole.getProgressMonitor();
Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
new Thread(() -> {
try {
logConsole.beginProcess("Import " + label + " to tileset");
pm.message("Checking input parameters...");
String _nameForTable = result[0];
int minZoom = 8;
int maxZoom = 16;
try {
minZoom = Integer.parseInt(result[1]);
maxZoom = Integer.parseInt(result[2]);
} catch (Exception e1) {
pm.errorMessage("The min or max zoomlevel were not entered correctly, exiting.");
return;
}
for (File file : openFiles) {
String dataPath = file.getAbsolutePath();
Envelope envelopeInternal = null;
if (isRaster) {
AbstractGridFormat format = GridFormatFinder.findFormat(file);
AbstractGridCoverage2DReader reader = format.getReader(file, null);
GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope();
CoordinateReferenceSystem crs = reader.getCoordinateReferenceSystem();
double[] ll = originalEnvelope.getLowerCorner().getCoordinate();
double[] ur = originalEnvelope.getUpperCorner().getCoordinate();
ReferencedEnvelope renv = new ReferencedEnvelope(ll[0], ur[0], ll[1], ur[1], crs);
envelopeInternal = renv.transform(mercatorCrs, true);
} else {
ReferencedEnvelope renv = OmsVectorReader.readEnvelope(file.getAbsolutePath());
envelopeInternal = renv.transform(mercatorCrs, true);
}
ITilesProducer tileProducer = new GeopackageTilesProducer(pm, dataPath, isRaster, minZoom, maxZoom, 256, _limitsGeom3857);
String description = "HM import of " + openFiles[0].getName();
int addedTiles = ((GeopackageCommonDb) databaseViewer.currentConnectedSqlDatabase).addTilestable(SqlName.m(_nameForTable), description, envelopeInternal, tileProducer);
pm.message("Inserted " + addedTiles + " new tiles.");
}
databaseViewer.refreshDatabaseTree();
} catch (Exception ex) {
pm.errorMessage(ex.getLocalizedMessage());
} finally {
logConsole.finishProcess();
logConsole.stopLogging();
Logger.INSTANCE.resetStreams();
}
}, "DatabaseController->Import " + label + " to tileset").start();
} catch (Exception e1) {
GuiUtilities.handleError(databaseViewer, e1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
use of org.hortonmachine.gears.libs.monitor.IHMProgressMonitor in project hortonmachine by TheHortonMachine.
the class CoverageUtilities method gridcoverageToCellPolygons.
/**
* Extracts a list of polygons from the cell bounds of a given {@link GridCoverage2D coverage}.
*
* <p><b>Note that the cells are added in a rows
* and cols order (for each row evaluate each column).</b></p>
*
* <p>The userdata of the geometry contains the value of the raster.
*
* @param coverage the coverage to use.
* @param keepCoordinatePredicate an optional predicate to filter out some of the cells.
* @return the list of envelope geometries.
*/
public static List<Polygon> gridcoverageToCellPolygons(GridCoverage2D coverage, Predicate<Coordinate> keepCoordinatePredicate, boolean doIncrementalMerge, IHMProgressMonitor pm) {
if (pm == null) {
pm = new DummyProgressMonitor();
}
RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(coverage);
double west = regionMap.getWest();
double north = regionMap.getNorth();
double xres = regionMap.getXres();
double yres = regionMap.getYres();
int cols = regionMap.getCols();
int rows = regionMap.getRows();
int everyRows = 1000;
GeometryFactory gf = GeometryUtilities.gf();
RandomIter iter = CoverageUtilities.getRandomIterator(coverage);
List<Geometry> bigPolygons = new ArrayList<Geometry>();
List<Polygon> polygons = new ArrayList<Polygon>();
pm.beginTask("Vectorizing raster cells...", rows);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
double w = west + xres * c;
double e = w + xres;
double n = north - yres * r;
double s = n - yres;
if (keepCoordinatePredicate != null && !keepCoordinatePredicate.test(new Coordinate(w + xres / 2, s + yres / 2))) {
continue;
}
Coordinate[] coords = new Coordinate[5];
coords[0] = new Coordinate(w, n);
coords[1] = new Coordinate(e, n);
coords[2] = new Coordinate(e, s);
coords[3] = new Coordinate(w, s);
coords[4] = new Coordinate(w, n);
LinearRing linearRing = gf.createLinearRing(coords);
Polygon polygon = gf.createPolygon(linearRing, null);
polygons.add(polygon);
double value = iter.getSampleDouble(c, r, 0);
polygon.setUserData(value);
}
if (doIncrementalMerge && ((r > 0 && r % everyRows == 0) || r == rows - 1)) {
// merge same value to single geometries to save memory
Map<Integer, List<Geometry>> collected = polygons.parallelStream().filter(poly -> ((Number) poly.getUserData()).doubleValue() != HMConstants.doubleNovalue).collect(Collectors.groupingBy(poly -> ((Number) poly.getUserData()).intValue()));
pm.message(r + " of " + rows);
polygons = new ArrayList<Polygon>();
int size = collected.size();
int count = 0;
for (Entry<Integer, List<Geometry>> entry : collected.entrySet()) {
count++;
if (count % 10 == 0)
pm.message(" -> " + count + " of " + size);
Integer basinId = entry.getKey();
List<Geometry> value = entry.getValue();
Geometry tmpGeom = CascadedPolygonUnion.union(value);
for (int i = 0; i < tmpGeom.getNumGeometries(); i++) {
Polygon geometryN = (Polygon) tmpGeom.getGeometryN(i);
geometryN.setUserData(basinId);
bigPolygons.add(geometryN);
}
}
}
pm.worked(1);
}
pm.done();
if (doIncrementalMerge) {
polygons = new ArrayList<Polygon>();
for (Geometry tmpGeom : bigPolygons) {
Object userData = tmpGeom.getUserData();
for (int i = 0; i < tmpGeom.getNumGeometries(); i++) {
Polygon geometryN = (Polygon) tmpGeom.getGeometryN(i);
geometryN.setUserData(userData);
polygons.add(geometryN);
}
}
}
return polygons;
}
use of org.hortonmachine.gears.libs.monitor.IHMProgressMonitor in project hortonmachine by TheHortonMachine.
the class LasOnDtmBuildingsExtractor method process.
@Execute
public void process() throws Exception {
checkNull(inLas, inDtm, outBuildings);
SimpleFeatureCollection buildingsFC = null;
GridCoverage2D inDtmGC = null;
try (ALasDataManager lasHandler = ALasDataManager.getDataManager(new File(inLas), inDtmGC, 0, null)) {
lasHandler.open();
ReferencedEnvelope3D e = lasHandler.getEnvelope3D();
if (pRasterResolution != null) {
OmsRasterReader reader = new OmsRasterReader();
reader.file = inDtm;
reader.pNorth = e.getMaxY();
reader.pSouth = e.getMinY();
reader.pWest = e.getMinX();
reader.pEast = e.getMaxX();
reader.pXres = pRasterResolution;
reader.pYres = pRasterResolution;
reader.process();
inDtmGC = reader.outRaster;
} else {
inDtmGC = getRaster(inDtm);
RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inDtmGC);
pRasterResolution = regionMap.getXres();
}
Envelope2D envelope2d = inDtmGC.getEnvelope2D();
Polygon regionPolygon = FeatureUtilities.envelopeToPolygon(envelope2d);
WritableRaster[] buildingsHolder = new WritableRaster[1];
GridCoverage2D newBuildingsRaster = CoverageUtilities.createCoverageFromTemplate(inDtmGC, 1.0, buildingsHolder);
GridGeometry2D gridGeometry = newBuildingsRaster.getGridGeometry();
java.awt.Point p = new java.awt.Point();
IHMProgressMonitor pm = new LogProgressMonitor();
pm.beginTask("Reading points...", IHMProgressMonitor.UNKNOWN);
List<LasRecord> pointsInGeometry = lasHandler.getPointsInGeometry(regionPolygon, true);
pm.done();
pm.beginTask("Buildings filtering...", (int) pointsInGeometry.size());
for (LasRecord dot : pointsInGeometry) {
Coordinate c = new Coordinate(dot.x, dot.y);
if (!envelope2d.contains(dot.x, dot.y)) {
continue;
}
double dtmValue = CoverageUtilities.getValue(inDtmGC, c);
double height = abs(dot.z - dtmValue);
CoverageUtilities.colRowFromCoordinate(c, gridGeometry, p);
if (height < pDtmThres) {
buildingsHolder[0].setSample(p.x, p.y, 0, doubleNovalue);
}
pm.worked(1);
}
pm.done();
OmsMorpher morpher = new OmsMorpher();
morpher.pm = pm;
morpher.inMap = newBuildingsRaster;
morpher.pMode = Variables.OPEN;
morpher.process();
newBuildingsRaster = morpher.outMap;
OmsVectorizer buildingsVectorizer = new OmsVectorizer();
buildingsVectorizer.pm = pm;
buildingsVectorizer.inRaster = newBuildingsRaster;
buildingsVectorizer.doRemoveHoles = true;
double minAreaInCells = pMinArea / pRasterResolution / pRasterResolution;
buildingsVectorizer.pThres = minAreaInCells;
buildingsVectorizer.fDefault = "rast";
buildingsVectorizer.process();
buildingsFC = buildingsVectorizer.outVector;
dumpVector(buildingsFC, outBuildings);
if (doSmoothing && outCleanBuildings != null) {
// smooth
SimpleFeatureCollection smoothedFC = smoothBuildings(pDensifyResolution, buildingsFC);
// remove trees
DefaultFeatureCollection removedAndSmoothedFC = removeNonBuildings(lasHandler, smoothedFC, inDtmGC, pBuildingsBuffer);
dumpVector(removedAndSmoothedFC, outCleanBuildings);
}
}
}
Aggregations