First commit
[anna.git] / include / anna / core / util / Average.hpp
1 // ANNA - Anna is Not 'N' Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_core_util_Average_hpp
38 #define anna_core_util_Average_hpp
39
40 #include <anna/core/util/Millisecond.hpp>
41 #include <anna/core//util/DelayMeter.hpp>
42 #include <anna/core/functions.hpp>
43
44 namespace anna {
45
46 /**
47    Template para calcular la media de una sucesion de valores numericos.
48
49    Internamente trabaja con Microsegundos porque los métodos que los proporcionan son
50    más eficientes.
51 */
52 template <class T> class Average {
53 public:
54   /**
55      Constructor.
56      \param name Nombre logico de esta instancia.
57      \param measure Unidad de medida. Solo se usa a efecto de salida de datos.
58   */
59   Average(const char* name, const char* measure = NULL) :
60     a_name(name), a_accumulator(0), a_n(0), a_measure(measure) {;}
61
62   /**
63      Devuelve el indicador de validez de esta media.
64      \return \em true Si la media no tiene ningun valor o \em false en caso contrario.
65   */
66   bool isEmpty() const throw()  { return (a_n == 0); }
67
68   /**
69      Devuelve \em true si el valor de la media es cero, bien por no tener valores o
70      bien porque todos ellos eran cero.
71      \return \em true el valor de la media es cero o \em false en otro caso.
72   */
73   bool isZero() const throw() { return a_n == 0 || a_accumulator == 0; }
74
75   /**
76      Devuelve el numero de elementos de contiene la media.
77      \return el numero de elementos de contiene la media.
78   */
79   int size() const throw() { return a_n; }
80
81   /**
82      Devuelve el valor acumulado.
83      \return el valor acumulado.
84   */
85   T getAccumulator() const throw() { return a_accumulator; }
86
87   /**
88      Devuelve la media de la sucesion de valores numericos asociados a esta.
89      \return La media de la sucesion de valores numericos asociados a esta.
90      \warning Antes de invocar a este operador hay que verificar que #isEmpty devuelve \em false.
91   */
92   T value() const throw() { return (isEmpty() == true) ? T(0) : (a_accumulator / a_n);  }
93
94   /**
95      Inicializa el valor de la media.
96   */
97   void clear() throw() {  a_accumulator = 0; a_n = 0; }
98
99   /**
100    * Establece manualmente el valor de la estadística.
101    * \param value Valor que tomará el acumulador de este instancia.
102    * \param _n valor que tomará el conteador de esta instancia.
103    */
104   void setValue(const T& value, const unsigned int _n) throw() {
105     a_accumulator = value;
106     a_n = _n;
107   }
108
109   /**
110      Devuelve la media de la sucesion de valores numericos asociados a esta.
111      \return La media de la sucesion de valores numericos asociados a esta.
112      \warning Antes de invocar a este operador hay que verificar que #isEmpty devuelve \em false.
113   */
114   operator T() const throw() { return value(); }
115
116   /**
117      Inicializa el valor de esta media.
118      \param value Valor con el que iniciar la media.
119      \return La referencia a esta instancia.
120   */
121   Average<T>& operator = (const T value)
122   throw() {
123     a_accumulator = value;
124     a_n = 1;
125     return *this;
126   }
127
128   /**
129      Contructor copia.
130      \param other Objeto del que obtener los valores.
131      \return La referencia a esta instancia.
132   */
133   Average<T>& operator = (const Average<T>& other)
134   throw() {
135     a_accumulator = other.a_accumulator;
136     a_n = other.a_n;
137     return *this;
138   }
139
140   /**
141      Incrementa la media con el valor recibido.
142      \param v Valor con el que incrementar la media.
143      \return La referencia a esta instancia.
144   */
145   Average<T>& operator += (const T& v)
146   throw() {
147     const T backup(a_accumulator);
148
149     if((a_accumulator += v) < backup) {
150       a_accumulator = v;
151       a_n = 1;
152     } else
153       a_n ++;
154
155     return *this;
156   }
157
158   /**
159      Decrementa la media con el valor recibido.
160      \param v Valor con el que incrementar la media.
161      \return La referencia a esta instancia.
162   */
163   Average<T>& operator -= (const T v)
164   throw() {
165     if(a_accumulator > v && a_n > 1) {
166       a_accumulator -= v;
167       a_n --;
168     } else {
169       a_accumulator = 0;
170       a_n = 0;
171     }
172
173     return *this;
174   }
175
176   /**
177      Devuelve una cadena con la informacion referente a esta clase.
178      \return Una cadena con la informacion referente a esta clase.
179   */
180   std::string asString() const
181   throw() {
182     std::string msg(a_name);
183     msg += " { Accumulate: ";
184     msg += functions::asString(a_accumulator);
185
186     if(a_measure != NULL)
187       msg += " " + std::string(a_measure);
188
189     msg += functions::asString(" | N: %u | avg: ", a_n);
190     msg += functions::asString(value());
191
192     if(a_measure != NULL)
193       msg += " " + std::string(a_measure);
194
195     return msg += " }";
196   }
197
198 private:
199   const char* a_name;
200   const char* a_measure;
201   T a_accumulator;
202   unsigned int a_n;
203 };
204
205 }
206
207 #endif
208
209
210