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