GaussianFitter.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.math3.fitting;

  18. import java.util.Arrays;
  19. import java.util.Comparator;
  20. import org.apache.commons.math3.analysis.function.Gaussian;
  21. import org.apache.commons.math3.exception.NullArgumentException;
  22. import org.apache.commons.math3.exception.NumberIsTooSmallException;
  23. import org.apache.commons.math3.exception.OutOfRangeException;
  24. import org.apache.commons.math3.exception.ZeroException;
  25. import org.apache.commons.math3.exception.NotStrictlyPositiveException;
  26. import org.apache.commons.math3.exception.util.LocalizedFormats;
  27. import org.apache.commons.math3.optim.nonlinear.vector.MultivariateVectorOptimizer;
  28. import org.apache.commons.math3.util.FastMath;

  29. /**
  30.  * Fits points to a {@link
  31.  * org.apache.commons.math3.analysis.function.Gaussian.Parametric Gaussian} function.
  32.  * <p>
  33.  * Usage example:
  34.  * <pre>
  35.  *   GaussianFitter fitter = new GaussianFitter(
  36.  *     new LevenbergMarquardtOptimizer());
  37.  *   fitter.addObservedPoint(4.0254623,  531026.0);
  38.  *   fitter.addObservedPoint(4.03128248, 984167.0);
  39.  *   fitter.addObservedPoint(4.03839603, 1887233.0);
  40.  *   fitter.addObservedPoint(4.04421621, 2687152.0);
  41.  *   fitter.addObservedPoint(4.05132976, 3461228.0);
  42.  *   fitter.addObservedPoint(4.05326982, 3580526.0);
  43.  *   fitter.addObservedPoint(4.05779662, 3439750.0);
  44.  *   fitter.addObservedPoint(4.0636168,  2877648.0);
  45.  *   fitter.addObservedPoint(4.06943698, 2175960.0);
  46.  *   fitter.addObservedPoint(4.07525716, 1447024.0);
  47.  *   fitter.addObservedPoint(4.08237071, 717104.0);
  48.  *   fitter.addObservedPoint(4.08366408, 620014.0);
  49.  *   double[] parameters = fitter.fit();
  50.  * </pre>
  51.  *
  52.  * @since 2.2
  53.  * @deprecated As of 3.3. Please use {@link GaussianCurveFitter} and
  54.  * {@link WeightedObservedPoints} instead.
  55.  */
  56. @Deprecated
  57. public class GaussianFitter extends CurveFitter<Gaussian.Parametric> {
  58.     /**
  59.      * Constructs an instance using the specified optimizer.
  60.      *
  61.      * @param optimizer Optimizer to use for the fitting.
  62.      */
  63.     public GaussianFitter(MultivariateVectorOptimizer optimizer) {
  64.         super(optimizer);
  65.     }

  66.     /**
  67.      * Fits a Gaussian function to the observed points.
  68.      *
  69.      * @param initialGuess First guess values in the following order:
  70.      * <ul>
  71.      *  <li>Norm</li>
  72.      *  <li>Mean</li>
  73.      *  <li>Sigma</li>
  74.      * </ul>
  75.      * @return the parameters of the Gaussian function that best fits the
  76.      * observed points (in the same order as above).
  77.      * @since 3.0
  78.      */
  79.     public double[] fit(double[] initialGuess) {
  80.         final Gaussian.Parametric f = new Gaussian.Parametric() {
  81.                 @Override
  82.                 public double value(double x, double ... p) {
  83.                     double v = Double.POSITIVE_INFINITY;
  84.                     try {
  85.                         v = super.value(x, p);
  86.                     } catch (NotStrictlyPositiveException e) { // NOPMD
  87.                         // Do nothing.
  88.                     }
  89.                     return v;
  90.                 }

  91.                 @Override
  92.                 public double[] gradient(double x, double ... p) {
  93.                     double[] v = { Double.POSITIVE_INFINITY,
  94.                                    Double.POSITIVE_INFINITY,
  95.                                    Double.POSITIVE_INFINITY };
  96.                     try {
  97.                         v = super.gradient(x, p);
  98.                     } catch (NotStrictlyPositiveException e) { // NOPMD
  99.                         // Do nothing.
  100.                     }
  101.                     return v;
  102.                 }
  103.             };

  104.         return fit(f, initialGuess);
  105.     }

  106.     /**
  107.      * Fits a Gaussian function to the observed points.
  108.      *
  109.      * @return the parameters of the Gaussian function that best fits the
  110.      * observed points (in the same order as above).
  111.      */
  112.     public double[] fit() {
  113.         final double[] guess = (new ParameterGuesser(getObservations())).guess();
  114.         return fit(guess);
  115.     }

  116.     /**
  117.      * Guesses the parameters {@code norm}, {@code mean}, and {@code sigma}
  118.      * of a {@link org.apache.commons.math3.analysis.function.Gaussian.Parametric}
  119.      * based on the specified observed points.
  120.      */
  121.     public static class ParameterGuesser {
  122.         /** Normalization factor. */
  123.         private final double norm;
  124.         /** Mean. */
  125.         private final double mean;
  126.         /** Standard deviation. */
  127.         private final double sigma;

  128.         /**
  129.          * Constructs instance with the specified observed points.
  130.          *
  131.          * @param observations Observed points from which to guess the
  132.          * parameters of the Gaussian.
  133.          * @throws NullArgumentException if {@code observations} is
  134.          * {@code null}.
  135.          * @throws NumberIsTooSmallException if there are less than 3
  136.          * observations.
  137.          */
  138.         public ParameterGuesser(WeightedObservedPoint[] observations) {
  139.             if (observations == null) {
  140.                 throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY);
  141.             }
  142.             if (observations.length < 3) {
  143.                 throw new NumberIsTooSmallException(observations.length, 3, true);
  144.             }

  145.             final WeightedObservedPoint[] sorted = sortObservations(observations);
  146.             final double[] params = basicGuess(sorted);

  147.             norm = params[0];
  148.             mean = params[1];
  149.             sigma = params[2];
  150.         }

  151.         /**
  152.          * Gets an estimation of the parameters.
  153.          *
  154.          * @return the guessed parameters, in the following order:
  155.          * <ul>
  156.          *  <li>Normalization factor</li>
  157.          *  <li>Mean</li>
  158.          *  <li>Standard deviation</li>
  159.          * </ul>
  160.          */
  161.         public double[] guess() {
  162.             return new double[] { norm, mean, sigma };
  163.         }

  164.         /**
  165.          * Sort the observations.
  166.          *
  167.          * @param unsorted Input observations.
  168.          * @return the input observations, sorted.
  169.          */
  170.         private WeightedObservedPoint[] sortObservations(WeightedObservedPoint[] unsorted) {
  171.             final WeightedObservedPoint[] observations = unsorted.clone();
  172.             final Comparator<WeightedObservedPoint> cmp
  173.                 = new Comparator<WeightedObservedPoint>() {
  174.                 public int compare(WeightedObservedPoint p1,
  175.                                    WeightedObservedPoint p2) {
  176.                     if (p1 == null && p2 == null) {
  177.                         return 0;
  178.                     }
  179.                     if (p1 == null) {
  180.                         return -1;
  181.                     }
  182.                     if (p2 == null) {
  183.                         return 1;
  184.                     }
  185.                     if (p1.getX() < p2.getX()) {
  186.                         return -1;
  187.                     }
  188.                     if (p1.getX() > p2.getX()) {
  189.                         return 1;
  190.                     }
  191.                     if (p1.getY() < p2.getY()) {
  192.                         return -1;
  193.                     }
  194.                     if (p1.getY() > p2.getY()) {
  195.                         return 1;
  196.                     }
  197.                     if (p1.getWeight() < p2.getWeight()) {
  198.                         return -1;
  199.                     }
  200.                     if (p1.getWeight() > p2.getWeight()) {
  201.                         return 1;
  202.                     }
  203.                     return 0;
  204.                 }
  205.             };

  206.             Arrays.sort(observations, cmp);
  207.             return observations;
  208.         }

  209.         /**
  210.          * Guesses the parameters based on the specified observed points.
  211.          *
  212.          * @param points Observed points, sorted.
  213.          * @return the guessed parameters (normalization factor, mean and
  214.          * sigma).
  215.          */
  216.         private double[] basicGuess(WeightedObservedPoint[] points) {
  217.             final int maxYIdx = findMaxY(points);
  218.             final double n = points[maxYIdx].getY();
  219.             final double m = points[maxYIdx].getX();

  220.             double fwhmApprox;
  221.             try {
  222.                 final double halfY = n + ((m - n) / 2);
  223.                 final double fwhmX1 = interpolateXAtY(points, maxYIdx, -1, halfY);
  224.                 final double fwhmX2 = interpolateXAtY(points, maxYIdx, 1, halfY);
  225.                 fwhmApprox = fwhmX2 - fwhmX1;
  226.             } catch (OutOfRangeException e) {
  227.                 // TODO: Exceptions should not be used for flow control.
  228.                 fwhmApprox = points[points.length - 1].getX() - points[0].getX();
  229.             }
  230.             final double s = fwhmApprox / (2 * FastMath.sqrt(2 * FastMath.log(2)));

  231.             return new double[] { n, m, s };
  232.         }

  233.         /**
  234.          * Finds index of point in specified points with the largest Y.
  235.          *
  236.          * @param points Points to search.
  237.          * @return the index in specified points array.
  238.          */
  239.         private int findMaxY(WeightedObservedPoint[] points) {
  240.             int maxYIdx = 0;
  241.             for (int i = 1; i < points.length; i++) {
  242.                 if (points[i].getY() > points[maxYIdx].getY()) {
  243.                     maxYIdx = i;
  244.                 }
  245.             }
  246.             return maxYIdx;
  247.         }

  248.         /**
  249.          * Interpolates using the specified points to determine X at the
  250.          * specified Y.
  251.          *
  252.          * @param points Points to use for interpolation.
  253.          * @param startIdx Index within points from which to start the search for
  254.          * interpolation bounds points.
  255.          * @param idxStep Index step for searching interpolation bounds points.
  256.          * @param y Y value for which X should be determined.
  257.          * @return the value of X for the specified Y.
  258.          * @throws ZeroException if {@code idxStep} is 0.
  259.          * @throws OutOfRangeException if specified {@code y} is not within the
  260.          * range of the specified {@code points}.
  261.          */
  262.         private double interpolateXAtY(WeightedObservedPoint[] points,
  263.                                        int startIdx,
  264.                                        int idxStep,
  265.                                        double y)
  266.             throws OutOfRangeException {
  267.             if (idxStep == 0) {
  268.                 throw new ZeroException();
  269.             }
  270.             final WeightedObservedPoint[] twoPoints
  271.                 = getInterpolationPointsForY(points, startIdx, idxStep, y);
  272.             final WeightedObservedPoint p1 = twoPoints[0];
  273.             final WeightedObservedPoint p2 = twoPoints[1];
  274.             if (p1.getY() == y) {
  275.                 return p1.getX();
  276.             }
  277.             if (p2.getY() == y) {
  278.                 return p2.getX();
  279.             }
  280.             return p1.getX() + (((y - p1.getY()) * (p2.getX() - p1.getX())) /
  281.                                 (p2.getY() - p1.getY()));
  282.         }

  283.         /**
  284.          * Gets the two bounding interpolation points from the specified points
  285.          * suitable for determining X at the specified Y.
  286.          *
  287.          * @param points Points to use for interpolation.
  288.          * @param startIdx Index within points from which to start search for
  289.          * interpolation bounds points.
  290.          * @param idxStep Index step for search for interpolation bounds points.
  291.          * @param y Y value for which X should be determined.
  292.          * @return the array containing two points suitable for determining X at
  293.          * the specified Y.
  294.          * @throws ZeroException if {@code idxStep} is 0.
  295.          * @throws OutOfRangeException if specified {@code y} is not within the
  296.          * range of the specified {@code points}.
  297.          */
  298.         private WeightedObservedPoint[] getInterpolationPointsForY(WeightedObservedPoint[] points,
  299.                                                                    int startIdx,
  300.                                                                    int idxStep,
  301.                                                                    double y)
  302.             throws OutOfRangeException {
  303.             if (idxStep == 0) {
  304.                 throw new ZeroException();
  305.             }
  306.             for (int i = startIdx;
  307.                  idxStep < 0 ? i + idxStep >= 0 : i + idxStep < points.length;
  308.                  i += idxStep) {
  309.                 final WeightedObservedPoint p1 = points[i];
  310.                 final WeightedObservedPoint p2 = points[i + idxStep];
  311.                 if (isBetween(y, p1.getY(), p2.getY())) {
  312.                     if (idxStep < 0) {
  313.                         return new WeightedObservedPoint[] { p2, p1 };
  314.                     } else {
  315.                         return new WeightedObservedPoint[] { p1, p2 };
  316.                     }
  317.                 }
  318.             }

  319.             // Boundaries are replaced by dummy values because the raised
  320.             // exception is caught and the message never displayed.
  321.             // TODO: Exceptions should not be used for flow control.
  322.             throw new OutOfRangeException(y,
  323.                                           Double.NEGATIVE_INFINITY,
  324.                                           Double.POSITIVE_INFINITY);
  325.         }

  326.         /**
  327.          * Determines whether a value is between two other values.
  328.          *
  329.          * @param value Value to test whether it is between {@code boundary1}
  330.          * and {@code boundary2}.
  331.          * @param boundary1 One end of the range.
  332.          * @param boundary2 Other end of the range.
  333.          * @return {@code true} if {@code value} is between {@code boundary1} and
  334.          * {@code boundary2} (inclusive), {@code false} otherwise.
  335.          */
  336.         private boolean isBetween(double value,
  337.                                   double boundary1,
  338.                                   double boundary2) {
  339.             return (value >= boundary1 && value <= boundary2) ||
  340.                 (value >= boundary2 && value <= boundary1);
  341.         }
  342.     }
  343. }