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.optimization.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.optimization.DifferentiableMultivariateVectorOptimizer;
  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.1 (to be removed in 4.0).
  54.  */
  55. @Deprecated
  56. public class GaussianFitter extends CurveFitter<Gaussian.Parametric> {
  57.     /**
  58.      * Constructs an instance using the specified optimizer.
  59.      *
  60.      * @param optimizer Optimizer to use for the fitting.
  61.      */
  62.     public GaussianFitter(DifferentiableMultivariateVectorOptimizer optimizer) {
  63.         super(optimizer);
  64.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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