use of org.geotoolkit.process.ProcessException in project geotoolkit by Geomatys.
the class StraightenProcess method execute.
/**
* {@inheritDoc}
*/
@Override
protected void execute() throws ProcessException {
final GridCoverage candidate = inputParameters.getValue(StraightenDescriptor.COVERAGE_IN);
// resample coverage, we want it to be 'straight', no rotation or different axe scale.
final GridGeometry gridgeom = candidate.getGridGeometry();
final CoordinateReferenceSystem crs = gridgeom.getCoordinateReferenceSystem();
final GridExtent gridenv = gridgeom.getExtent();
final MathTransform gridToCRS = gridgeom.getGridToCRS(PixelInCell.CELL_CORNER);
try {
final double[] coords = new double[2 * 5];
coords[0] = gridenv.getLow(0);
coords[1] = gridenv.getLow(1);
coords[2] = gridenv.getLow(0);
coords[3] = gridenv.getHigh(1) + 1;
coords[4] = gridenv.getHigh(0) + 1;
coords[5] = gridenv.getHigh(1) + 1;
coords[6] = gridenv.getHigh(0) + 1;
coords[7] = gridenv.getLow(1);
coords[8] = gridenv.getHigh(0) + 2;
coords[9] = gridenv.getHigh(1) + 2;
gridToCRS.transform(coords, 0, coords, 0, 5);
double minX = Math.min(Math.min(coords[0], coords[2]), Math.min(coords[4], coords[6]));
double maxX = Math.max(Math.max(coords[0], coords[2]), Math.max(coords[4], coords[6]));
double minY = Math.min(Math.min(coords[1], coords[3]), Math.min(coords[5], coords[7]));
double maxY = Math.max(Math.max(coords[1], coords[3]), Math.max(coords[5], coords[7]));
double spanX = maxX - minX;
double spanY = maxY - minY;
double scaleX = spanX / gridenv.getSize(0);
double scaleY = spanY / gridenv.getSize(1);
double scale = Math.min(scaleX, scaleY);
if (coords[0] > coords[6]) {
// x axe flip
minX = Math.min(minX, coords[8]);
}
if (coords[1] < coords[3]) {
// y axe flip
maxY = Math.max(maxY, coords[9]);
}
final AffineTransform2D outGridToCRS = new AffineTransform2D(scale, 0, 0, -scale, minX, maxY);
final GridExtent gridEnv = new GridExtent((long) (spanX / scale), (long) (spanY / scale));
final GridGeometry outgridGeom = new GridGeometry(gridEnv, PixelInCell.CELL_CORNER, outGridToCRS, crs);
final GridCoverage outCoverage = new ResampleProcess(candidate, outgridGeom.getCoordinateReferenceSystem(), outgridGeom, InterpolationCase.NEIGHBOR, null).executeNow();
outputParameters.getOrCreate(StraightenDescriptor.COVERAGE_OUT).setValue(outCoverage);
} catch (TransformException ex) {
throw new ProcessException(ex.getMessage(), this, ex);
}
}
use of org.geotoolkit.process.ProcessException in project geotoolkit by Geomatys.
the class ComputeVolumeProcess method execute.
/**
* {@inheritDoc }.
*/
@Override
protected void execute() throws ProcessException {
ArgumentChecks.ensureNonNull("inputParameters", inputParameters);
final GridCoverageResource gcReader = inputParameters.getValue(ComputeVolumeDescriptor.IN_GRIDCOVERAGE_READER);
final Geometry jtsGeom = inputParameters.getValue(ComputeVolumeDescriptor.IN_JTSGEOMETRY);
CoordinateReferenceSystem geomCRS = inputParameters.getValue(ComputeVolumeDescriptor.IN_GEOMETRY_CRS);
final Integer bIndex = inputParameters.getValue(ComputeVolumeDescriptor.IN_INDEX_BAND);
final Double zMinCeil = inputParameters.getValue(ComputeVolumeDescriptor.IN_GEOMETRY_ALTITUDE);
final double zMaxCeiling = inputParameters.getValue(ComputeVolumeDescriptor.IN_MAX_ALTITUDE_CEILING);
final int bandIndex = (bIndex == null) ? 0 : (int) bIndex;
final double zGroundCeiling = (zMinCeil == null) ? 0 : (double) zMinCeil;
final boolean positiveSens = zGroundCeiling < zMaxCeiling;
if (zGroundCeiling == zMaxCeiling) {
outputParameters.getOrCreate(ComputeVolumeDescriptor.OUT_VOLUME_RESULT).setValue(0);
return;
}
try {
/*
* geomCRS attribut should be null, we looking for find another way to define geometry CoordinateReferenceSystem.
* It may be already stipulate in JTS geometry.
*/
if (geomCRS == null) {
geomCRS = JTS.findCoordinateReferenceSystem(jtsGeom);
}
final GridGeometry covGridGeom = gcReader.getGridGeometry();
/*
* If we have no CRS informations from geometry we consider that geometry is defined in same crs as Coverage.
*/
final CoordinateReferenceSystem covCrs = covGridGeom.getCoordinateReferenceSystem();
if (geomCRS == null) {
geomCRS = covCrs;
}
final MathTransform covToGeomCRS = CRS.findOperation(covCrs, geomCRS, null).getMathTransform();
// -- next read only interest area.
final Envelope envGeom = jtsGeom.getEnvelopeInternal();
final Envelope2D envGeom2D = new Envelope2D(geomCRS, envGeom.getMinX(), envGeom.getMinY(), envGeom.getWidth(), envGeom.getHeight());
/**
****************************************
*/
final GridCoverage dem = gcReader.read(gcReader.getGridGeometry().derive().subgrid(envGeom2D).build());
final SampleDimension gsd = dem.getSampleDimensions().get(bandIndex);
final MathTransform1D zmt = gsd.getTransferFunction().orElse(null);
if (zmt == null) {
throw new ProcessException("you should stipulate MathTransform1D from sampleDimension to geophysic.", this, null);
}
final GridGeometry gg2d = dem.getGridGeometry();
InterpolationCase interpolationChoice;
// -- adapt interpolation in function of grid extend
final GridExtent gridEnv2D = gg2d.getExtent();
final int[] subSpace = gridEnv2D.getSubspaceDimensions(2);
final long gWidth = gridEnv2D.getSize(subSpace[0]);
final long gHeight = gridEnv2D.getSize(subSpace[1]);
if (gWidth < 1 || gHeight < 1) {
outputParameters.getOrCreate(ComputeVolumeDescriptor.OUT_VOLUME_RESULT).setValue(0);
return;
} else if (gWidth < 2 || gHeight < 2) {
interpolationChoice = InterpolationCase.NEIGHBOR;
} else if (gWidth < 4 || gHeight < 4) {
interpolationChoice = InterpolationCase.BILINEAR;
} else {
// -- paranoiac assert
assert gWidth >= 4 && gHeight >= 4;
interpolationChoice = InterpolationCase.BICUBIC;
}
final MathTransform gridToCrs = gg2d.getGridToCRS(PixelInCell.CELL_CENTER);
final CoordinateSystem destCS = covCrs.getCoordinateSystem();
final RenderedImage mnt = dem.render(null);
final Interpolation interpol = Interpolation.create(new PixelIterator.Builder().setIteratorOrder(SequenceType.LINEAR).create(mnt), interpolationChoice, 0, ResampleBorderComportement.EXTRAPOLATION, null);
final MathTransform gridToGeom = MathTransforms.concatenate(gridToCrs, covToGeomCRS);
final StepPixelAreaCalculator stePixCalculator;
if (covCrs instanceof GeographicCRS) {
stePixCalculator = new GeographicStepPixelAreaCalculator(PIXELSTEP, covCrs, gridToCrs);
} else {
if (destCS instanceof CartesianCS) {
// -- resolution
final double[] resolution;
try {
resolution = gg2d.getResolution(false);
} catch (IncompleteGridGeometryException ex) {
throw new ProcessException("Cannot estimate resolution", this, ex);
}
final int dimDestCS = destCS.getDimension();
final int destDim = destCS.getDimension();
final UnitConverter[] unitConverters = new UnitConverter[dimDestCS];
for (int d = 0; d < destDim; d++) {
final CoordinateSystemAxis csA = destCS.getAxis(d);
unitConverters[d] = csA.getUnit().getConverterToAny(METER);
}
// -- pixel step computing in m²
stePixCalculator = new CartesianStepPixelAreaCalculator(PIXELSTEP, unitConverters, resolution);
} else {
throw new ProcessException("Coordinate reference system configuration not supported. CRS should be instance of geographic crs or has a cartesian coordinate system.", this, null);
}
}
// -- geometry factory to create point at n step to test if it is within geometry
final GeometryFactory gf = JTS.getFactory();
// -- coordinate to test if point is within geom
final Coordinate coords = new Coordinate();
// -- image attributs
final double minx = mnt.getMinX() - 0.5;
final double miny = mnt.getMinY() - 0.5;
final double maxx = minx + mnt.getWidth();
final double maxy = miny + mnt.getHeight();
final double debx = minx + PIXELSTEP / 2.0;
final double[] pixPoint = new double[] { debx, miny + PIXELSTEP / 2.0 };
final double[] geomPoint = new double[2];
double volume = 0;
final UnitConverter hconverter;
if (!gsd.getUnits().isPresent() || Units.UNITY.equals(gsd.getUnits().get())) {
// -- unit unknowed, assume it's meters already
hconverter = METER.getConverterTo(METER);
} else {
hconverter = gsd.getUnits().get().getConverterToAny(METER);
}
while (pixPoint[1] < maxy) {
stopIfDismissed();
pixPoint[0] = debx;
while (pixPoint[0] < maxx) {
stopIfDismissed();
// -- project point in geomtry CRS
gridToGeom.transform(pixPoint, 0, geomPoint, 0, 1);
// -- test if point is within geometry.
coords.setOrdinate(0, geomPoint[0]);
coords.setOrdinate(1, geomPoint[1]);
if (jtsGeom.contains(gf.createPoint(coords))) {
// -- get interpolate value
double h = interpol.interpolate(pixPoint[0], pixPoint[1], bandIndex);
// -- projet h in geophysic value
h = zmt.transform(h);
// -- convert in meter
h = hconverter.convert(h);
// -- Verify that h value found is in appropriate interval.
if ((positiveSens && h > zGroundCeiling) || (!positiveSens && h < zGroundCeiling)) {
// -- add in volum
volume += (Math.min(Math.abs(h - zGroundCeiling), Math.abs(zMaxCeiling - zGroundCeiling))) * stePixCalculator.computeStepPixelArea(pixPoint);
}
}
pixPoint[0] += PIXELSTEP;
}
pixPoint[1] += PIXELSTEP;
}
outputParameters.getOrCreate(ComputeVolumeDescriptor.OUT_VOLUME_RESULT).setValue(volume);
} catch (Exception ex) {
throw new ProcessException(ex.getMessage(), this, ex);
}
}
use of org.geotoolkit.process.ProcessException in project geotoolkit by Geomatys.
the class Copy method execute.
/**
* {@inheritDoc }
*/
@Override
protected void execute() throws ProcessException {
final FeatureStore sourceDS = inputParameters.getValue(SOURCE_STORE);
final FeatureStore targetDS = inputParameters.getValue(TARGET_STORE);
Session targetSS = inputParameters.getValue(TARGET_SESSION);
final Boolean eraseParam = inputParameters.getValue(ERASE);
final Boolean newVersion = inputParameters.getValue(NEW_VERSION);
// Type name can be removed, it's embedded in the query param.
final String typenameParam = inputParameters.getValue(TYPE_NAME);
final Query queryParam = inputParameters.getValue(QUERY);
final boolean doCommit = targetSS == null;
final Session sourceSS = sourceDS.createSession(false);
if (targetSS == null) {
if (targetDS != null) {
targetSS = targetDS.createSession(true);
} else {
throw new ProcessException("Input target_session or target_datastore missing.", this, null);
}
}
boolean reBuildQuery = false;
final String queryName;
if (queryParam != null) {
queryName = queryParam.getTypeName();
reBuildQuery = true;
} else if (typenameParam != null) {
queryName = typenameParam;
} else {
queryName = "*";
}
final Set<GenericName> names;
if ("*".equals(queryName)) {
// all values
try {
names = sourceDS.getNames();
} catch (DataStoreException ex) {
throw new ProcessException(ex.getMessage(), this, ex);
}
} else {
// pick only the wanted names
names = new HashSet<>();
final List<String> wanted = UnmodifiableArrayList.wrap(queryName.split(","));
for (String s : wanted) {
try {
final FeatureType type = sourceDS.getFeatureType(s);
names.add(type.getName());
} catch (DataStoreException ex) {
throw new ProcessException(ex.getMessage(), this, ex);
}
}
}
final float size = names.size();
int inc = 0;
for (GenericName n : names) {
fireProgressing("Copying " + n + ".", (int) ((inc * 100f) / size), false);
try {
Query query;
if (reBuildQuery) {
Query builder = new Query();
builder.copy(queryParam);
builder.setTypeName(n);
query = builder;
} else {
query = queryParam != null ? queryParam : new Query(n);
}
insert(n, sourceSS, targetSS, query, eraseParam, newVersion);
} catch (DataStoreException ex) {
throw new ProcessException(ex.getMessage(), this, ex);
}
inc++;
}
try {
Date lastVersionDate = null;
if (doCommit) {
LOGGER.log(Level.INFO, "Commit all changes");
targetSS.commit();
// find last version
for (GenericName n : names) {
if (targetSS.getFeatureStore().getQueryCapabilities().handleVersioning()) {
final List<Version> versions = targetSS.getFeatureStore().getVersioning(n.toString()).list();
if (!versions.isEmpty()) {
if (lastVersionDate == null || versions.get(versions.size() - 1).getDate().getTime() > lastVersionDate.getTime()) {
lastVersionDate = versions.get(versions.size() - 1).getDate();
}
}
}
}
}
if (lastVersionDate != null) {
outputParameters.getOrCreate(VERSION).setValue(lastVersionDate);
}
} catch (DataStoreException ex) {
throw new ProcessException(ex.getMessage(), this, ex);
} catch (VersioningException ex) {
throw new ProcessException(ex.getMessage(), this, ex);
}
}
use of org.geotoolkit.process.ProcessException in project geotoolkit by Geomatys.
the class SampleClassifier method execute.
@Override
protected void execute() throws ProcessException {
final RenderedImage input = getImage();
if (input.getSampleModel().getNumBands() > 1) {
throw new ProcessException("Input image must be single banded.", this);
}
final ClassMap baseMapping = buildClasses();
final BufferedImage output = new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
final int minTileX = input.getMinTileX();
final int minTileY = input.getMinTileY();
final int numTiles = input.getNumXTiles() * input.getNumYTiles();
final Point firstTile = new Point(minTileX, minTileY);
if (numTiles < 2) {
processTile(firstTile, input, output, baseMapping);
} else {
final int maxXTile = input.getNumXTiles() + minTileX - 1;
final UnaryOperator<Point> nextTile = tile -> {
final boolean nextLine = tile.x >= maxXTile;
final int nextX = nextLine ? minTileX : tile.x + 1;
final int nextY = nextLine ? tile.y + 1 : tile.y;
return new Point(nextX, nextY);
};
Stream.iterate(firstTile, nextTile).limit(numTiles).parallel().forEach(tile -> SampleClassifier.processTile(tile, input, output, baseMapping.clone()));
}
outputParameters.getOrCreate(SampleClassifierDescriptor.IMAGE).setValue(output);
}
use of org.geotoolkit.process.ProcessException in project geotoolkit by Geomatys.
the class DynamicRangeStretchProcess method execute.
@Override
protected void execute() throws ProcessException {
ArgumentChecks.ensureNonNull("inputParameter", inputParameters);
final RenderedImage inputImage = inputParameters.getValue(IN_IMAGE);
final int[] bands = inputParameters.getValue(IN_BANDS);
final double[][] ranges = inputParameters.getValue(IN_RANGES);
if (bands.length < 3 || ranges.length < 3) {
throw new ProcessException("Bands and Ranges parameters must contain at least 3 components (red, green, blue).", this);
}
final SampleModel inputSampleModel = inputImage.getSampleModel();
final int inputNbBand = inputSampleModel.getNumBands();
for (int i = 0; i < bands.length; i++) {
if (bands[i] > (inputNbBand - 1)) {
throw new ProcessException("Invalid configuration, band " + bands[i] + " do not exist.", this);
}
}
final boolean noAlpha = bands.length < 4;
final BufferedImage resultImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), noAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB);
// copy data
final PixelIterator readIte = PixelIterator.create(inputImage);
final WritablePixelIterator writeIte = WritablePixelIterator.create(resultImage);
final double[] pixel = new double[inputNbBand];
final int[] rgba = new int[noAlpha ? 3 : 4];
final double[] rangeRatios = new double[ranges.length];
for (int i = 0; i < bands.length; i++) {
if (bands[i] < 0) {
continue;
} else if (ranges.length <= i) {
throw new ProcessException(String.format("%d bands defined, but only %d ranges", i, ranges.length) + i, this);
} else if (ranges[i].length < 2) {
throw new ProcessException("Bad definition for value range " + i, this);
}
final double span = ranges[i][1] - ranges[i][0];
if (span > 0) {
rangeRatios[i] = 255 / span;
} else {
rangeRatios[i] = 0;
}
}
Point position;
while (readIte.next()) {
readIte.getPixel(pixel);
position = readIte.getPosition();
writeIte.moveTo(position.x, position.y);
// calculate color
boolean hasNan = false;
for (int i = 0; i < rgba.length; i++) {
if (bands[i] < 0) {
// default value
rgba[i] = (i == 3) ? 255 : 0;
} else {
// calculate value
double v = pixel[bands[i]];
if (Double.isNaN(v)) {
hasNan = true;
break;
}
v = (v - ranges[i][0]) * rangeRatios[i];
rgba[i] = XMath.clamp((int) v, 0, 255);
}
}
if (hasNan) {
Arrays.fill(rgba, 0);
}
// write target pixels
writeIte.setPixel(rgba);
}
outputParameters.getOrCreate(OUT_IMAGE).setValue(resultImage);
}
Aggregations