Utils: Fix Statistics unit-test float compare glitch
[senf.git] / senf / Utils / Statistics.cc
1 // $Id$
2 //
3 // Copyright (C) 2008 
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \file
24     \brief Statistics non-inline non-template implementation */
25
26 #include "Statistics.hh"
27 //#include "Statistics.ih"
28
29 // Custom includes
30 #include <cmath>
31 #include <sstream>
32 #include <senf/Utils/Console/Console.hh>
33 #include "StatisticsTargets.hh"
34
35 //#include "Statistics.mpp"
36 #define prefix_
37 ///////////////////////////////cc.p////////////////////////////////////////
38
39 ///////////////////////////////////////////////////////////////////////////
40 // senf::StatisticsBase
41
42 prefix_ void senf::StatisticsBase::enter(float min, float avg, float max, float dev)
43 {
44     min_ = min;
45     avg_ = avg;
46     max_ = max;
47     dev_ = dev;
48     generateOutput();
49     signalChildren();
50 }
51
52 prefix_ senf::Collector & senf::StatisticsBase::operator[](unsigned rank)
53 {
54     Children::iterator i (children_.find(rank));
55     if (i == children_.end())
56         throw InvalidRankException();
57     return i->second;
58 }
59
60 prefix_ senf::Collector & senf::StatisticsBase::collect(unsigned rank)
61 {
62     std::pair<Children::iterator, bool> state (
63         children_.insert(std::make_pair(rank, Collector(this, rank))) );
64     if (! state.second)
65         throw DuplicateRankException();
66     return state.first->second;
67 }
68
69 prefix_ senf::StatisticsBase::OutputProxy<senf::StatisticsBase>
70 senf::StatisticsBase::output(unsigned n)
71 {
72     OutputMap::iterator i (outputs_.find(n));
73     if (i == outputs_.end()) {
74         i = outputs_.insert(std::make_pair(n, OutputEntry(n))).first;
75         std::stringstream nm;
76         nm << "output" << path() << ":" << n;
77         base().dir.node().add(nm.str(), i->second.dir);
78         detail::StatisticsLoggerRegistry::instance().apply(*this, n, i->second.dir);
79     }
80     if (n > maxQueueLen_)
81         maxQueueLen_ = n;
82     return OutputProxy<StatisticsBase>(this, &(i->second));
83 }
84
85 //
86 // generate an engineering style notation 
87 //
88 std::string format_eng( float f)
89 {
90     char buf[16];
91     if (f > 0) {
92         int n = 0;
93         while( f >= 1000.0f) {
94                 f /= 1000.0f;
95                 n+=3;
96         }
97
98         if( n >=3)
99             sprintf( buf, " %3.2fe%+03d", f, n);
100         else
101             sprintf( buf, "      %3.2f", f);
102     }
103     else if (f < 0) {
104         int n = 0;
105         while( f <= -1000.0f) {
106                 f *= 1000.0f;
107                 n+=3;
108         }
109         if( n >=3)
110             sprintf( buf, " %3.2fe%+03d", f, n);
111         else
112             sprintf( buf, "      %3.2f", f);
113     }
114     else{
115         sprintf( buf, "        0.00");
116     }
117
118     return buf;
119 }
120
121
122 prefix_ void senf::StatisticsBase::consoleList(unsigned level, std::ostream & os)
123     const
124 {
125     os << boost::format("%s%-5d%|15t|  %12s  %12s+/-%12s  %12s\n") 
126         % std::string(2*level,' ') 
127         % rank() 
128         % format_eng(min()) 
129         % format_eng(avg()) 
130         % format_eng(dev())
131         % format_eng(max());
132     {
133         OutputMap::const_iterator i (outputs_.begin());
134         OutputMap::const_iterator i_end (outputs_.end());
135         for (; i != i_end; ++i)
136             os << boost::format("            %3d  %12s  %12s+/-%12s  %12s\n")
137                 % i->second.n 
138                 % format_eng(i->second.min/i->second.n) 
139                 % format_eng(i->second.avg/i->second.n)
140                 % format_eng(i->second.dev/i->second.n)
141                 % format_eng(i->second.max/i->second.n);
142     }
143     {
144         Children::const_iterator i (children_.begin());
145         Children::const_iterator const i_end (children_.end());
146         for (; i != i_end; ++i)
147             i->second.consoleList(level+1, os);
148     }
149 }
150
151 prefix_ void senf::StatisticsBase::generateOutput()
152 {
153     queue_.push_front(QueueEntry(min_, avg_, max_, dev_));
154     while (queue_.size() > maxQueueLen_)
155         queue_.pop_back();
156
157     OutputMap::iterator i (outputs_.begin());
158     OutputMap::iterator const i_end (outputs_.end());
159     for (; i != i_end; ++i) {
160         i->second.min = i->second.avg = i->second.max = i->second.dev = 0.0f;
161         Queue::const_iterator j (queue_.begin());
162         Queue::const_iterator const j_end (queue_.end());
163         unsigned n (0);
164         for (; n < i->second.n && j != j_end; ++n, ++j) {
165             i->second.min += j->min;
166             i->second.avg += j->avg;
167             i->second.max += j->max;
168             i->second.dev += j->dev;
169         }
170         i->second.signal(i->second.min/n, i->second.avg/n, i->second.max/n, i->second.dev/n);
171     }
172 }
173
174 prefix_ void senf::StatisticsBase::signalChildren()
175 {
176     Children::iterator i (children_.begin());
177     Children::iterator const i_end  (children_.end());
178     for (; i != i_end; ++i)
179         i->second.enter(min_, avg_, max_, dev_);
180 }
181
182 ///////////////////////////////////////////////////////////////////////////
183 // senf::Statistics
184
185 prefix_ senf::Statistics::Statistics()
186 #ifndef SENF_DISABLE_CONSOLE
187     : dir (this)
188 #endif
189 {
190 #ifndef SENF_DISABLE_CONSOLE
191     dir.add("list", &Statistics::consoleList)
192         .doc("List statistics collection intervals and current values.\n"
193              "\n"
194              "Columns:\n"
195              "    RANK    Number of values collected. Since the statistics collectors form\n"
196              "            a tree, the value is indented according to it's tree location.\n"
197              "    WIN     Size of output average window.\n"
198              "    MIN     Last entered minimum value.\n"
199              "    AVG     Last entered average value.\n"
200              "    DEV     Standard deviation of average value over the collector rank.\n"
201              "    MAX     Last entered maximum value.");
202     dir.add("collect", &Statistics::consoleCollect)
203         .doc("Add statistics collection groups. The argument gives a sequence of collector\n"
204              "ranks each building on the preceding collector:\n"
205              "\n"
206              "    $ collect (10 60 60)\n"
207              "\n"
208              "Will start by collecting every 10 values together to a new value. 60 of such\n"
209              "combined values will be collected together in the next step again followed by\n"
210              "a collection of 60 values. If the statistics is entered with a frequency of\n"
211              "10 values per second, this will provide combined statistics over the second,\n"
212              "minutes and hours ranges.\n"
213              "\n"
214              "You may call collect multiple times. Any missing collection ranks will be\n"
215              "added.")
216         .arg("ranks","chain of collector ranks");
217     dir.add("output", &Statistics::consoleOutput)
218         .doc("Generate statistics output. This statement will add an additional output\n"
219              "generator. This generator will be attached to the collector specified by\n"
220              "the {rank} parameter. This parameter is a chain of successive rank values\n"
221              "which specifies the exact collector to use. If the collector does not\n"
222              "exist, it will be created (this is like automatically calling 'collect'\n"
223              "with {rank} as argument).\n"
224              "\n"
225              "If the output is to be sent somewhere it must be connected to a statistics\n"
226              "target.\n"
227              "\n"
228              "The output may optionally be built using a sliding average over the last\n"
229              "{window} values.\n"
230              "\n"
231              "    $ output ()\n"
232              "\n"
233              "will output the basic statistics value each time a new value is entered.\n"
234              "\n"
235              "    $ output (10 60) 5\n"
236              "\n"
237              "Assuming that new data values are entered 10 times per second, this command\n"
238              "will generate output once every minute. The value will be the average over\n"
239              "the last 5 minutes.")
240         .arg("rank","Rank chain selecting the value to generate output for")
241         .arg("window","Optional size of sliding average window",
242              senf::console::kw::default_value = 1u);
243 #endif
244 }
245
246 prefix_ void senf::Statistics::consoleList(std::ostream & os)
247 {
248     os << "RANK        WIN           MIN           AVG            DEV           MAX\n";
249     StatisticsBase::consoleList(0, os);
250 }
251
252 prefix_ void senf::Statistics::consoleCollect(std::vector<unsigned> & ranks)
253 {
254     StatisticsBase * stats (this);
255     std::vector<unsigned>::const_iterator i (ranks.begin());
256     std::vector<unsigned>::const_iterator const i_end (ranks.end());
257
258     try {
259         for (; i != i_end; ++i)
260             stats = &(*stats)[*i];
261     }
262     catch (InvalidRankException &) {}
263
264     for (; i != i_end; ++i)
265         stats = & (stats->collect(*i));
266         
267 }
268
269 prefix_  boost::shared_ptr<senf::console::DirectoryNode>
270 senf::Statistics::consoleOutput(std::vector<unsigned> & ranks, unsigned window)
271 {
272     StatisticsBase * stats (this);
273     std::vector<unsigned>::const_iterator i (ranks.begin());
274     std::vector<unsigned>::const_iterator const i_end (ranks.end());
275     
276     try {
277         for (; i != i_end; ++i)
278             stats = &(*stats)[*i];
279     }
280     catch (InvalidRankException &) {}
281
282     for (; i != i_end; ++i)
283         stats = & (stats->collect(*i));
284     
285     return stats->output(window).dir().node().thisptr();
286 }
287
288 prefix_ senf::Statistics & senf::Statistics::v_base()
289 {
290     return *this;
291 }
292
293 prefix_ std::string senf::Statistics::v_path()
294     const
295 {
296     return "";
297 }
298
299 ///////////////////////////////////////////////////////////////////////////
300 // senf::Collector
301
302 prefix_ void senf::Collector::enter(float min, float avg, float max, float dev)
303 {
304     accSum_ += avg;
305     accSumSq_ += avg*avg + dev*dev;
306     if (min < accMin_) accMin_ = min;
307     if (max > accMax_) accMax_ = max;
308     if (++i_ >= rank_) {
309         float accAvg (accSum_ / i_);
310         float accDev (std::sqrt(accSumSq_ / i_ - accAvg*accAvg));
311         StatisticsBase::enter(accMin_, accAvg, accMax_, accDev);
312         i_ = 0;
313         accMin_ = FLT_MAX;
314         accSum_ = 0.0f;
315         accSumSq_ = 0.0f;
316         accMax_ = -FLT_MAX;
317     }
318 }
319
320 prefix_ senf::Statistics & senf::Collector::v_base()
321 {
322     return owner_->base();
323 }
324
325 prefix_ std::string senf::Collector::v_path()
326     const
327 {
328     return owner_->path() + "-" + senf::str(rank_);
329 }
330
331 ///////////////////////////////cc.e////////////////////////////////////////
332 #undef prefix_
333 //#include "Statistics.mpp"
334
335 \f
336 // Local Variables:
337 // mode: c++
338 // fill-column: 100
339 // comment-column: 40
340 // c-file-style: "senf"
341 // indent-tabs-mode: nil
342 // ispell-local-dictionary: "american"
343 // compile-command: "scons -u test"
344 // End: