8e25803abb40b137c7091ec97cbe2c25964e8e55
[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 <cstdlib>
32 #include <sstream>
33 #include <senf/Utils/Format.hh>
34 #include <senf/Utils/Console/STLSupport.hh>
35 #include "StatisticsTargets.hh"
36
37 //#include "Statistics.mpp"
38 #define prefix_
39 //-/////////////////////////////////////////////////////////////////////////////////////////////////
40
41 //-/////////////////////////////////////////////////////////////////////////////////////////////////
42 // senf::StatisticsBase
43
44 prefix_ void senf::StatisticsBase::enter(unsigned n, float min, float avg, float max, float dev)
45 {
46     min_ = min;
47     avg_ = avg;
48     max_ = max;
49     dev_ = dev;
50     for (unsigned i (0); i < n; ++i)
51         generateOutput();
52     Children::iterator i (children_.begin());
53     Children::iterator const i_end  (children_.end());
54     for (; i != i_end; ++i)
55         i->second.enter(n, min_, avg_, max_, dev_);
56 }
57
58 prefix_ senf::Collector & senf::StatisticsBase::operator[](unsigned rank)
59 {
60     Children::iterator i (children_.find(rank));
61     if (i == children_.end())
62         throw InvalidRankException();
63     return i->second;
64 }
65
66 prefix_ senf::Collector const & senf::StatisticsBase::operator[](unsigned rank)
67     const
68 {
69     Children::const_iterator i (children_.find(rank));
70     if (i == children_.end())
71         throw InvalidRankException();
72     return i->second;
73 }
74
75 prefix_ senf::Collector & senf::StatisticsBase::collect(unsigned rank)
76 {
77     std::pair<Children::iterator, bool> state (
78         children_.insert(std::make_pair(rank, Collector(this, rank))) );
79     if (! state.second)
80         throw DuplicateRankException();
81     return state.first->second;
82 }
83
84 prefix_ senf::StatisticsBase::OutputProxy<senf::StatisticsBase>
85 senf::StatisticsBase::output(unsigned n)
86 {
87     OutputMap::iterator i (outputs_.find(n));
88     if (i == outputs_.end()) {
89         i = outputs_.insert(std::make_pair(n, OutputEntry(n))).first;
90         std::stringstream nm;
91         nm << "output" << path() << ":" << n;
92         base().dir.node().add(nm.str(), i->second.dir);
93         detail::StatisticsLoggerRegistry::instance().apply(*this, n, i->second.dir);
94     }
95     if (n > maxQueueLen_)
96         maxQueueLen_ = n;
97     return OutputProxy<StatisticsBase>(this, &(i->second));
98 }
99
100 prefix_ void senf::StatisticsBase::consoleList(unsigned level, std::ostream & os)
101     const
102 {
103     namespace fmt = senf::format;
104
105     os << boost::format("%s%-5d%|15t|  %12.5g  %19.5g  %12.5g\n")
106         % std::string(2*level,' ') % rank()
107         % fmt::eng(min()).setw() % fmt::eng(avg(),dev()).setw() % fmt::eng(max()).setw();
108     {
109         OutputMap::const_iterator i (outputs_.begin());
110         OutputMap::const_iterator i_end (outputs_.end());
111         for (; i != i_end; ++i)
112             os << boost::format("            %3d  %12.5g  %19.5g  %12.5g\n")
113                 % i->second.n
114                 % fmt::eng(i->second.min).setw()
115                 % fmt::eng(i->second.avg, i->second.dev).setw()
116                 % fmt::eng(i->second.max).setw();
117     }
118     {
119         Children::const_iterator i (children_.begin());
120         Children::const_iterator const i_end (children_.end());
121         for (; i != i_end; ++i)
122             i->second.consoleList(level+1, os);
123     }
124 }
125
126 prefix_ void senf::StatisticsBase::generateOutput()
127 {
128     queue_.push_front(QueueEntry(min_, avg_, max_, dev_));
129     while (queue_.size() > maxQueueLen_)
130         queue_.pop_back();
131
132     OutputMap::iterator i (outputs_.begin());
133     OutputMap::iterator const i_end (outputs_.end());
134     for (; i != i_end; ++i) {
135         i->second.min = i->second.avg = i->second.max = i->second.dev = 0.0f;
136         Queue::const_iterator j (queue_.begin());
137         Queue::const_iterator const j_end (queue_.end());
138         unsigned n (0);
139         for (; n < i->second.n && j != j_end; ++n, ++j) {
140             i->second.min += j->min;
141             i->second.avg += j->avg;
142             i->second.max += j->max;
143             i->second.dev += j->dev;
144         }
145         i->second.min /= n;
146         i->second.avg /= n;
147         i->second.max /= n;
148         i->second.dev /= n;
149         i->second.signal(i->second.min, i->second.avg, i->second.max, i->second.dev);
150     }
151 }
152
153 //-/////////////////////////////////////////////////////////////////////////////////////////////////
154 // senf::StatisticsBase::OutputEntry
155
156 prefix_ void senf::StatisticsBase::OutputEntry::consoleList(std::ostream & os)
157 {
158     for (boost::ptr_vector<TargetBase>::iterator i (targets_.begin());
159          i != targets_.end(); ++i)
160         if (! i->label.empty())
161             os << i->label << "\n";
162 }
163
164 //-/////////////////////////////////////////////////////////////////////////////////////////////////
165 // senf::Statistics
166
167 prefix_ senf::Statistics::Statistics()
168 #ifndef SENF_DISABLE_CONSOLE
169     : dir (this)
170 #endif
171 {
172 #ifndef SENF_DISABLE_CONSOLE
173     namespace fty = console::factory;
174
175     dir.add("list", fty::Command(&Statistics::consoleList, this)
176             .doc("List statistics collection intervals and current values.\n"
177                  "\n"
178                  "Columns:\n"
179                  "    RANK    Number of values collected. Since the statistics collectors form\n"
180                  "            a tree, the value is indented according to it's tree location.\n"
181                  "    WIN     Size of output average window.\n"
182                  "    MIN     Last entered minimum value.\n"
183                  "    AVG     Last entered average value.\n"
184                  "    DEV     Standard deviation of average value over the collector rank.\n"
185                  "    MAX     Last entered maximum value.") );
186     dir.add("collect", fty::Command(&Statistics::consoleCollect, this)
187             .doc("Add statistics collection groups. The argument gives a sequence of collector\n"
188                  "ranks each building on the preceding collector:\n"
189                  "\n"
190                  "    $ collect (10 60 60)\n"
191                  "\n"
192                  "Will start by collecting every 10 values together to a new value. 60 of such\n"
193                  "combined values will be collected together in the next step again followed by\n"
194                  "a collection of 60 values. If the statistics is entered with a frequency of\n"
195                  "10 values per second, this will provide combined statistics over the second,\n"
196                  "minutes and hours ranges.\n"
197                  "\n"
198                  "You may call collect multiple times. Any missing collection ranks will be\n"
199                  "added.")
200             .arg("ranks","chain of collector ranks") );
201     dir.add("output", fty::Command(&Statistics::consoleOutput, this)
202             .doc("Generate statistics output. This statement will add an additional output\n"
203                  "generator. This generator will be attached to the collector specified by\n"
204                  "the {rank} parameter. This parameter is a chain of successive rank values\n"
205                  "which specifies the exact collector to use. If the collector does not\n"
206                  "exist, it will be created (this is like automatically calling 'collect'\n"
207                  "with {rank} as argument).\n"
208                  "\n"
209                  "If the output is to be sent somewhere it must be connected to a statistics\n"
210                  "target.\n"
211                  "\n"
212                  "The output may optionally be built using a sliding average over the last\n"
213                  "{window} values.\n"
214                  "\n"
215                  "    $ output ()\n"
216                  "\n"
217                  "will output the basic statistics value each time a new value is entered.\n"
218                  "\n"
219                  "    $ output (10 60) 5\n"
220                  "\n"
221                  "Assuming that new data values are entered 10 times per second, this command\n"
222                  "will generate output once every minute. The value will be the average over\n"
223                  "the last 5 minutes.")
224             .arg("rank","Rank chain selecting the value to generate output for")
225             .arg("window","Optional size of sliding average window",
226                  console::kw::default_value = 1u) );
227 #endif
228 }
229
230 prefix_ void senf::Statistics::consoleList(std::ostream & os)
231 {
232     os << "RANK        WIN       MIN          AVG                   MAX\n";
233     StatisticsBase::consoleList(0, os);
234 }
235
236 prefix_ void senf::Statistics::consoleCollect(std::vector<unsigned> & ranks)
237 {
238     StatisticsBase * stats (this);
239     std::vector<unsigned>::const_iterator i (ranks.begin());
240     std::vector<unsigned>::const_iterator const i_end (ranks.end());
241
242     try {
243         for (; i != i_end; ++i)
244             stats = &(*stats)[*i];
245     }
246     catch (InvalidRankException &) {}
247
248     for (; i != i_end; ++i)
249         stats = & (stats->collect(*i));
250
251 }
252
253 prefix_  boost::shared_ptr<senf::console::DirectoryNode>
254 senf::Statistics::consoleOutput(std::vector<unsigned> & ranks, unsigned window)
255 {
256     StatisticsBase * stats (this);
257     std::vector<unsigned>::const_iterator i (ranks.begin());
258     std::vector<unsigned>::const_iterator const i_end (ranks.end());
259
260     try {
261         for (; i != i_end; ++i)
262             stats = &(*stats)[*i];
263     }
264     catch (InvalidRankException &) {}
265
266     for (; i != i_end; ++i)
267         stats = & (stats->collect(*i));
268
269     return stats->output(window).dir().node().thisptr();
270 }
271
272 prefix_ senf::Statistics & senf::Statistics::v_base()
273 {
274     return *this;
275 }
276
277 prefix_ std::string senf::Statistics::v_path()
278     const
279 {
280     return "";
281 }
282
283 //-/////////////////////////////////////////////////////////////////////////////////////////////////
284 // senf::Collector
285
286 prefix_ void senf::Collector::enter(unsigned n, float min, float avg, float max, float dev)
287 {
288     if (min < accMin_) accMin_ = min;
289     if (max > accMax_) accMax_ = max;
290
291     if (i_ + n >= rank_) {
292         accSum_ += (rank_-i_)*avg;
293         accSumSq_ += (rank_-i_)*(rank_-i_)*(avg*avg + dev*dev);
294         float accAvg (accSum_ / rank_);
295         float accDev (std::sqrt(std::max(0.0f,accSumSq_ / rank_ - accAvg*accAvg)));
296         StatisticsBase::enter(1, accMin_, accAvg, accMax_, accDev);
297         accMin_ = FLT_MAX;
298         accSum_ = 0.0f;
299         accSumSq_ = 0.0f;
300         accMax_ = -FLT_MAX;
301         n -= (rank_ - i_);
302         i_ = 0;
303
304         if (n >= rank_) {
305             std::div_t d (std::div(int(n), int(rank_)));
306             StatisticsBase::enter(d.quot, min, avg, max, dev);
307             n = d.rem;
308         }
309     }
310
311     if (n>0) {
312         accSum_ += n*avg;
313         accSumSq_ += n*n*(avg*avg+dev*dev);
314         i_ += n;
315         if (min < accMin_) accMin_ = min;
316         if (max > accMax_) accMax_ = 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 //-/////////////////////////////////////////////////////////////////////////////////////////////////
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: