View Javadoc
1   package org.djutils.stats.summarizers.event;
2   
3   import java.io.Serializable;
4   import java.rmi.RemoteException;
5   import java.util.Calendar;
6   
7   import org.djutils.event.Event;
8   import org.djutils.event.EventListener;
9   import org.djutils.event.EventListenerMap;
10  import org.djutils.event.EventProducer;
11  import org.djutils.event.LocalEventProducer;
12  import org.djutils.event.TimedEvent;
13  import org.djutils.exceptions.Throw;
14  import org.djutils.stats.summarizers.TimestampWeightedTally;
15  
16  /**
17   * The TimestampWeightedTally class defines a time-weighted tally based on timestamped data. The difference with a normal
18   * time-weighed tally is that the weight of a value is only known at the occurrence of the next timestamp. Furthermore, a last
19   * timestamp needs to be specified to determine the weight of the last value. This EventBased version of the tally can be
20   * notified with timestamps and values using the EventListenerInterface. It also produces events when values are tallied and
21   * when the tally is initialized. Timestamps can be Number based or Calendar based.
22   * <p>
23   * Copyright (c) 2020-2024 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
24   * for project information <a href="https://simulation.tudelft.nl/" target="_blank"> https://simulation.tudelft.nl</a>. The DSOL
25   * project is distributed under a three-clause BSD-style license, which can be found at
26   * <a href="https://simulation.tudelft.nl/dsol/3.0/license.html" target="_blank">
27   * https://simulation.tudelft.nl/dsol/3.0/license.html</a>. <br>
28   * @author <a href="https://www.tudelft.nl/averbraeck" target="_blank"> Alexander Verbraeck</a>
29   */
30  public class EventBasedTimestampWeightedTally extends TimestampWeightedTally implements EventProducer, EventListener
31  {
32      /** */
33      private static final long serialVersionUID = 20200228L;
34  
35      /** The embedded EventProducer. */
36      private EventProducer eventProducer = null;
37  
38      /**
39       * constructs a new EventBasedTimestampWeightedTally with a description.
40       * @param description String; the description of this EventBasedTimestampWeightedTally
41       */
42      public EventBasedTimestampWeightedTally(final String description)
43      {
44          this(description, new LocalEventProducer());
45      }
46  
47      /**
48       * Construct a new EventBasedTimestampWeightedTally with a description.
49       * @param description String; the description of this WeightedTally
50       * @param eventProducer EventProducer; the EventProducer to embed and use in this statistic
51       */
52      public EventBasedTimestampWeightedTally(final String description, final EventProducer eventProducer)
53      {
54          super(description);
55          Throw.whenNull(eventProducer, "eventProducer cannot be null");
56          this.eventProducer = eventProducer;
57      }
58  
59      @Override
60      public EventListenerMap getEventListenerMap() throws RemoteException
61      {
62          return this.eventProducer.getEventListenerMap();
63      }
64  
65      @Override
66      public void initialize()
67      {
68          super.initialize();
69          if (this.eventProducer != null)
70          {
71              try
72              {
73                  this.eventProducer.fireEvent(StatisticsEvents.INITIALIZED_EVENT);
74              }
75              catch (RemoteException exception)
76              {
77                  throw new RuntimeException(exception);
78              }
79          }
80      }
81  
82      @Override
83      public void notify(final Event event)
84      {
85          if (event instanceof TimedEvent<?>)
86          {
87              TimedEvent<?> timedEvent = (TimedEvent<?>) event;
88              double value = 0.0;
89              if (event.getContent() instanceof Number)
90              {
91                  value = ((Number) event.getContent()).doubleValue();
92              }
93              else
94              {
95                  throw new IllegalArgumentException(
96                          "EventBasedTimestampWeightedTally.notify: Content " + event.getContent() + " should be a Number");
97              }
98              Object timestamp = timedEvent.getTimeStamp();
99              if (timestamp instanceof Number)
100             {
101                 register(((Number) timestamp).doubleValue(), value);
102             }
103             else if (timestamp instanceof Calendar)
104             {
105                 register(((Calendar) timestamp).getTimeInMillis(), value);
106             }
107             else
108             {
109                 throw new IllegalArgumentException(
110                         "EventBasedTimestampWeightedTally.notify: timestamp should be a Number or Calendar");
111             }
112         }
113         else
114         {
115             throw new IllegalArgumentException("EventBasedTimestampWeightedTally.notify: Event should be a TimedEvent");
116         }
117     }
118 
119     /**
120      * Process one observed Calender-based value. The time used will be the Calendar's time in milliseconds. Silently ignore
121      * when a value is registered, but tally is not active, i.e. when endObservations() has been called.
122      * @param timestamp Calendar; the Calendar object representing the timestamp
123      * @param value double; the value to process
124      * @return double; the value
125      * @throws NullPointerException when timestamp is null
126      * @throws IllegalArgumentException when value is NaN
127      * @throws IllegalArgumentException when given timestamp is before last timestamp
128      */
129     @Override
130     public double register(final Calendar timestamp, final double value)
131     {
132         super.register(timestamp, value);
133         try
134         {
135             if (hasListeners())
136             {
137                 this.eventProducer.fireEvent(StatisticsEvents.TIMESTAMPED_OBSERVATION_ADDED_EVENT,
138                         new Serializable[] {timestamp, value});
139                 fireEvents(timestamp);
140             }
141         }
142         catch (RemoteException exception)
143         {
144             throw new RuntimeException(exception);
145         }
146         return value;
147     }
148 
149     /**
150      * Process one observed Number-based value. Silently ignore when a value is registered, but tally is not active, i.e. when
151      * endObservations() has been called.
152      * @param timestamp Number; the object representing the timestamp
153      * @param value double; the value to process
154      * @return double; the value
155      * @throws NullPointerException when timestamp is null
156      * @throws IllegalArgumentException when value is NaN or timestamp is NaN
157      * @throws IllegalArgumentException when given timestamp is before last timestamp
158      */
159     @Override
160     public double register(final Number timestamp, final double value)
161     {
162         super.register(timestamp, value);
163         try
164         {
165             if (hasListeners())
166             {
167                 this.eventProducer.fireEvent(StatisticsEvents.TIMESTAMPED_OBSERVATION_ADDED_EVENT,
168                         new Serializable[] {timestamp, value});
169                 fireEvents(timestamp);
170             }
171         }
172         catch (RemoteException exception)
173         {
174             throw new RuntimeException(exception);
175         }
176         return value;
177     }
178 
179     /**
180      * Explicit;y override the double value method signature of WeightedTally to call the right method.<br>
181      * Process one observed double value. Silently ignore when a value is registered, but tally is not active, i.e. when
182      * endObservations() has been called.
183      * @param timestamp Number; the object representing the timestamp
184      * @param value double; the value to process
185      * @return double; the value
186      * @throws NullPointerException when timestamp is null
187      * @throws IllegalArgumentException when value is NaN or timestamp is NaN
188      * @throws IllegalArgumentException when given timestamp is before last timestamp
189      */
190     @Override
191     public double register(final double timestamp, final double value)
192     {
193         return register((Number) Double.valueOf(timestamp), value);
194     }
195 
196     /**
197      * Method that can be overridden to fire own events or additional events when registering an observation.
198      * @param <T> a type for the timestamp that is Serializable and Comparable
199      * @param timestamp T; the timestamp to use in the TimedEvents
200      * @throws RemoteException on network error
201      */
202     protected <T extends Serializable & Comparable<T>> void fireEvents(final Serializable timestamp) throws RemoteException
203     {
204         // Note that All implementations of Number are Comparable and (by default) Serializable. So is Calendar.
205         @SuppressWarnings("unchecked")
206         T castedTimestamp = (T) timestamp;
207         fireTimedEvent(StatisticsEvents.TIMED_N_EVENT, getN(), castedTimestamp);
208         fireTimedEvent(StatisticsEvents.TIMED_MIN_EVENT, getMin(), castedTimestamp);
209         fireTimedEvent(StatisticsEvents.TIMED_MAX_EVENT, getMax(), castedTimestamp);
210         fireTimedEvent(StatisticsEvents.TIMED_WEIGHTED_POPULATION_MEAN_EVENT, getWeightedPopulationMean(), castedTimestamp);
211         fireTimedEvent(StatisticsEvents.TIMED_WEIGHTED_POPULATION_VARIANCE_EVENT, getWeightedPopulationVariance(),
212                 castedTimestamp);
213         fireTimedEvent(StatisticsEvents.TIMED_WEIGHTED_POPULATION_STDEV_EVENT, getWeightedPopulationStDev(), castedTimestamp);
214         fireTimedEvent(StatisticsEvents.TIMED_WEIGHTED_SUM_EVENT, getWeightedSum(), castedTimestamp);
215         fireTimedEvent(StatisticsEvents.TIMED_WEIGHTED_SAMPLE_MEAN_EVENT, getWeightedSampleMean(), castedTimestamp);
216         fireTimedEvent(StatisticsEvents.TIMED_WEIGHTED_SAMPLE_VARIANCE_EVENT, getWeightedSampleVariance(), castedTimestamp);
217         fireTimedEvent(StatisticsEvents.TIMED_WEIGHTED_SAMPLE_STDEV_EVENT, getWeightedSampleStDev(), castedTimestamp);
218     }
219 
220     @Override
221     @SuppressWarnings("checkstyle:designforextension")
222     public String toString()
223     {
224         return "EventBasedWeightedTally" + super.toString().substring("WeightedTally".length());
225     }
226 
227 }