EmpiricalDistribution.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.  *      https://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. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */

  21. package org.hipparchus.stat.fitting;

  22. import java.io.BufferedReader;
  23. import java.io.Closeable;
  24. import java.io.File;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.io.InputStreamReader;
  28. import java.net.URL;
  29. import java.nio.charset.Charset;
  30. import java.nio.file.Files;
  31. import java.util.ArrayList;
  32. import java.util.List;

  33. import org.hipparchus.distribution.RealDistribution;
  34. import org.hipparchus.distribution.continuous.AbstractRealDistribution;
  35. import org.hipparchus.distribution.continuous.ConstantRealDistribution;
  36. import org.hipparchus.distribution.continuous.NormalDistribution;
  37. import org.hipparchus.exception.LocalizedCoreFormats;
  38. import org.hipparchus.exception.MathIllegalArgumentException;
  39. import org.hipparchus.exception.MathIllegalStateException;
  40. import org.hipparchus.exception.MathRuntimeException;
  41. import org.hipparchus.exception.NullArgumentException;
  42. import org.hipparchus.random.RandomDataGenerator;
  43. import org.hipparchus.random.RandomGenerator;
  44. import org.hipparchus.stat.descriptive.StatisticalSummary;
  45. import org.hipparchus.stat.descriptive.StreamingStatistics;
  46. import org.hipparchus.util.FastMath;
  47. import org.hipparchus.util.MathUtils;

  48. /**
  49.  * <p>Represents an <a href="http://http://en.wikipedia.org/wiki/Empirical_distribution_function">
  50.  * empirical probability distribution</a> -- a probability distribution derived
  51.  * from observed data without making any assumptions about the functional form
  52.  * of the population distribution that the data come from.</p>
  53.  *
  54.  * <p>An <code>EmpiricalDistribution</code> maintains data structures, called
  55.  * <i>distribution digests</i>, that describe empirical distributions and
  56.  * support the following operations:
  57.  * </p>
  58.  * <ul>
  59.  * <li>loading the distribution from a file of observed data values</li>
  60.  * <li>dividing the input data into "bin ranges" and reporting bin frequency
  61.  *     counts (data for histogram)</li>
  62.  * <li>reporting univariate statistics describing the full set of data values
  63.  *     as well as the observations within each bin</li>
  64.  * <li>generating random values from the distribution</li>
  65.  * </ul>
  66.  * <p>
  67.  * Applications can use <code>EmpiricalDistribution</code> to build grouped
  68.  * frequency histograms representing the input data or to generate random values
  69.  * "like" those in the input file -- i.e., the values generated will follow the
  70.  * distribution of the values in the file.
  71.  * </p>
  72.  *
  73.  * <p>The implementation uses what amounts to the
  74.  * <a href="http://nedwww.ipac.caltech.edu/level5/March02/Silverman/Silver2_6.html">
  75.  * Variable Kernel Method</a> with Gaussian smoothing:</p>
  76.  * <p><strong>Digesting the input file</strong></p>
  77.  * <ol><li>Pass the file once to compute min and max.</li>
  78.  * <li>Divide the range from min-max into <code>binCount</code> "bins."</li>
  79.  * <li>Pass the data file again, computing bin counts and univariate
  80.  *     statistics (mean, std dev.) for each of the bins </li>
  81.  * <li>Divide the interval (0,1) into subintervals associated with the bins,
  82.  *     with the length of a bin's subinterval proportional to its count.</li></ol>
  83.  * <strong>Generating random values from the distribution</strong><ol>
  84.  * <li>Generate a uniformly distributed value in (0,1) </li>
  85.  * <li>Select the subinterval to which the value belongs.
  86.  * <li>Generate a random Gaussian value with mean = mean of the associated
  87.  *     bin and std dev = std dev of associated bin.</li></ol>
  88.  *
  89.  * <p>EmpiricalDistribution implements the {@link RealDistribution} interface
  90.  * as follows.  Given x within the range of values in the dataset, let B
  91.  * be the bin containing x and let K be the within-bin kernel for B.  Let P(B-)
  92.  * be the sum of the probabilities of the bins below B and let K(B) be the
  93.  * mass of B under K (i.e., the integral of the kernel density over B).  Then
  94.  * set P(X &lt; x) = P(B-) + P(B) * K(x) / K(B) where K(x) is the kernel distribution
  95.  * evaluated at x. This results in a cdf that matches the grouped frequency
  96.  * distribution at the bin endpoints and interpolates within bins using
  97.  * within-bin kernels.</p>
  98.  *
  99.  *<p><strong>USAGE NOTES:</strong></p>
  100.  *<ul>
  101.  *<li>The <code>binCount</code> is set by default to 1000.  A good rule of thumb
  102.  *    is to set the bin count to approximately the length of the input file divided
  103.  *    by 10. </li>
  104.  *<li>The input file <i>must</i> be a plain text file containing one valid numeric
  105.  *    entry per line.</li>
  106.  * </ul>
  107.  *
  108.  */
  109. public class EmpiricalDistribution extends AbstractRealDistribution {

  110.     /** Default bin count */
  111.     public static final int DEFAULT_BIN_COUNT = 1000;

  112.     /** Character set for file input */
  113.     private static final String FILE_CHARSET = "US-ASCII";

  114.     /** Serializable version identifier */
  115.     private static final long serialVersionUID = 5729073523949762654L;

  116.     /** RandomDataGenerator instance to use in repeated calls to getNext() */
  117.     protected final RandomDataGenerator randomData;

  118.     /** List of SummaryStatistics objects characterizing the bins */
  119.     private final List<StreamingStatistics> binStats;

  120.     /** Sample statistics */
  121.     private StreamingStatistics sampleStats;

  122.     /** Max loaded value */
  123.     private double max = Double.NEGATIVE_INFINITY;

  124.     /** Min loaded value */
  125.     private double min = Double.POSITIVE_INFINITY;

  126.     /** Grid size */
  127.     private double delta;

  128.     /** number of bins */
  129.     private final int binCount;

  130.     /** is the distribution loaded? */
  131.     private boolean loaded;

  132.     /** upper bounds of subintervals in (0,1) "belonging" to the bins */
  133.     private double[] upperBounds;

  134.     /**
  135.      * Creates a new EmpiricalDistribution with the default bin count.
  136.      */
  137.     public EmpiricalDistribution() {
  138.         this(DEFAULT_BIN_COUNT);
  139.     }

  140.     /**
  141.      * Creates a new EmpiricalDistribution with the specified bin count.
  142.      *
  143.      * @param binCount number of bins. Must be strictly positive.
  144.      * @throws MathIllegalArgumentException if {@code binCount <= 0}.
  145.      */
  146.     public EmpiricalDistribution(int binCount) {
  147.         this(binCount, new RandomDataGenerator());
  148.     }

  149.     /**
  150.      * Creates a new EmpiricalDistribution with the specified bin count using the
  151.      * provided {@link RandomGenerator} as the source of random data.
  152.      *
  153.      * @param binCount number of bins. Must be strictly positive.
  154.      * @param generator random data generator (may be null, resulting in default JDK generator)
  155.      * @throws MathIllegalArgumentException if {@code binCount <= 0}.
  156.      */
  157.     public EmpiricalDistribution(int binCount, RandomGenerator generator) {
  158.         this(binCount, RandomDataGenerator.of(generator));
  159.     }

  160.     /**
  161.      * Creates a new EmpiricalDistribution with default bin count using the
  162.      * provided {@link RandomGenerator} as the source of random data.
  163.      *
  164.      * @param generator random data generator (may be null, resulting in default JDK generator)
  165.      */
  166.     public EmpiricalDistribution(RandomGenerator generator) {
  167.         this(DEFAULT_BIN_COUNT, generator);
  168.     }

  169.     /**
  170.      * Private constructor to allow lazy initialisation of the RNG contained
  171.      * in the {@link #randomData} instance variable.
  172.      *
  173.      * @param binCount number of bins. Must be strictly positive.
  174.      * @param randomData Random data generator.
  175.      * @throws MathIllegalArgumentException if {@code binCount <= 0}.
  176.      */
  177.     private EmpiricalDistribution(int binCount,
  178.                                   RandomDataGenerator randomData) {
  179.         if (binCount <= 0) {
  180.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_SMALL_BOUND_EXCLUDED,
  181.                                                    binCount, 0);
  182.         }
  183.         this.binCount = binCount;
  184.         this.randomData = randomData;
  185.         binStats = new ArrayList<>();
  186.     }

  187.     /**
  188.      * Computes the empirical distribution from the provided
  189.      * array of numbers.
  190.      *
  191.      * @param in the input data array
  192.      * @exception NullArgumentException if in is null
  193.      */
  194.     public void load(double[] in) throws NullArgumentException {
  195.         try (DataAdapter da = new ArrayDataAdapter(in)) {
  196.             da.computeStats();
  197.             // new adapter for the second pass
  198.             fillBinStats(new ArrayDataAdapter(in));
  199.         } catch (IOException ex) {
  200.             // Can't happen
  201.             throw MathRuntimeException.createInternalError();
  202.         }
  203.         loaded = true;

  204.     }

  205.     /**
  206.      * Computes the empirical distribution using data read from a URL.
  207.      *
  208.      * <p>The input file <i>must</i> be an ASCII text file containing one
  209.      * valid numeric entry per line.</p>
  210.      *
  211.      * @param url url of the input file
  212.      *
  213.      * @throws IOException if an IO error occurs
  214.      * @throws NullArgumentException if url is null
  215.      * @throws MathIllegalArgumentException if URL contains no data
  216.      */
  217.     public void load(URL url) throws IOException, MathIllegalArgumentException, NullArgumentException {
  218.         MathUtils.checkNotNull(url);
  219.         Charset charset = Charset.forName(FILE_CHARSET);
  220.         try (InputStream       is1  = url.openStream();
  221.              InputStreamReader isr1 = new InputStreamReader(is1, charset);
  222.              BufferedReader    br1  = new BufferedReader(isr1);
  223.              DataAdapter       da1  = new StreamDataAdapter(br1)) {
  224.             da1.computeStats();
  225.             if (sampleStats.getN() == 0) {
  226.                 throw new MathIllegalArgumentException(LocalizedCoreFormats.URL_CONTAINS_NO_DATA, url);
  227.             }
  228.             // new adapter for the second pass
  229.             try (InputStream       is2  = url.openStream();
  230.                  InputStreamReader isr2 = new InputStreamReader(is2, charset);
  231.                  BufferedReader    br2  = new BufferedReader(isr2);
  232.                  DataAdapter       da2  = new StreamDataAdapter(br2)) {
  233.                 fillBinStats(da2);
  234.                 loaded = true;
  235.             }
  236.         }
  237.     }

  238.     /**
  239.      * Computes the empirical distribution from the input file.
  240.      *
  241.      * <p>The input file <i>must</i> be an ASCII text file containing one
  242.      * valid numeric entry per line.</p>
  243.      *
  244.      * @param file the input file
  245.      * @throws IOException if an IO error occurs
  246.      * @throws NullArgumentException if file is null
  247.      */
  248.     public void load(File file) throws IOException, NullArgumentException {
  249.         MathUtils.checkNotNull(file);
  250.         Charset charset = Charset.forName(FILE_CHARSET);
  251.         try (InputStream    is1 = Files.newInputStream(file.toPath());
  252.              BufferedReader br1 = new BufferedReader(new InputStreamReader(is1, charset));
  253.              DataAdapter    da1 = new StreamDataAdapter(br1)) {
  254.             da1.computeStats();
  255.             // new adapter for second pass
  256.             try (InputStream    is2 = Files.newInputStream(file.toPath());
  257.                  BufferedReader in2 = new BufferedReader(new InputStreamReader(is2, charset));
  258.                  DataAdapter    da2 = new StreamDataAdapter(in2)) {
  259.                 fillBinStats(da2);
  260.             }
  261.             loaded = true;
  262.         }
  263.     }

  264.     /**
  265.      * Provides methods for computing <code>sampleStats</code> and
  266.      * <code>beanStats</code> abstracting the source of data.
  267.      */
  268.     private abstract class DataAdapter implements Closeable {

  269.         /**
  270.          * Compute bin stats.
  271.          *
  272.          * @throws IOException  if an error occurs computing bin stats
  273.          */
  274.         public abstract void computeBinStats() throws IOException;

  275.         /**
  276.          * Compute sample statistics.
  277.          *
  278.          * @throws IOException if an error occurs computing sample stats
  279.          */
  280.         public abstract void computeStats() throws IOException;

  281.     }

  282.     /**
  283.      * <code>DataAdapter</code> for data provided through some input stream
  284.      */
  285.     private class StreamDataAdapter extends DataAdapter {

  286.         /** Input stream providing access to the data */
  287.         private BufferedReader inputStream;

  288.         /**
  289.          * Create a StreamDataAdapter from a BufferedReader
  290.          *
  291.          * @param in BufferedReader input stream
  292.          */
  293.         StreamDataAdapter(BufferedReader in) {
  294.             inputStream = in;
  295.         }

  296.         /** {@inheritDoc} */
  297.         @Override
  298.         public void computeBinStats() throws IOException {
  299.             for (String str = inputStream.readLine(); str != null; str = inputStream.readLine()) {
  300.                 final double val = Double.parseDouble(str);
  301.                 StreamingStatistics stats = binStats.get(findBin(val));
  302.                 stats.addValue(val);
  303.             }
  304.         }

  305.         /** {@inheritDoc} */
  306.         @Override
  307.         public void computeStats() throws IOException {
  308.             sampleStats = new StreamingStatistics();
  309.             for (String str = inputStream.readLine(); str != null; str = inputStream.readLine()) {
  310.                 final double val = Double.parseDouble(str);
  311.                 sampleStats.addValue(val);
  312.             }
  313.         }

  314.         /** {@inheritDoc} */
  315.         @Override
  316.         public void close() throws IOException {
  317.             if (inputStream != null) {
  318.                 inputStream.close();
  319.                 inputStream = null;
  320.             }
  321.         }

  322.     }

  323.     /**
  324.      * <code>DataAdapter</code> for data provided as array of doubles.
  325.      */
  326.     private class ArrayDataAdapter extends DataAdapter {

  327.         /** Array of input  data values */
  328.         private final double[] inputArray;

  329.         /**
  330.          * Construct an ArrayDataAdapter from a double[] array
  331.          *
  332.          * @param in double[] array holding the data, a reference to the array will be stored
  333.          * @throws NullArgumentException if in is null
  334.          */
  335.         ArrayDataAdapter(double[] in) throws NullArgumentException {
  336.             super();
  337.             MathUtils.checkNotNull(in);
  338.             inputArray = in; // NOPMD - storing a reference to the array is intentional and documented here
  339.         }

  340.         /** {@inheritDoc} */
  341.         @Override
  342.         public void computeStats() {
  343.             sampleStats = new StreamingStatistics();
  344.             for (int i = 0; i < inputArray.length; i++) {
  345.                 sampleStats.addValue(inputArray[i]);
  346.             }
  347.         }

  348.         /** {@inheritDoc} */
  349.         @Override
  350.         public void computeBinStats() {
  351.             for (int i = 0; i < inputArray.length; i++) {
  352.                 StreamingStatistics stats =
  353.                     binStats.get(findBin(inputArray[i]));
  354.                 stats.addValue(inputArray[i]);
  355.             }
  356.         }

  357.         /** {@inheritDoc} */
  358.         @Override
  359.         public void close() {
  360.             // nothing to do
  361.         }

  362.     }

  363.     /**
  364.      * Fills binStats array (second pass through data file).
  365.      *
  366.      * @param da object providing access to the data
  367.      * @throws IOException  if an IO error occurs
  368.      */
  369.     private void fillBinStats(final DataAdapter da)
  370.         throws IOException {
  371.         // Set up grid
  372.         min = sampleStats.getMin();
  373.         max = sampleStats.getMax();
  374.         delta = (max - min)/binCount;

  375.         // Initialize binStats ArrayList
  376.         if (!binStats.isEmpty()) {
  377.             binStats.clear();
  378.         }
  379.         for (int i = 0; i < binCount; i++) {
  380.             StreamingStatistics stats = new StreamingStatistics();
  381.             binStats.add(i,stats);
  382.         }

  383.         // Filling data in binStats Array
  384.         da.computeBinStats();

  385.         // Assign upperBounds based on bin counts
  386.         upperBounds = new double[binCount];
  387.         upperBounds[0] =
  388.         ((double) binStats.get(0).getN()) / (double) sampleStats.getN();
  389.         for (int i = 1; i < binCount-1; i++) {
  390.             upperBounds[i] = upperBounds[i-1] +
  391.             ((double) binStats.get(i).getN()) / (double) sampleStats.getN();
  392.         }
  393.         upperBounds[binCount-1] = 1.0d;
  394.     }

  395.     /**
  396.      * Returns the index of the bin to which the given value belongs
  397.      *
  398.      * @param value  the value whose bin we are trying to find
  399.      * @return the index of the bin containing the value
  400.      */
  401.     private int findBin(double value) {
  402.         return FastMath.min(
  403.                 FastMath.max((int) FastMath.ceil((value - min) / delta) - 1, 0),
  404.                 binCount - 1);
  405.     }

  406.     /**
  407.      * Generates a random value from this distribution.
  408.      * <strong>Preconditions:</strong><ul>
  409.      * <li>the distribution must be loaded before invoking this method</li></ul>
  410.      * @return the random value.
  411.      * @throws MathIllegalStateException if the distribution has not been loaded
  412.      */
  413.     public double getNextValue() throws MathIllegalStateException {

  414.         if (!loaded) {
  415.             throw new MathIllegalStateException(LocalizedCoreFormats.DISTRIBUTION_NOT_LOADED);
  416.         }

  417.         return inverseCumulativeProbability(randomData.nextDouble());
  418.     }

  419.     /**
  420.      * Returns a {@link StatisticalSummary} describing this distribution.
  421.      * <strong>Preconditions:</strong><ul>
  422.      * <li>the distribution must be loaded before invoking this method</li></ul>
  423.      *
  424.      * @return the sample statistics
  425.      * @throws IllegalStateException if the distribution has not been loaded
  426.      */
  427.     public StatisticalSummary getSampleStats() {
  428.         return sampleStats;
  429.     }

  430.     /**
  431.      * Returns the number of bins.
  432.      *
  433.      * @return the number of bins.
  434.      */
  435.     public int getBinCount() {
  436.         return binCount;
  437.     }

  438.     /**
  439.      * Returns a List of {@link StreamingStatistics} instances containing
  440.      * statistics describing the values in each of the bins.  The list is
  441.      * indexed on the bin number.
  442.      *
  443.      * @return List of bin statistics.
  444.      */
  445.     public List<StreamingStatistics> getBinStats() {
  446.         return binStats;
  447.     }

  448.     /**
  449.      * <p>Returns a fresh copy of the array of upper bounds for the bins.
  450.      * Bins are: <br>
  451.      * [min,upperBounds[0]],(upperBounds[0],upperBounds[1]],...,
  452.      *  (upperBounds[binCount-2], upperBounds[binCount-1] = max].</p>
  453.      *
  454.      * @return array of bin upper bounds
  455.      */
  456.     public double[] getUpperBounds() {
  457.         double[] binUpperBounds = new double[binCount];
  458.         for (int i = 0; i < binCount - 1; i++) {
  459.             binUpperBounds[i] = min + delta * (i + 1);
  460.         }
  461.         binUpperBounds[binCount - 1] = max;
  462.         return binUpperBounds;
  463.     }

  464.     /**
  465.      * <p>Returns a fresh copy of the array of upper bounds of the subintervals
  466.      * of [0,1] used in generating data from the empirical distribution.
  467.      * Subintervals correspond to bins with lengths proportional to bin counts.</p>
  468.      *
  469.      * <strong>Preconditions:</strong><ul>
  470.      * <li>the distribution must be loaded before invoking this method</li></ul>
  471.      *
  472.      * @return array of upper bounds of subintervals used in data generation
  473.      * @throws NullPointerException unless a {@code load} method has been
  474.      * called beforehand.
  475.      */
  476.     public double[] getGeneratorUpperBounds() {
  477.         int len = upperBounds.length;
  478.         double[] out = new double[len];
  479.         System.arraycopy(upperBounds, 0, out, 0, len);
  480.         return out;
  481.     }

  482.     /**
  483.      * Property indicating whether or not the distribution has been loaded.
  484.      *
  485.      * @return true if the distribution has been loaded
  486.      */
  487.     public boolean isLoaded() {
  488.         return loaded;
  489.     }

  490.     /**
  491.      * Reseeds the random number generator used by {@link #getNextValue()}.
  492.      *
  493.      * @param seed random generator seed
  494.      */
  495.     public void reSeed(long seed) {
  496.         randomData.setSeed(seed);
  497.     }

  498.     // Distribution methods ---------------------------

  499.     /**
  500.      * {@inheritDoc}
  501.      *
  502.      * <p>Returns the kernel density normalized so that its integral over each bin
  503.      * equals the bin mass.</p>
  504.      *
  505.      * <p>Algorithm description:</p>
  506.      * <ol>
  507.      * <li>Find the bin B that x belongs to.</li>
  508.      * <li>Compute K(B) = the mass of B with respect to the within-bin kernel (i.e., the
  509.      * integral of the kernel density over B).</li>
  510.      * <li>Return k(x) * P(B) / K(B), where k is the within-bin kernel density
  511.      * and P(B) is the mass of B.</li></ol>
  512.      */
  513.     @Override
  514.     public double density(double x) {
  515.         if (x < min || x > max) {
  516.             return 0d;
  517.         }
  518.         final int binIndex = findBin(x);
  519.         final RealDistribution kernel = getKernel(binStats.get(binIndex));
  520.         double kernelDensity = kernel.density(x);
  521.         if (kernelDensity == 0d) {
  522.             return 0d;
  523.         }
  524.         return kernelDensity * pB(binIndex) / kB(binIndex);
  525.     }

  526.     /**
  527.      * {@inheritDoc}
  528.      *
  529.      * <p>Algorithm description:</p>
  530.      * <ol>
  531.      * <li>Find the bin B that x belongs to.</li>
  532.      * <li>Compute P(B) = the mass of B and P(B-) = the combined mass of the bins below B.</li>
  533.      * <li>Compute K(B) = the probability mass of B with respect to the within-bin kernel
  534.      * and K(B-) = the kernel distribution evaluated at the lower endpoint of B</li>
  535.      * <li>Return P(B-) + P(B) * [K(x) - K(B-)] / K(B) where
  536.      * K(x) is the within-bin kernel distribution function evaluated at x.</li></ol>
  537.      * <p>If K is a constant distribution, we return P(B-) + P(B) (counting the full
  538.      * mass of B).</p>
  539.      *
  540.      */
  541.     @Override
  542.     public double cumulativeProbability(double x) {
  543.         if (x < min) {
  544.             return 0d;
  545.         } else if (x >= max) {
  546.             return 1d;
  547.         }
  548.         final int binIndex = findBin(x);
  549.         final double pBminus = pBminus(binIndex);
  550.         final double pB = pB(binIndex);
  551.         final RealDistribution kernel = k(x);
  552.         if (kernel instanceof ConstantRealDistribution) {
  553.             if (x < kernel.getNumericalMean()) {
  554.                 return pBminus;
  555.             } else {
  556.                 return pBminus + pB;
  557.             }
  558.         }
  559.         final double[] binBounds = getUpperBounds();
  560.         final double kB = kB(binIndex);
  561.         final double lower = binIndex == 0 ? min : binBounds[binIndex - 1];
  562.         final double withinBinCum =
  563.             (kernel.cumulativeProbability(x) -  kernel.cumulativeProbability(lower)) / kB;
  564.         return pBminus + pB * withinBinCum;
  565.     }

  566.     /**
  567.      * {@inheritDoc}
  568.      *
  569.      * <p>Algorithm description:</p>
  570.      * <ol>
  571.      * <li>Find the smallest i such that the sum of the masses of the bins
  572.      *  through i is at least p.</li>
  573.      * <li>
  574.      *   Let K be the within-bin kernel distribution for bin i.<br>
  575.      *   Let K(B) be the mass of B under K. <br>
  576.      *   Let K(B-) be K evaluated at the lower endpoint of B (the combined
  577.      *   mass of the bins below B under K).<br>
  578.      *   Let P(B) be the probability of bin i.<br>
  579.      *   Let P(B-) be the sum of the bin masses below bin i. <br>
  580.      *   Let pCrit = p - P(B-)<br>
  581.      * <li>Return the inverse of K evaluated at <br>
  582.      *    K(B-) + pCrit * K(B) / P(B) </li>
  583.      *  </ol>
  584.      *
  585.      */
  586.     @Override
  587.     public double inverseCumulativeProbability(final double p) throws MathIllegalArgumentException {
  588.         MathUtils.checkRangeInclusive(p, 0, 1);

  589.         if (p == 0.0) {
  590.             return getSupportLowerBound();
  591.         }

  592.         if (p == 1.0) {
  593.             return getSupportUpperBound();
  594.         }

  595.         int i = 0;
  596.         while (cumBinP(i) < p) {
  597.             i++;
  598.         }

  599.         final RealDistribution kernel = getKernel(binStats.get(i));
  600.         final double kB = kB(i);
  601.         final double[] binBounds = getUpperBounds();
  602.         final double lower = i == 0 ? min : binBounds[i - 1];
  603.         final double kBminus = kernel.cumulativeProbability(lower);
  604.         final double pB = pB(i);
  605.         final double pBminus = pBminus(i);
  606.         final double pCrit = p - pBminus;
  607.         if (pCrit <= 0) {
  608.             return lower;
  609.         }
  610.         return kernel.inverseCumulativeProbability(kBminus + pCrit * kB / pB);
  611.     }

  612.     /**
  613.      * {@inheritDoc}
  614.      */
  615.     @Override
  616.     public double getNumericalMean() {
  617.        return sampleStats.getMean();
  618.     }

  619.     /**
  620.      * {@inheritDoc}
  621.      */
  622.     @Override
  623.     public double getNumericalVariance() {
  624.         return sampleStats.getVariance();
  625.     }

  626.     /**
  627.      * {@inheritDoc}
  628.      */
  629.     @Override
  630.     public double getSupportLowerBound() {
  631.        return min;
  632.     }

  633.     /**
  634.      * {@inheritDoc}
  635.      */
  636.     @Override
  637.     public double getSupportUpperBound() {
  638.         return max;
  639.     }

  640.     /**
  641.      * {@inheritDoc}
  642.      */
  643.     @Override
  644.     public boolean isSupportConnected() {
  645.         return true;
  646.     }

  647.     /**
  648.      * Reseed the underlying PRNG.
  649.      *
  650.      * @param seed new seed value
  651.      */
  652.     public void reseedRandomGenerator(long seed) {
  653.         randomData.setSeed(seed);
  654.     }

  655.     /**
  656.      * The probability of bin i.
  657.      *
  658.      * @param i the index of the bin
  659.      * @return the probability that selection begins in bin i
  660.      */
  661.     private double pB(int i) {
  662.         return i == 0 ? upperBounds[0] :
  663.             upperBounds[i] - upperBounds[i - 1];
  664.     }

  665.     /**
  666.      * The combined probability of the bins up to but not including bin i.
  667.      *
  668.      * @param i the index of the bin
  669.      * @return the probability that selection begins in a bin below bin i.
  670.      */
  671.     private double pBminus(int i) {
  672.         return i == 0 ? 0 : upperBounds[i - 1];
  673.     }

  674.     /**
  675.      * Mass of bin i under the within-bin kernel of the bin.
  676.      *
  677.      * @param i index of the bin
  678.      * @return the difference in the within-bin kernel cdf between the
  679.      * upper and lower endpoints of bin i
  680.      */
  681.     private double kB(int i) {
  682.         final double[] binBounds = getUpperBounds();
  683.         final RealDistribution kernel = getKernel(binStats.get(i));
  684.         return i == 0 ? kernel.probability(min, binBounds[0]) :
  685.             kernel.probability(binBounds[i - 1], binBounds[i]);
  686.     }

  687.     /**
  688.      * The within-bin kernel of the bin that x belongs to.
  689.      *
  690.      * @param x the value to locate within a bin
  691.      * @return the within-bin kernel of the bin containing x
  692.      */
  693.     private RealDistribution k(double x) {
  694.         final int binIndex = findBin(x);
  695.         return getKernel(binStats.get(binIndex));
  696.     }

  697.     /**
  698.      * The combined probability of the bins up to and including binIndex.
  699.      *
  700.      * @param binIndex maximum bin index
  701.      * @return sum of the probabilities of bins through binIndex
  702.      */
  703.     private double cumBinP(int binIndex) {
  704.         return upperBounds[binIndex];
  705.     }

  706.     /**
  707.      * The within-bin smoothing kernel. Returns a Gaussian distribution
  708.      * parameterized by {@code bStats}, unless the bin contains less than 2
  709.      * observations, in which case a constant distribution is returned.
  710.      *
  711.      * @param bStats summary statistics for the bin
  712.      * @return within-bin kernel parameterized by bStats
  713.      */
  714.     protected RealDistribution getKernel(StreamingStatistics bStats) {
  715.         if (bStats.getN() < 2 || bStats.getVariance() == 0) {
  716.             return new ConstantRealDistribution(bStats.getMean());
  717.         } else {
  718.             return new NormalDistribution(bStats.getMean(),
  719.                                           bStats.getStandardDeviation());
  720.         }
  721.     }
  722. }