View Javadoc
1   package org.opentrafficsim.core.distributions;
2   
3   import java.io.Serializable;
4   import java.util.ArrayList;
5   import java.util.List;
6   
7   import nl.tudelft.simulation.jstats.distributions.DistUniform;
8   import nl.tudelft.simulation.jstats.streams.StreamInterface;
9   import nl.tudelft.simulation.language.Throw;
10  
11  /**
12   * Generic implementation of a set of objects that have a draw method with corresponding probabilities / frequencies.
13   * <p>
14   * Copyright (c) 2013-2016 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
15   * BSD-style license. See <a href="http://opentrafficsim.org/docs/current/license.html">OpenTrafficSim License</a>.
16   * <p>
17   * @version $Revision$, $LastChangedDate$, by $Author$, initial version Mar 1, 2016 <br>
18   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
19   * @param <O> Type of the object returned by the draw method
20   */
21  public class Distribution<O> implements Generator<O>, Serializable
22  {
23      /** */
24      private static final long serialVersionUID = 20160301L;
25  
26      /** The generators (with their probabilities or frequencies). */
27      private final List<FrequencyAndObject<O>> generators = new ArrayList<>();
28  
29      /** Sum of all probabilities or frequencies. */
30      private double cumulativeTotal;
31  
32      /** The uniform random generator used to select a Generator. */
33      private final DistUniform random;
34  
35      /**
36       * Construct a new Distribution.
37       * @param generators List&lt;FrequencyAndObject&lt;O&gt;&gt;; the generators and their frequencies (or probabilities)
38       * @param stream StreamInterface; source for randomness
39       * @throws ProbabilityException when a frequency (or probability) is negative, or when generators is null or stream is null
40       */
41      public Distribution(final List<FrequencyAndObject<O>> generators, final StreamInterface stream) throws ProbabilityException
42      {
43          this(stream);
44          Throw.when(null == generators, ProbabilityException.class, "generators may not be null");
45          // Store a defensive copy of the generator list (the generators are immutable; a list of them is not) and make sure it
46          // is a List that supports add, remove, etc.
47          this.generators.addAll(generators);
48          fixProbabilities();
49      }
50  
51      /**
52       * Construct a new Distribution with no generators.
53       * @param stream StreamInterface; source for randomness
54       * @throws ProbabilityException when a frequency (or probability) is negative, or when generators is null or stream is null
55       */
56      public Distribution(final StreamInterface stream) throws ProbabilityException
57      {
58          Throw.when(null == stream, ProbabilityException.class, "random stream may not be null");
59          this.random = new DistUniform(stream, 0, 1);
60      }
61  
62      /**
63       * Compute the cumulative frequencies of the storedGenerators.
64       * @throws ProbabilityException on negative frequency
65       */
66      private void fixProbabilities() throws ProbabilityException
67      {
68          if (0 == this.generators.size())
69          {
70              return;
71          }
72          this.cumulativeTotal = 0;
73          for (FrequencyAndObject<O> generator : this.generators)
74          {
75              double frequency = generator.getFrequency();
76              Throw.when(frequency < 0, ProbabilityException.class, "Negative frequency or probability is not allowed (got "
77                      + frequency + ")");
78              this.cumulativeTotal += frequency;
79          }
80      }
81  
82      /** {@inheritDoc} */
83      public final O draw() throws ProbabilityException
84      {
85          Throw.when(0 == this.generators.size(), ProbabilityException.class, "Cannot draw from empty collection");
86          Throw.when(0 == this.cumulativeTotal, ProbabilityException.class, "Sum of frequencies or probabilities must be > 0");
87  
88          double randomValue = this.random.draw() * this.cumulativeTotal;
89          for (FrequencyAndObject<O> fAndO : this.generators)
90          {
91              double frequency = fAndO.getFrequency();
92              if (frequency >= randomValue)
93              {
94                  return fAndO.getObject();
95              }
96              randomValue -= frequency;
97          }
98          // If we get here we missed the intended object by a few ULP; return the first object that has non-zero frequency
99          FrequencyAndObject<O> useThisOne = this.generators.get(0);
100         for (FrequencyAndObject<O> fAndO : this.generators)
101         {
102             if (fAndO.getFrequency() > 0)
103             {
104                 useThisOne = fAndO;
105                 break;
106             }
107         }
108         return useThisOne.getObject();
109     }
110 
111     /**
112      * Append a generator to the internally stored list.
113      * @param generator FrequencyAndObject&lt;O&gt;; the generator to add
114      * @return Distribution&lt;O&gt;; this
115      * @throws ProbabilityException when frequency less than zero
116      */
117     public final Distribution<O> add(final FrequencyAndObject<O> generator) throws ProbabilityException
118     {
119         return add(this.generators.size(), generator);
120     }
121 
122     /**
123      * Insert a generator at the specified position in the internally stored list.
124      * @param index int; position to store the generator
125      * @param generator FrequencyAndObject&lt;O&gt;; the generator to add
126      * @return Distribution&lt;O&gt;; this
127      * @throws ProbabilityException when frequency less than zero
128      */
129     public final Distribution<O> add(final int index, final FrequencyAndObject<O> generator) throws ProbabilityException
130     {
131         Throw.when(generator.getFrequency() < 0, ProbabilityException.class, "frequency (or probability) must be >= 0 (got "
132                 + generator.getFrequency() + ")");
133         this.generators.add(index, generator);
134         fixProbabilities();
135         return this;
136     }
137 
138     /**
139      * Remove the generator at the specified position from the internally stored list.
140      * @param index int; the position
141      * @return this
142      * @throws IndexOutOfBoundsException when index is &lt; 0 or &gt;= size
143      * @throws ProbabilityException if the sum of the remaining probabilities or frequencies adds up to 0
144      */
145     public final Distribution<O> remove(final int index) throws IndexOutOfBoundsException, ProbabilityException
146     {
147         this.generators.remove(index);
148         fixProbabilities();
149         return this;
150     }
151 
152     /**
153      * Replace the generator at the specified position.
154      * @param index int; the position of the generator that must be replaced
155      * @param generator FrequencyAndObject; the new generator and the frequency (or probability)
156      * @return this
157      * @throws ProbabilityException when the frequency (or probability) &lt; 0, or when index is &lt; 0 or &gt;= size
158      */
159     public final Distribution<O> set(final int index, final FrequencyAndObject<O> generator) throws ProbabilityException
160     {
161         Throw.when(generator.getFrequency() < 0, ProbabilityException.class, "frequency (or probability) must be >= 0 (got "
162                 + generator.getFrequency() + ")");
163         try
164         {
165             this.generators.set(index, generator);
166         }
167         catch (IndexOutOfBoundsException ie)
168         {
169             throw new ProbabilityException("Index out of bounds for set operation, index=" + index);
170         }
171         fixProbabilities();
172         return this;
173     }
174 
175     /**
176      * Alter the frequency (or probability) of one of the stored generators.
177      * @param index int; index of the stored generator
178      * @param frequency double; new frequency (or probability)
179      * @return this
180      * @throws ProbabilityException when the frequency (or probability) &lt; 0, or when index is &lt; 0 or &gt;= size
181      */
182     public final Distribution<O> modifyFrequency(final int index, final double frequency) throws ProbabilityException
183     {
184         return set(index, new FrequencyAndObject<O>(frequency, this.generators.get(index).getObject()));
185     }
186 
187     /**
188      * Empty the internally stored list.
189      * @return this
190      */
191     public final Distribution<O> clear()
192     {
193         this.generators.clear();
194         return this;
195     }
196 
197     /**
198      * Retrieve one of the internally stored generators.
199      * @param index int; the index of the FrequencyAndObject to retrieve
200      * @return FrequencyAndObject&lt;O&gt;; the generator stored at position <cite>index</cite>
201      * @throws ProbabilityException when index &lt; 0 or &gt;= size()
202      */
203     public final FrequencyAndObject<O> get(final int index) throws ProbabilityException
204     {
205         try
206         {
207             return this.generators.get(index);
208         }
209         catch (IndexOutOfBoundsException ie)
210         {
211             throw new ProbabilityException("Index out of bounds for set operation, index=" + index);
212         }
213     }
214 
215     /**
216      * Report the number of generators.
217      * @return int; the number of generators
218      */
219     public final int size()
220     {
221         return this.generators.size();
222     }
223 
224     /** {@inheritDoc} */
225     @Override
226     public final int hashCode()
227     {
228         final int prime = 31;
229         int result = 1;
230         long temp;
231         temp = Double.doubleToLongBits(this.cumulativeTotal);
232         result = prime * result + (int) (temp ^ (temp >>> 32));
233         result = prime * result + ((this.generators == null) ? 0 : this.generators.hashCode());
234         result = prime * result + ((this.random == null) ? 0 : this.random.hashCode());
235         return result;
236     }
237 
238     /** {@inheritDoc} */
239     @Override
240     @SuppressWarnings("checkstyle:needbraces")
241     public final boolean equals(final Object obj)
242     {
243         if (this == obj)
244             return true;
245         if (obj == null)
246             return false;
247         if (getClass() != obj.getClass())
248             return false;
249         Distribution<?> other = (Distribution<?>) obj;
250         if (Double.doubleToLongBits(this.cumulativeTotal) != Double.doubleToLongBits(other.cumulativeTotal))
251             return false;
252         if (this.generators == null)
253         {
254             if (other.generators != null)
255                 return false;
256         }
257         else if (!this.generators.equals(other.generators))
258             return false;
259         if (this.random == null)
260         {
261             if (other.random != null)
262                 return false;
263         }
264         else if (!this.random.equals(other.random))
265             return false;
266         return true;
267     }
268 
269     /** {@inheritDoc} */
270     public final String toString()
271     {
272         StringBuilder result = new StringBuilder();
273         result.append("Distribution [");
274         String separator = "";
275         for (FrequencyAndObject<O> fAndO : this.generators)
276         {
277             result.append(separator + fAndO.getFrequency() + "->" + fAndO.getObject());
278             separator = ", ";
279         }
280         result.append(']');
281         return result.toString();
282     }
283 
284     /**
285      * Immutable storage for a frequency (or probability) plus a Generator.
286      * <p>
287      * Copyright (c) 2013-2016 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands.<br>
288      * All rights reserved. <br>
289      * BSD-style license. See <a href="http://opentrafficsim.org/docs/current/license.html">OpenTrafficSim License</a>.
290      * <p>
291      * @version $Revision$, $LastChangedDate$, by $Author$, initial version Mar 1, 2016 <br>
292      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
293      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
294      * @param <O> Type of the object returned by the draw method
295      */
296     public static class FrequencyAndObject<O> implements Serializable
297     {
298         /** */
299         private static final long serialVersionUID = 20160301L;
300 
301         /** Frequency (or probability) of an object. */
302         private final double frequency;
303 
304         /** The object. */
305         private final O object;
306 
307         /**
308          * Construct a new FrequencyAndObject instance.
309          * @param frequency double; the (<b>not cumulative</b>) frequency (or probability) of the <cite>generatingObject</cite>
310          * @param object O; an object
311          */
312         public FrequencyAndObject(final double frequency, final O object)
313         {
314             this.frequency = frequency;
315             this.object = object;
316         }
317 
318         /**
319          * Retrieve the frequency (or probability) of this FrequencyAndObject.
320          * @return double; the frequency (or probability) of this FrequencyAndObject
321          */
322         public final double getFrequency()
323         {
324             return this.frequency;
325         }
326 
327         /**
328          * Call the draw method of the generatingObject and return its result.
329          * @return O; the result of a call to the draw method of the generatingObject
330          */
331         public final O getObject()
332         {
333             return this.object;
334         }
335 
336         /** {@inheritDoc} */
337         @Override
338         public final int hashCode()
339         {
340             final int prime = 31;
341             int result = 1;
342             long temp;
343             temp = Double.doubleToLongBits(this.frequency);
344             result = prime * result + (int) (temp ^ (temp >>> 32));
345             result = prime * result + ((this.object == null) ? 0 : this.object.hashCode());
346             return result;
347         }
348 
349         /** {@inheritDoc} */
350         @Override
351         @SuppressWarnings("checkstyle:needbraces")
352         public final boolean equals(final Object obj)
353         {
354             if (this == obj)
355                 return true;
356             if (obj == null)
357                 return false;
358             if (getClass() != obj.getClass())
359                 return false;
360             FrequencyAndObject<?> other = (FrequencyAndObject<?>) obj;
361             if (Double.doubleToLongBits(this.frequency) != Double.doubleToLongBits(other.frequency))
362                 return false;
363             if (this.object == null)
364             {
365                 if (other.object != null)
366                     return false;
367             }
368             else if (!this.object.equals(other.object))
369                 return false;
370             return true;
371         }
372 
373         /** {@inheritDoc} */
374         @Override
375         public final String toString()
376         {
377             return "FrequencyAndObject [frequency=" + this.frequency + ", object=" + this.object + "]";
378         }
379 
380     }
381 
382 }