diff artifacts/src/main/java/org/dive4elements/river/artifacts/sinfo/tkhcalculation/BedQualityD50KmValueFinder.java @ 8915:d9dbf0b74bc2

Refaktoring of flow depth calculation, extracting tkh part. First implementation of tkh calculation.
author gernotbelger
date Wed, 28 Feb 2018 17:27:15 +0100
parents artifacts/src/main/java/org/dive4elements/river/artifacts/sinfo/flowdepth/BedQualityD50KmValueFinder.java@37ff7f435912
children 29442c03c6e3
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/artifacts/src/main/java/org/dive4elements/river/artifacts/sinfo/tkhcalculation/BedQualityD50KmValueFinder.java	Wed Feb 28 17:27:15 2018 +0100
@@ -0,0 +1,260 @@
+/* Copyright (C) 2017 by Bundesanstalt für Gewässerkunde
+ * Software engineering by
+ *  Björnsen Beratende Ingenieure GmbH
+ *  Dr. Schumacher Ingenieurbüro für Wasser und Umwelt
+ *
+ * This file is Free Software under the GNU AGPL (>=v3)
+ * and comes with ABSOLUTELY NO WARRANTY! Check out the
+ * documentation coming with Dive4Elements River for details.
+ */
+
+package org.dive4elements.river.artifacts.sinfo.tkhcalculation;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+import org.apache.commons.lang.math.DoubleRange;
+import org.apache.commons.math.ArgumentOutsideDomainException;
+import org.apache.commons.math.analysis.interpolation.LinearInterpolator;
+import org.apache.commons.math.analysis.polynomials.PolynomialSplineFunction;
+import org.apache.log4j.Logger;
+import org.dive4elements.river.backend.SedDBSessionHolder;
+import org.dive4elements.river.model.River;
+import org.hibernate.SQLQuery;
+import org.hibernate.Session;
+import org.hibernate.type.StandardBasicTypes;
+
+/**
+ * Searchable sorted km array with parallel bed measurements value array and linear interpolation for km and d50 between
+ * the array elements.<br />
+ * <br />
+ * See comment of SQL command on how the values are filtered and aggregated.
+ *
+ * @author Matthias Schäfer
+ *
+ */
+final class BedQualityD50KmValueFinder {
+
+    /***** INNER CLASSES *****/
+
+    /**
+     * A bed measurements aggregate with its d50 characteristic grain diameter
+     */
+    private static class D50Measurement {
+        private double km;
+
+        public double getKm() {
+            return this.km;
+        }
+
+        // private Date mindate;
+
+        // public Date getMinDate() {
+        // return this.mindate;
+        // }
+
+        // private Date maxdate;
+
+        // public Date getMaxDate() {
+        // return this.maxdate;
+        // }
+
+        private int cnt;
+
+        public int getCnt() {
+            return this.cnt;
+        }
+
+        // private double mindepth;
+
+        // public double getMinDepth() {
+        // return this.mindepth;
+        // }
+
+        // private double maxdepth;
+
+        // public double getMaxDepth() {
+        // return this.maxdepth;
+        // }
+
+        private double d50;
+
+        /**
+         * D50 in m
+         */
+        public double getD50() {
+            return this.d50;
+        }
+
+        // /**
+        // * Parameter constructor
+        // */
+        // public D50Measurement(final double km, final Date mindate, final Date maxdate, final int cnt, final double mindepth,
+        // final double maxdepth,
+        // final double d50mm) {
+        // this.km = km;
+        // this.mindate = mindate;
+        // this.maxdate = maxdate;
+        // this.cnt = cnt;
+        // this.mindepth = mindepth;
+        // this.maxdepth = maxdepth;
+        // this.d50 = d50mm / 1000;
+        // }
+
+        /**
+         * Query result row constructor
+         */
+        public D50Measurement(final Object[] tuple, final String[] aliases) {
+            this.km = 0;
+            // this.mindate = null;
+            // this.maxdate = null;
+            this.cnt = 0;
+            // this.mindepth = Double.NaN;
+            // this.maxdepth = Double.NaN;
+            this.d50 = Double.NaN;
+            for (int i = 0; i < tuple.length; ++i) {
+                if (tuple[i] == null)
+                    continue;
+                switch (aliases[i]) {
+                case "km":
+                    this.km = ((Number) tuple[i]).doubleValue();
+                    break;
+                    // case "mindate":
+                    // this.mindate = (Date) tuple[i];
+                    // break;
+                    // case "maxdate":
+                    // this.maxdate = (Date) tuple[i];
+                    // break;
+                case "cnt":
+                    this.cnt = ((Number) tuple[i]).intValue();
+                    break;
+                    // case "mindepth":
+                    // this.mindepth = ((Number) tuple[i]).doubleValue();
+                    // break;
+                    // case "maxdepth":
+                    // this.maxdepth = ((Number) tuple[i]).doubleValue();
+                    // break;
+                case "d50":
+                    this.d50 = ((Number) tuple[i]).doubleValue() / 1000; // mm to m
+                    break;
+                default:
+                    break;
+                }
+            }
+        }
+    }
+
+    /***** FIELDS *****/
+
+    /**
+     * Private log to use here.
+     */
+    private static Logger log = Logger.getLogger(BedQualityD50KmValueFinder.class);
+
+    /**
+     * Query that aggregates by km for a km range and a time period all sub layer bed measurements with their d50<br />
+     * <br />
+     * A km may have bed measurements for multiple dates, multiple distances from the river bank, and multiple depth layers.
+     * The query filters by km range, time period and layer (sub layer: below bed to max. 50 cm depth).
+     * Those measurements are then grouped by km, and the D50 aggregated as average value.
+     */
+    private static final String SQL_BED_D50_SUBLAYER_MEASUREMENT =
+            "SELECT t.km, MIN(t.datum) AS mindate, MAX(t.datum) AS maxdate, COUNT(*) AS cnt," //
+            + " MIN(p.tiefevon) AS mindepth, MAX(p.tiefebis) AS maxdepth, AVG(a.d50) AS d50" //
+            + " FROM sohltest t INNER JOIN station s ON t.stationid = s.stationid" //
+            + "    INNER JOIN gewaesser g ON s.gewaesserid = g.gewaesserid" //
+            + "    INNER JOIN sohlprobe p ON t.sohltestid = p.sohltestid" //
+            + "    INNER JOIN siebanalyse a ON p.sohlprobeid = a.sohlprobeid" //
+            + " WHERE (g.name = :name) AND (s.km BETWEEN :fromkm - 0.0001 AND :tokm + 0.0001)" //
+            + "    AND (p.tiefevon > 0.0) AND (p.tiefebis <= 0.5)" //
+            + "    AND (t.datum BETWEEN :fromdate AND :todate)" //
+            + " GROUP BY t.km" //
+            + " ORDER BY t.km"; //
+
+    private static final String[] SQL_BED_D50_SELECT_ALIAS = { "km", "mindate", "maxdate", "cnt", "mindepth", "maxdepth", "d50" };
+
+    /**
+     * Real linear interpolator for kms and d50 values
+     */
+    private final PolynomialSplineFunction interpolator;
+
+    /***** METHODS *****/
+
+    private BedQualityD50KmValueFinder(final double[] kms, final double[] values) {
+        this.interpolator = new LinearInterpolator().interpolate(kms, values);
+    }
+
+    /**
+     * Sohlbeschaffenheit (D50 Korndurchmesser aus Seddb)
+     * Abhängig von Peiljahr
+     */
+    public static BedQualityD50KmValueFinder loadBedMeasurements(final River river, final DoubleRange kmRange, final int soundingYear, final int validYears) {
+
+        /* construct valid measurement time range */
+        final Calendar cal = Calendar.getInstance();
+        cal.clear();
+
+        cal.set(soundingYear - validYears, 0, 1);
+        final Date startTime = cal.getTime();
+
+        cal.set(soundingYear + validYears, 11, 31);
+        final Date endTime = cal.getTime();
+
+        log.debug(String.format("loadValues km %.3f - %.3f %tF - %tF", kmRange.getMinimumDouble(), kmRange.getMaximumDouble(), startTime, endTime));
+        final Session session = SedDBSessionHolder.HOLDER.get();
+        final SQLQuery sqlQuery = session.createSQLQuery(SQL_BED_D50_SUBLAYER_MEASUREMENT).addScalar("km", StandardBasicTypes.DOUBLE)
+                .addScalar("mindate", StandardBasicTypes.DATE).addScalar("maxdate", StandardBasicTypes.DATE).addScalar("cnt", StandardBasicTypes.INTEGER)
+                .addScalar("mindepth", StandardBasicTypes.DOUBLE).addScalar("maxdepth", StandardBasicTypes.DOUBLE).addScalar("d50", StandardBasicTypes.DOUBLE);
+        final String seddbRiver = river.nameForSeddb();
+        sqlQuery.setString("name", seddbRiver);
+        sqlQuery.setDouble("fromkm", kmRange.getMinimumDouble());
+        sqlQuery.setDouble("tokm", kmRange.getMaximumDouble());
+        sqlQuery.setDate("fromdate", startTime);
+        sqlQuery.setDate("todate", endTime);
+
+        final List<Object[]> rows = sqlQuery.list();
+        final double[] kms = new double[rows.size()];
+        final double[] values = new double[rows.size()];
+        D50Measurement measurement;
+        int i = -1;
+        for (final Object[] row : rows) {
+            measurement = new D50Measurement(row, SQL_BED_D50_SELECT_ALIAS);
+            i++;
+            kms[i] = measurement.getKm();
+            values[i] = measurement.getD50();
+            log.debug(String.format("loadValues km %.3f d50(mm) %.1f count %d", kms[i], values[i], measurement.getCnt()));
+        }
+        try {
+            return new BedQualityD50KmValueFinder(kms, values);
+        }
+        catch (final Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    /**
+     * Returns the d50 value interpolated according to a km
+     *
+     * @return d50 (mm) of the km, or NaN
+     */
+    public double findD50(final double km) throws ArgumentOutsideDomainException {
+        return this.interpolator.value(km);
+        /*
+         * ohne interpolation:
+         * if ((kms == null) || (kms.size() == 0))
+         * return Double.NaN;
+         * int i = kms.binarySearch(km);
+         * if (i >= 0)
+         * return values.get(i);
+         * i = -i - 1;
+         * if ((i - 1 >= 0) && Utils.epsilonEquals(km, kms.get(i - 1), 0.0001))
+         * return values.get(i - 1);
+         * else if ((i >= 0) && (i <= kms.size() - 1) && Utils.epsilonEquals(km, kms.get(i), 0.0001))
+         * return values.get(i);
+         * else
+         * return Double.NaN;
+         */
+    }
+}
\ No newline at end of file

http://dive4elements.wald.intevation.org