Search in sources :

Example 1 with Weight

use of org.geotoolkit.processing.science.drift.Weight in project geotoolkit by Geomatys.

the class Predictor method compute.

private List<Output> compute(final Instant startTime, final Instant endTime, final PredictionContext ctx, final MeteoDataset.TimeSet meteo) throws ProcessException {
    final double totalSeconds = startTime.until(endTime, ChronoUnit.SECONDS);
    boolean newDay = false;
    Instant nextDay = startTime.plus(1, ChronoUnit.DAYS);
    Instant stepTime = startTime;
    // TODO : We should think about a better way of managing output grid, because here we waste a lot of space.
    final double[] globalProba = new double[ctx.grid.width * ctx.grid.height];
    final double[] dayProba = new double[globalProba.length];
    final List<Output> outputs = new ArrayList<>();
    // When computing point drift, we'll add a point for each weight available. As we don't want this amount to grow
    // past a configured maximum, we have to purge available points before each computing pass.
    final int maxAllowedPoints = ctx.points.maxPts / (ctx.weights.length + 1);
    do {
        final long timePassed = startTime.until(stepTime, ChronoUnit.SECONDS);
        fireProgressing("Drifting: " + stepTime, (float) (timePassed / totalSeconds) * 100f, false);
        MeteoDataset.Snapshot snapshot = meteo.setTime(stepTime).map(calibration -> calibration.setHorizontalComponent(ctx.grid.model.getEnvelope())).orElse(null);
        if (snapshot == null)
            break;
        ctx.points.removeLeastProbable(maxAllowedPoints);
        final double[] stepProba = advance(ctx, snapshot);
        if (stepProba == null)
            break;
        // TODO : add abstraction here : we could reduce loop by iterating only over a rectangle where probabilities
        // have really been updated.
        IntStream.range(0, dayProba.length).parallel().forEach(i -> {
            dayProba[i] += stepProba[i];
            globalProba[i] += stepProba[i];
        });
        newDay = stepTime.isAfter(nextDay);
        if (newDay) {
            nextDay = nextDay.plus(1, ChronoUnit.DAYS);
            outputs.add(new Output(dayProba, ctx.grid.width, ctx.grid.height));
            Arrays.fill(dayProba, 0);
        }
    } while ((stepTime = ctx.step(stepTime)).isBefore(endTime));
    if (stepTime.equals(startTime)) {
        throw new ProcessException("No data available for time: " + stepTime, this);
    }
    if (!newDay) {
        outputs.add(new Output(dayProba, ctx.grid.width, ctx.grid.height));
    }
    outputs.add(new Output(globalProba, ctx.grid.width, ctx.grid.height));
    outputParameters.getOrCreate(ACTUAL_END_TIMESTAMP).setValue(stepTime.toEpochMilli());
    return outputs;
}
Also used : IntStream(java.util.stream.IntStream) Output(org.geotoolkit.processing.science.drift.Output) Arrays(java.util.Arrays) GridGeometry(org.apache.sis.coverage.grid.GridGeometry) CRS(org.apache.sis.referencing.CRS) PixelInCell(org.opengis.referencing.datum.PixelInCell) AffineTransform2D(org.apache.sis.internal.referencing.j2d.AffineTransform2D) HashMap(java.util.HashMap) NoninvertibleTransformException(org.opengis.referencing.operation.NoninvertibleTransformException) Supplier(java.util.function.Supplier) AbstractProcess(org.geotoolkit.processing.AbstractProcess) ArrayList(java.util.ArrayList) SingleCRS(org.opengis.referencing.crs.SingleCRS) Duration(java.time.Duration) Map(java.util.Map) AxisDirections(org.apache.sis.internal.referencing.AxisDirections) ProcessException(org.geotoolkit.process.ProcessException) DataStoreException(org.apache.sis.storage.DataStoreException) Path(java.nio.file.Path) GridCoverageResource(org.apache.sis.storage.GridCoverageResource) DirectPosition(org.opengis.geometry.DirectPosition) TransformException(org.opengis.referencing.operation.TransformException) Weight(org.geotoolkit.processing.science.drift.Weight) PrintStream(java.io.PrintStream) Parameters(org.apache.sis.parameter.Parameters) Files(java.nio.file.Files) PointReference(org.geotoolkit.processing.science.drift.v2.PointBucket.PointReference) ProcessDescriptor(org.geotoolkit.process.ProcessDescriptor) IOException(java.io.IOException) Vector2d(org.geotoolkit.geometry.math.Vector2d) AffineTransform(java.awt.geom.AffineTransform) Instant(java.time.Instant) List(java.util.List) DirectPosition2D(org.apache.sis.geometry.DirectPosition2D) InvalidRangeException(ucar.ma2.InvalidRangeException) ChronoUnit(java.time.temporal.ChronoUnit) ParameterValueGroup(org.opengis.parameter.ParameterValueGroup) MathTransform(org.opengis.referencing.operation.MathTransform) Optional(java.util.Optional) GridExtent(org.apache.sis.coverage.grid.GridExtent) Utilities.setTime(org.geotoolkit.processing.science.drift.v2.Utilities.setTime) PredictorDescriptor(org.geotoolkit.processing.science.drift.v2.PredictorDescriptor) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) FactoryException(org.opengis.util.FactoryException) Instant(java.time.Instant) ArrayList(java.util.ArrayList) ProcessException(org.geotoolkit.process.ProcessException) Output(org.geotoolkit.processing.science.drift.Output)

Example 2 with Weight

use of org.geotoolkit.processing.science.drift.Weight in project geotoolkit by Geomatys.

the class Predictor method advance.

/**
 * /!\ Can return null
 *
 * @param ctx
 * @param uv
 * @return The new snapshot of probabilities for given data snapshot. Will be null if we cannot advance anymore.
 *
 * @throws ProcessException
 */
private double[] advance(final PredictionContext ctx, MeteoDataset.Snapshot uv) throws ProcessException {
    final Vector2d move = new Vector2d();
    final CoordinateReferenceSystem workCrs = ctx.grid.model.getCoordinateReferenceSystem();
    final SingleCRS workHorizontal = CRS.getHorizontalComponent(workCrs);
    if (workHorizontal == null) {
        throw new ProcessException("Cannot identify neither easting nor northing in configured coordinate reference system.", this);
    }
    final int xAxis = AxisDirections.indexOfColinear(workCrs.getCoordinateSystem(), workHorizontal.getCoordinateSystem());
    final int yAxis = xAxis + 1;
    final DirectPosition2D location = new DirectPosition2D(workCrs);
    // TODO: try to parallelize. Point bucket is no synchronized, but it may be
    final HashMap<PointReference, List<PointReference>> movements = new HashMap<>((int) (ctx.points.references.size() * 1.3f));
    final PointReference[] refs = ctx.points.references.toArray(new PointReference[ctx.points.references.size()]);
    for (PointBucket.PointReference ref : refs) {
        ref.read(location);
        final Optional<Vector2d> currentOpt = uv.current.evaluate(location);
        if (!currentOpt.isPresent()) {
            // No more data on current point. All we can do is evince it from processing, hoping that other points
            // are still in the game.
            ctx.points.remove(ref);
            continue;
        }
        final Vector2d current = currentOpt.get();
        final Vector2d wind = uv.wind.evaluate(location).orElseGet(// TODO : should we just ignore wind here ?
        RANDOM_NOISE);
        /*
             * At this point (easting, northing) is the projected coordinates in metres and (xStart, yStart)
             * is the same position in grid coordinates. Now compute different possible drift speeds.
             */
        final List<PointReference> children = new ArrayList<>(ctx.weights.length);
        for (final Weight w : ctx.weights) {
            final double pw = ref.getWeight() * w.probability;
            // if (pw <= ctx.probabilityThreshold) {
            // continue;
            // }
            wind.scale(w.wind);
            current.scale(w.current);
            move.x = wind.x + current.x;
            move.y = wind.y + current.y;
            move.scale(ctx.timestep.getSeconds());
            final double[] movedLocation = location.getCoordinate();
            movedLocation[0] += move.x;
            movedLocation[1] += move.y;
            children.add(ctx.points.add(movedLocation, pw));
        }
        if (children.size() > 0) {
            movements.put(ref, children);
        }
    }
    if (movements.isEmpty())
        return null;
    try {
        ctx.points.refreshGrid();
    } catch (TransformException ex) {
        throw new ProcessException("Cannot project geo-points on output grid", this, ex);
    }
    final double[] probabilityChanges = new double[ctx.grid.width * ctx.grid.height];
    // Number of points evaluated at this step in the output grid.
    int numOnGrid = 0;
    for (Map.Entry<PointReference, List<PointReference>> entry : movements.entrySet()) {
        final PointReference origin = entry.getKey();
        origin.readInGrid(location);
        ctx.points.remove(origin);
        // TODO : check order of grid axes
        final double xStart = location.getOrdinate(xAxis);
        final double yStart = location.getOrdinate(yAxis);
        double Δxi = Double.NaN;
        double Δyi = Double.NaN;
        // TODO : this code has been copied without proper understanding. We should review it and make it more lisible.
        for (PointReference child : entry.getValue()) {
            child.readInGrid(location);
            final double x1 = location.getOrdinate(xAxis);
            final double y1 = location.getOrdinate(yAxis);
            double xi = xStart;
            double yi = yStart;
            // is (xi,yi) on (x₀,y₀)-(x₁,y₁) line and inside (x₀, y₀, x₀+1, y₀+1) cell?
            boolean isValid;
            do {
                int gx = (int) xi;
                int gy = (int) yi;
                final double x0 = xi;
                final double y0 = yi;
                final double Δx = x1 - x0;
                final double Δy = y1 - y0;
                isValid = (Δx > 0) ? ((xi = Math.floor(x0) + 1) < x1) : (Δx < 0) && ((xi = Math.ceil(x0) - 1) >= x1);
                if (isValid) {
                    Δxi = xi - x0;
                    Δyi = Δy * (Δxi / Δx);
                    yi = Δyi + y0;
                    final double f = Math.floor(y0);
                    final double e = yi - f;
                    if (f != y0) {
                        isValid = (e >= 0 && e <= 1);
                    } else {
                        isValid = (e >= -1 && e <= 1);
                        if (isValid && e < 0)
                            gy--;
                    }
                    if (isValid && Δxi == -1)
                        gx--;
                }
                if (!isValid) {
                    // if we do not intersect vertical grid line, maybe we intersect horizontal one.
                    isValid = (Δy > 0) ? ((yi = Math.floor(y0) + 1) < y1) : (Δy < 0) && ((yi = Math.ceil(y0) - 1) >= y1);
                    if (isValid) {
                        Δyi = yi - y0;
                        Δxi = Δx * (Δyi / Δy);
                        xi = Δxi + x0;
                        final double f = Math.floor(x0);
                        final double e = xi - f;
                        if (f != x0) {
                            assert (e >= 0 && e <= 1) : e;
                        } else {
                            assert (e >= -1 && e <= 1) : e;
                            if (e < 0)
                                gx--;
                        }
                        if (Δyi == -1)
                            gy--;
                    }
                }
                if (!isValid) {
                    // if no intersection with horizontal or vertical line, line is fully inside cell.
                    Δxi = Δx;
                    Δyi = Δy;
                    gx = (int) x1;
                    gy = (int) y1;
                }
                final double xOrigin = Math.abs(x1 - xStart);
                final double yOrigin = Math.abs(y1 - yStart);
                // Note : we've removed norm computing, as compared vectors are colinear. We just need to make a
                // ratio over any dimension.
                final double ratio;
                if (xOrigin == 0 && yOrigin == 0) {
                    ratio = 1;
                } else {
                    ratio = (xOrigin < yOrigin) ? Math.abs(Δyi / yOrigin) : Math.abs(Δxi / xOrigin);
                }
                final double p = ((ratio < 1e-12) ? 1 : ratio) * child.getWeight();
                if (OUT != null) {
                    OUT.printf("x=%3d y=%3d  Δx=%7.3f  Δy=%7.3f  p=%4.3f%n", gx, gy, Δxi, Δyi, p);
                }
                if (gx >= 0 && gx < ctx.grid.width && gy >= 0 && gy < ctx.grid.height) {
                    probabilityChanges[((ctx.grid.height - 1) - gy) * ctx.grid.width + gx] += p;
                    numOnGrid++;
                }
            } while (isValid);
            if (OUT != null) {
                OUT.println();
            }
        }
    }
    if (numOnGrid < 1)
        return null;
    // Average probability by number of evaluated points
    for (int i = 0; i < probabilityChanges.length; i++) probabilityChanges[i] /= numOnGrid;
    return probabilityChanges;
}
Also used : SingleCRS(org.opengis.referencing.crs.SingleCRS) HashMap(java.util.HashMap) PointReference(org.geotoolkit.processing.science.drift.v2.PointBucket.PointReference) ArrayList(java.util.ArrayList) NoninvertibleTransformException(org.opengis.referencing.operation.NoninvertibleTransformException) TransformException(org.opengis.referencing.operation.TransformException) DirectPosition2D(org.apache.sis.geometry.DirectPosition2D) PointReference(org.geotoolkit.processing.science.drift.v2.PointBucket.PointReference) Weight(org.geotoolkit.processing.science.drift.Weight) ProcessException(org.geotoolkit.process.ProcessException) Vector2d(org.geotoolkit.geometry.math.Vector2d) ArrayList(java.util.ArrayList) List(java.util.List) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 DirectPosition2D (org.apache.sis.geometry.DirectPosition2D)2 Vector2d (org.geotoolkit.geometry.math.Vector2d)2 ProcessException (org.geotoolkit.process.ProcessException)2 Weight (org.geotoolkit.processing.science.drift.Weight)2 PointReference (org.geotoolkit.processing.science.drift.v2.PointBucket.PointReference)2 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)2 SingleCRS (org.opengis.referencing.crs.SingleCRS)2 AffineTransform (java.awt.geom.AffineTransform)1 IOException (java.io.IOException)1 PrintStream (java.io.PrintStream)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 Duration (java.time.Duration)1 Instant (java.time.Instant)1 ChronoUnit (java.time.temporal.ChronoUnit)1 Arrays (java.util.Arrays)1