Mercurial > dive4elements > river
diff artifacts/src/main/java/org/dive4elements/river/artifacts/math/MovingAverage.java @ 5838:5aa05a7a34b7
Rename modules to more fitting names.
author | Sascha L. Teichmann <teichmann@intevation.de> |
---|---|
date | Thu, 25 Apr 2013 15:23:37 +0200 |
parents | flys-artifacts/src/main/java/org/dive4elements/river/artifacts/math/MovingAverage.java@bd047b71ab37 |
children | 4897a58c8746 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/artifacts/src/main/java/org/dive4elements/river/artifacts/math/MovingAverage.java Thu Apr 25 15:23:37 2013 +0200 @@ -0,0 +1,67 @@ +package org.dive4elements.river.artifacts.math; + +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; + + +public class MovingAverage +{ + + public static double[][] simple(double[][] values, double radius) { + TreeMap<Double, Double> map = toMap(values); + int N = map.size(); + double [] xs = new double[N]; + double [] ys = new double[N]; + int ndx = 0; + for (double x: map.keySet()) { + SortedMap<Double, Double> range = + map.subMap(x-radius, true, x+radius, true); + double avg = 0d; + for (double v: range.values()) { + avg += v; + } + avg /= range.size(); + xs[ndx] = x; + ys[ndx] = avg; + ndx++; + } + return new double [][] { xs, ys }; + } + + public static double[][] weighted(double[][] values, double radius) { + TreeMap<Double, Double> map = toMap(values); + int N = map.size(); + double [] xs = new double[N]; + double [] ys = new double[N]; + int ndx = 0; + double _1radius = 1d/radius; + for (double x: map.keySet()) { + double avg = 0d; + double weights = 0d; + for (Map.Entry<Double, Double> e: + map.subMap(x-radius, false, x+radius, false).entrySet() + ) { + double weight = 1d - Math.abs(x - e.getKey())*_1radius; + avg += weight*e.getValue(); + weights += weight; + } + avg /= weights; + xs[ndx] = x; + ys[ndx] = avg; + ndx++; + } + return new double [][] { xs, ys }; + } + + private static TreeMap<Double, Double> toMap(double[][] values) { + TreeMap<Double, Double> map = new TreeMap<Double, Double>(); + double [] xs = values[0]; + double [] ys = values[1]; + for (int i = 0; i < xs.length; i++) { + map.put(xs[i], ys[i]); + } + return map; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :