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