View Javadoc
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  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  package org.hipparchus.distribution.continuous;
23  
24  import java.util.ArrayList;
25  import java.util.HashMap;
26  import java.util.List;
27  import java.util.Map;
28  import java.util.Map.Entry;
29  
30  import org.hipparchus.distribution.EnumeratedDistribution;
31  import org.hipparchus.exception.MathIllegalArgumentException;
32  import org.hipparchus.util.MathArrays;
33  import org.hipparchus.util.MathUtils;
34  import org.hipparchus.util.Pair;
35  
36  /**
37   * Implementation of a real-valued {@link EnumeratedDistribution}.
38   * <p>
39   * Values with zero-probability are allowed but they do not extend the
40   * support.
41   * <p>
42   * Duplicate values are allowed. Probabilities of duplicate values are
43   * combined when computing cumulative probabilities and statistics.
44   */
45  public class EnumeratedRealDistribution extends AbstractRealDistribution {
46  
47      /** Serializable UID. */
48      private static final long serialVersionUID = 20130308L;
49  
50      /**
51       * {@link EnumeratedDistribution} (using the {@link Double} wrapper)
52       * used to generate the pmf.
53       */
54      private final EnumeratedDistribution<Double> innerDistribution;
55  
56      /**
57       * Create a discrete real-valued distribution from the input data.  Values are assigned
58       * mass based on their frequency.  For example, [0,1,1,2] as input creates a distribution
59       * with values 0, 1 and 2 having probability masses 0.25, 0.5 and 0.25 respectively,
60       *
61       * @param data input dataset
62       */
63      public EnumeratedRealDistribution(final double[] data) {
64          final Map<Double, Integer> dataMap = new HashMap<>();
65          for (double value : data) {
66              Integer count = dataMap.get(value);
67              if (count == null) {
68                  count = 0;
69              }
70              dataMap.put(value, ++count);
71          }
72          final int massPoints = dataMap.size();
73          final double denom = data.length;
74          final double[] values = new double[massPoints];
75          final double[] probabilities = new double[massPoints];
76          int index = 0;
77          for (Entry<Double, Integer> entry : dataMap.entrySet()) {
78              values[index] = entry.getKey();
79              probabilities[index] = entry.getValue() / denom;
80              index++;
81          }
82          innerDistribution =
83                  new EnumeratedDistribution<>(createDistribution(values, probabilities));
84      }
85  
86      /**
87       * Create a discrete real-valued distribution using the given probability mass function
88       * enumeration.
89       *
90       * @param singletons array of random variable values.
91       * @param probabilities array of probabilities.
92       * @throws MathIllegalArgumentException if
93       * {@code singletons.length != probabilities.length}
94       * @throws MathIllegalArgumentException if any of the probabilities are negative.
95       * @throws MathIllegalArgumentException if any of the probabilities are NaN.
96       * @throws MathIllegalArgumentException if any of the probabilities are infinite.
97       */
98      public EnumeratedRealDistribution(final double[] singletons, final double[] probabilities)
99          throws MathIllegalArgumentException {
100         innerDistribution =
101                 new EnumeratedDistribution<>(createDistribution(singletons, probabilities));
102     }
103 
104 
105     /**
106      * Create the list of Pairs representing the distribution from singletons and probabilities.
107      *
108      * @param singletons values
109      * @param probabilities probabilities
110      * @return list of value/probability pairs
111      * @throws MathIllegalArgumentException if probabilities contains negative, infinite or NaN values or only 0's
112      */
113     private static List<Pair<Double, Double>> createDistribution(double[] singletons,
114                                                                  double[] probabilities) {
115         MathArrays.checkEqualLength(singletons, probabilities);
116         final List<Pair<Double, Double>> samples = new ArrayList<>(singletons.length);
117 
118         final double[] normalizedProbabilities = EnumeratedDistribution.checkAndNormalize(probabilities);
119         for (int i = 0; i < singletons.length; i++) {
120             samples.add(new Pair<>(singletons[i], normalizedProbabilities[i]));
121         }
122         return samples;
123     }
124 
125     /**
126      * For a random variable {@code X} whose values are distributed according to
127      * this distribution, this method returns {@code P(X = x)}. In other words,
128      * this method represents the probability mass function (PMF) for the
129      * distribution.
130      * <p>
131      * Note that if {@code x1} and {@code x2} satisfy {@code x1.equals(x2)},
132      * or both are null, then {@code probability(x1) = probability(x2)}.
133      *
134      * @param x the point at which the PMF is evaluated
135      * @return the value of the probability mass function at {@code x}
136      */
137     public double probability(final double x) {
138         return innerDistribution.probability(x);
139     }
140 
141     /**
142      * For a random variable {@code X} whose values are distributed according to
143      * this distribution, this method returns {@code P(X = x)}. In other words,
144      * this method represents the probability mass function (PMF) for the
145      * distribution.
146      *
147      * @param x the point at which the PMF is evaluated
148      * @return the value of the probability mass function at point {@code x}
149      */
150     @Override
151     public double density(final double x) {
152         return probability(x);
153     }
154 
155     /**
156      * {@inheritDoc}
157      */
158     @Override
159     public double cumulativeProbability(final double x) {
160         double probability = 0;
161 
162         for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
163             if (sample.getKey() <= x) {
164                 probability += sample.getValue();
165             }
166         }
167 
168         return probability;
169     }
170 
171     /**
172      * {@inheritDoc}
173      */
174     @Override
175     public double inverseCumulativeProbability(final double p) throws MathIllegalArgumentException {
176         MathUtils.checkRangeInclusive(p, 0, 1);
177 
178         double probability = 0;
179         double x = getSupportLowerBound();
180         for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
181             if (sample.getValue() == 0.0) {
182                 continue;
183             }
184 
185             probability += sample.getValue();
186             x = sample.getKey();
187 
188             if (probability >= p) {
189                 break;
190             }
191         }
192 
193         return x;
194     }
195 
196     /**
197      * {@inheritDoc}
198      *
199      * @return {@code sum(singletons[i] * probabilities[i])}
200      */
201     @Override
202     public double getNumericalMean() {
203         double mean = 0;
204 
205         for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
206             mean += sample.getValue() * sample.getKey();
207         }
208 
209         return mean;
210     }
211 
212     /**
213      * {@inheritDoc}
214      *
215      * @return {@code sum((singletons[i] - mean) ^ 2 * probabilities[i])}
216      */
217     @Override
218     public double getNumericalVariance() {
219         double mean = 0;
220         double meanOfSquares = 0;
221 
222         for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
223             mean += sample.getValue() * sample.getKey();
224             meanOfSquares += sample.getValue() * sample.getKey() * sample.getKey();
225         }
226 
227         return meanOfSquares - mean * mean;
228     }
229 
230     /**
231      * {@inheritDoc}
232      *
233      * Returns the lowest value with non-zero probability.
234      *
235      * @return the lowest value with non-zero probability.
236      */
237     @Override
238     public double getSupportLowerBound() {
239         double min = Double.POSITIVE_INFINITY;
240         for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
241             if (sample.getKey() < min && sample.getValue() > 0) {
242                 min = sample.getKey();
243             }
244         }
245 
246         return min;
247     }
248 
249     /**
250      * {@inheritDoc}
251      *
252      * Returns the highest value with non-zero probability.
253      *
254      * @return the highest value with non-zero probability.
255      */
256     @Override
257     public double getSupportUpperBound() {
258         double max = Double.NEGATIVE_INFINITY;
259         for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
260             if (sample.getKey() > max && sample.getValue() > 0) {
261                 max = sample.getKey();
262             }
263         }
264 
265         return max;
266     }
267 
268     /**
269      * {@inheritDoc}
270      *
271      * The support of this distribution is connected.
272      *
273      * @return {@code true}
274      */
275     @Override
276     public boolean isSupportConnected() {
277         return true;
278     }
279 
280     /**
281      * Return the probability mass function as a list of (value, probability) pairs.
282      *
283      * @return the probability mass function.
284      */
285     public List<Pair<Double, Double>> getPmf() {
286         return innerDistribution.getPmf();
287     }
288 }