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