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