sascha@427: package de.intevation.flys.artifacts.math; sascha@427: sascha@452: import org.apache.log4j.Logger; sascha@452: sascha@427: public class LinearRemap sascha@427: { sascha@452: private static Logger logger = Logger.getLogger(LinearRemap.class); sascha@452: sascha@427: public static class Segment { sascha@427: sascha@427: protected Segment next; sascha@427: sascha@427: protected double from; sascha@427: protected double to; sascha@427: sascha@427: protected double m; sascha@427: protected double b; sascha@427: sascha@427: public Segment() { sascha@427: } sascha@427: sascha@427: public Segment( sascha@427: double from, double to, sascha@427: double m, double b, sascha@427: Segment next sascha@427: ) { sascha@427: this.from = from; sascha@427: this.to = to; sascha@427: this.m = m; sascha@427: this.b = b; sascha@427: } sascha@427: sascha@427: public double eval(double x) { sascha@427: return m*x + b; sascha@427: } sascha@427: } // class Segment sascha@427: sascha@427: protected Segment head; sascha@427: sascha@427: public LinearRemap() { sascha@427: } sascha@427: sascha@427: public void add( sascha@427: double from, double to, sascha@427: double x1, double y1, sascha@427: double x2, double y2 sascha@427: ) { sascha@427: // y1 = m*x1 + b <=> b = y1 - m*x1 sascha@427: // y2 = m*x2 + b sascha@427: // y2 - y1 = m*(x2 - x1) sascha@427: // m = (y2 - y1)/(x2 - x1) sascha@427: sascha@427: double m, b; sascha@427: sascha@427: if (x2 == x1) { sascha@427: m = 0.0; sascha@427: b = 0.5*(y2 + y1); sascha@427: } sascha@427: else { sascha@427: m = (y2 - y1)/(x2 - x1); sascha@427: b = y1 - m*x1; sascha@427: } sascha@427: sascha@427: head = new Segment(from, to, m, b, head); sascha@452: sascha@452: if (logger.isDebugEnabled()) { sascha@452: logger.debug("LinearRemap.add --------- enter"); sascha@452: logger.debug(" range: [" + from + ", " + to + "]"); sascha@452: logger.debug(" " + x1 + " -> " + y1 + " (" + head.eval(x1) + ")"); sascha@452: logger.debug(" " + x2 + " -> " + y2 + " (" + head.eval(x2) + ")"); sascha@452: logger.debug("LinearRemap.add --------- leave"); sascha@452: } sascha@427: } sascha@427: sascha@427: public double eval(double pos, double x) { sascha@427: Segment current = head; sascha@427: sascha@427: while (current != null) { sascha@427: sascha@427: if (pos >= current.from && pos <= current.to) { sascha@427: return current.eval(x); sascha@427: } sascha@427: sascha@427: current = current.next; sascha@427: } sascha@427: sascha@427: return Double.NaN; sascha@427: } sascha@427: } sascha@427: // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :