statistics.hh revision 7829:9069448c4fbc
1/*
2 * Copyright (c) 2003-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Nathan Binkert
29 */
30
31/** @file
32 * Declaration of Statistics objects.
33 */
34
35/**
36* @todo
37*
38* Generalized N-dimensinal vector
39* documentation
40* key stats
41* interval stats
42*   -- these both can use the same function that prints out a
43*   specific set of stats
44* VectorStandardDeviation totals
45* Document Namespaces
46*/
47#ifndef __BASE_STATISTICS_HH__
48#define __BASE_STATISTICS_HH__
49
50#include <algorithm>
51#include <cassert>
52#ifdef __SUNPRO_CC
53#include <math.h>
54#endif
55#include <cmath>
56#include <functional>
57#include <iosfwd>
58#include <list>
59#include <string>
60#include <vector>
61
62#include "base/cast.hh"
63#include "base/cprintf.hh"
64#include "base/intmath.hh"
65#include "base/refcnt.hh"
66#include "base/stats/info.hh"
67#include "base/stats/types.hh"
68#include "base/stats/visit.hh"
69#include "base/str.hh"
70#include "base/types.hh"
71
72class Callback;
73
74/** The current simulated tick. */
75extern Tick curTick();
76
77/* A namespace for all of the Statistics */
78namespace Stats {
79
80template <class Stat, class Base>
81class InfoProxy : public Base
82{
83  protected:
84    Stat &s;
85
86  public:
87    InfoProxy(Stat &stat) : s(stat) {}
88
89    bool check() const { return s.check(); }
90    void prepare() { s.prepare(); }
91    void reset() { s.reset(); }
92    void
93    visit(Visit &visitor)
94    {
95        visitor.visit(*static_cast<Base *>(this));
96    }
97    bool zero() const { return s.zero(); }
98};
99
100template <class Stat>
101class ScalarInfoProxy : public InfoProxy<Stat, ScalarInfo>
102{
103  public:
104    ScalarInfoProxy(Stat &stat) : InfoProxy<Stat, ScalarInfo>(stat) {}
105
106    Counter value() const { return this->s.value(); }
107    Result result() const { return this->s.result(); }
108    Result total() const { return this->s.total(); }
109};
110
111template <class Stat>
112class VectorInfoProxy : public InfoProxy<Stat, VectorInfo>
113{
114  protected:
115    mutable VCounter cvec;
116    mutable VResult rvec;
117
118  public:
119    VectorInfoProxy(Stat &stat) : InfoProxy<Stat, VectorInfo>(stat) {}
120
121    size_type size() const { return this->s.size(); }
122
123    VCounter &
124    value() const
125    {
126        this->s.value(cvec);
127        return cvec;
128    }
129
130    const VResult &
131    result() const
132    {
133        this->s.result(rvec);
134        return rvec;
135    }
136
137    Result total() const { return this->s.total(); }
138};
139
140template <class Stat>
141class DistInfoProxy : public InfoProxy<Stat, DistInfo>
142{
143  public:
144    DistInfoProxy(Stat &stat) : InfoProxy<Stat, DistInfo>(stat) {}
145};
146
147template <class Stat>
148class VectorDistInfoProxy : public InfoProxy<Stat, VectorDistInfo>
149{
150  public:
151    VectorDistInfoProxy(Stat &stat) : InfoProxy<Stat, VectorDistInfo>(stat) {}
152
153    size_type size() const { return this->s.size(); }
154};
155
156template <class Stat>
157class Vector2dInfoProxy : public InfoProxy<Stat, Vector2dInfo>
158{
159  public:
160    Vector2dInfoProxy(Stat &stat) : InfoProxy<Stat, Vector2dInfo>(stat) {}
161};
162
163struct StorageParams
164{
165    virtual ~StorageParams();
166};
167
168class InfoAccess
169{
170  protected:
171    /** Set up an info class for this statistic */
172    void setInfo(Info *info);
173    /** Save Storage class parameters if any */
174    void setParams(const StorageParams *params);
175    /** Save Storage class parameters if any */
176    void setInit();
177
178    /** Grab the information class for this statistic */
179    Info *info();
180    /** Grab the information class for this statistic */
181    const Info *info() const;
182
183  public:
184    /**
185     * Reset the stat to the default state.
186     */
187    void reset() { }
188
189    /**
190     * @return true if this stat has a value and satisfies its
191     * requirement as a prereq
192     */
193    bool zero() const { return true; }
194
195    /**
196     * Check that this stat has been set up properly and is ready for
197     * use
198     * @return true for success
199     */
200    bool check() const { return true; }
201};
202
203template <class Derived, template <class> class InfoProxyType>
204class DataWrap : public InfoAccess
205{
206  public:
207    typedef InfoProxyType<Derived> Info;
208
209  protected:
210    Derived &self() { return *static_cast<Derived *>(this); }
211
212  protected:
213    Info *
214    info()
215    {
216        return safe_cast<Info *>(InfoAccess::info());
217    }
218
219  public:
220    const Info *
221    info() const
222    {
223        return safe_cast<const Info *>(InfoAccess::info());
224    }
225
226  protected:
227    /**
228     * Copy constructor, copies are not allowed.
229     */
230    DataWrap(const DataWrap &stat);
231
232    /**
233     * Can't copy stats.
234     */
235    void operator=(const DataWrap &);
236
237  public:
238    DataWrap()
239    {
240        this->setInfo(new Info(self()));
241    }
242
243    /**
244     * Set the name and marks this stat to print at the end of simulation.
245     * @param name The new name.
246     * @return A reference to this stat.
247     */
248    Derived &
249    name(const std::string &name)
250    {
251        Info *info = this->info();
252        info->setName(name);
253        info->flags.set(display);
254        return this->self();
255    }
256    const std::string &name() const { return this->info()->name; }
257
258    /**
259     * Set the description and marks this stat to print at the end of
260     * simulation.
261     * @param desc The new description.
262     * @return A reference to this stat.
263     */
264    Derived &
265    desc(const std::string &_desc)
266    {
267        this->info()->desc = _desc;
268        return this->self();
269    }
270
271    /**
272     * Set the precision and marks this stat to print at the end of simulation.
273     * @param _precision The new precision
274     * @return A reference to this stat.
275     */
276    Derived &
277    precision(int _precision)
278    {
279        this->info()->precision = _precision;
280        return this->self();
281    }
282
283    /**
284     * Set the flags and marks this stat to print at the end of simulation.
285     * @param f The new flags.
286     * @return A reference to this stat.
287     */
288    Derived &
289    flags(Flags _flags)
290    {
291        this->info()->flags.set(_flags);
292        return this->self();
293    }
294
295    /**
296     * Set the prerequisite stat and marks this stat to print at the end of
297     * simulation.
298     * @param prereq The prerequisite stat.
299     * @return A reference to this stat.
300     */
301    template <class Stat>
302    Derived &
303    prereq(const Stat &prereq)
304    {
305        this->info()->prereq = prereq.info();
306        return this->self();
307    }
308};
309
310template <class Derived, template <class> class InfoProxyType>
311class DataWrapVec : public DataWrap<Derived, InfoProxyType>
312{
313  public:
314    typedef InfoProxyType<Derived> Info;
315
316    // The following functions are specific to vectors.  If you use them
317    // in a non vector context, you will get a nice compiler error!
318
319    /**
320     * Set the subfield name for the given index, and marks this stat to print
321     * at the end of simulation.
322     * @param index The subfield index.
323     * @param name The new name of the subfield.
324     * @return A reference to this stat.
325     */
326    Derived &
327    subname(off_type index, const std::string &name)
328    {
329        Derived &self = this->self();
330        Info *info = self.info();
331
332        std::vector<std::string> &subn = info->subnames;
333        if (subn.size() <= index)
334            subn.resize(index + 1);
335        subn[index] = name;
336        return self;
337    }
338
339    // The following functions are specific to 2d vectors.  If you use
340    // them in a non vector context, you will get a nice compiler
341    // error because info doesn't have the right variables.
342
343    /**
344     * Set the subfield description for the given index and marks this stat to
345     * print at the end of simulation.
346     * @param index The subfield index.
347     * @param desc The new description of the subfield
348     * @return A reference to this stat.
349     */
350    Derived &
351    subdesc(off_type index, const std::string &desc)
352    {
353        Info *info = this->info();
354
355        std::vector<std::string> &subd = info->subdescs;
356        if (subd.size() <= index)
357            subd.resize(index + 1);
358        subd[index] = desc;
359
360        return this->self();
361    }
362
363    void
364    prepare()
365    {
366        Derived &self = this->self();
367        Info *info = this->info();
368
369        size_t size = self.size();
370        for (off_type i = 0; i < size; ++i)
371            self.data(i)->prepare(info);
372    }
373
374    void
375    reset()
376    {
377        Derived &self = this->self();
378        Info *info = this->info();
379
380        size_t size = self.size();
381        for (off_type i = 0; i < size; ++i)
382            self.data(i)->reset(info);
383    }
384};
385
386template <class Derived, template <class> class InfoProxyType>
387class DataWrapVec2d : public DataWrapVec<Derived, InfoProxyType>
388{
389  public:
390    typedef InfoProxyType<Derived> Info;
391
392    /**
393     * @warning This makes the assumption that if you're gonna subnames a 2d
394     * vector, you're subnaming across all y
395     */
396    Derived &
397    ysubnames(const char **names)
398    {
399        Derived &self = this->self();
400        Info *info = this->info();
401
402        info->y_subnames.resize(self.y);
403        for (off_type i = 0; i < self.y; ++i)
404            info->y_subnames[i] = names[i];
405        return self;
406    }
407
408    Derived &
409    ysubname(off_type index, const std::string &subname)
410    {
411        Derived &self = this->self();
412        Info *info = this->info();
413
414        assert(index < self.y);
415        info->y_subnames.resize(self.y);
416        info->y_subnames[index] = subname.c_str();
417        return self;
418    }
419
420    std::string
421    ysubname(off_type i) const
422    {
423        return this->info()->y_subnames[i];
424    }
425
426};
427
428//////////////////////////////////////////////////////////////////////
429//
430// Simple Statistics
431//
432//////////////////////////////////////////////////////////////////////
433
434/**
435 * Templatized storage and interface for a simple scalar stat.
436 */
437class StatStor
438{
439  private:
440    /** The statistic value. */
441    Counter data;
442
443  public:
444    struct Params : public StorageParams {};
445
446  public:
447    /**
448     * Builds this storage element and calls the base constructor of the
449     * datatype.
450     */
451    StatStor(Info *info)
452        : data(Counter())
453    { }
454
455    /**
456     * The the stat to the given value.
457     * @param val The new value.
458     */
459    void set(Counter val) { data = val; }
460    /**
461     * Increment the stat by the given value.
462     * @param val The new value.
463     */
464    void inc(Counter val) { data += val; }
465    /**
466     * Decrement the stat by the given value.
467     * @param val The new value.
468     */
469    void dec(Counter val) { data -= val; }
470    /**
471     * Return the value of this stat as its base type.
472     * @return The value of this stat.
473     */
474    Counter value() const { return data; }
475    /**
476     * Return the value of this stat as a result type.
477     * @return The value of this stat.
478     */
479    Result result() const { return (Result)data; }
480    /**
481     * Prepare stat data for dumping or serialization
482     */
483    void prepare(Info *info) { }
484    /**
485     * Reset stat value to default
486     */
487    void reset(Info *info) { data = Counter(); }
488
489    /**
490     * @return true if zero value
491     */
492    bool zero() const { return data == Counter(); }
493};
494
495/**
496 * Templatized storage and interface to a per-tick average stat. This keeps
497 * a current count and updates a total (count * ticks) when this count
498 * changes. This allows the quick calculation of a per tick count of the item
499 * being watched. This is good for keeping track of residencies in structures
500 * among other things.
501 */
502class AvgStor
503{
504  private:
505    /** The current count. */
506    Counter current;
507    /** The tick of the last reset */
508    Tick lastReset;
509    /** The total count for all tick. */
510    mutable Result total;
511    /** The tick that current last changed. */
512    mutable Tick last;
513
514  public:
515    struct Params : public StorageParams {};
516
517  public:
518    /**
519     * Build and initializes this stat storage.
520     */
521    AvgStor(Info *info)
522        : current(0), lastReset(0), total(0), last(0)
523    { }
524
525    /**
526     * Set the current count to the one provided, update the total and last
527     * set values.
528     * @param val The new count.
529     */
530    void
531    set(Counter val)
532    {
533        total += current * (curTick() - last);
534        last = curTick();
535        current = val;
536    }
537
538    /**
539     * Increment the current count by the provided value, calls set.
540     * @param val The amount to increment.
541     */
542    void inc(Counter val) { set(current + val); }
543
544    /**
545     * Deccrement the current count by the provided value, calls set.
546     * @param val The amount to decrement.
547     */
548    void dec(Counter val) { set(current - val); }
549
550    /**
551     * Return the current count.
552     * @return The current count.
553     */
554    Counter value() const { return current; }
555
556    /**
557     * Return the current average.
558     * @return The current average.
559     */
560    Result
561    result() const
562    {
563        assert(last == curTick());
564        return (Result)(total + current) / (Result)(curTick() - lastReset + 1);
565    }
566
567    /**
568     * @return true if zero value
569     */
570    bool zero() const { return total == 0.0; }
571
572    /**
573     * Prepare stat data for dumping or serialization
574     */
575    void
576    prepare(Info *info)
577    {
578        total += current * (curTick() - last);
579        last = curTick();
580    }
581
582    /**
583     * Reset stat value to default
584     */
585    void
586    reset(Info *info)
587    {
588        total = 0.0;
589        last = curTick();
590        lastReset = curTick();
591    }
592
593};
594
595/**
596 * Implementation of a scalar stat. The type of stat is determined by the
597 * Storage template.
598 */
599template <class Derived, class Stor>
600class ScalarBase : public DataWrap<Derived, ScalarInfoProxy>
601{
602  public:
603    typedef Stor Storage;
604    typedef typename Stor::Params Params;
605
606  protected:
607    /** The storage of this stat. */
608    char storage[sizeof(Storage)] __attribute__ ((aligned (8)));
609
610  protected:
611    /**
612     * Retrieve the storage.
613     * @param index The vector index to access.
614     * @return The storage object at the given index.
615     */
616    Storage *
617    data()
618    {
619        return reinterpret_cast<Storage *>(storage);
620    }
621
622    /**
623     * Retrieve a const pointer to the storage.
624     * for the given index.
625     * @param index The vector index to access.
626     * @return A const pointer to the storage object at the given index.
627     */
628    const Storage *
629    data() const
630    {
631        return reinterpret_cast<const Storage *>(storage);
632    }
633
634    void
635    doInit()
636    {
637        new (storage) Storage(this->info());
638        this->setInit();
639    }
640
641  public:
642    /**
643     * Return the current value of this stat as its base type.
644     * @return The current value.
645     */
646    Counter value() const { return data()->value(); }
647
648  public:
649    ScalarBase()
650    {
651        this->doInit();
652    }
653
654  public:
655    // Common operators for stats
656    /**
657     * Increment the stat by 1. This calls the associated storage object inc
658     * function.
659     */
660    void operator++() { data()->inc(1); }
661    /**
662     * Decrement the stat by 1. This calls the associated storage object dec
663     * function.
664     */
665    void operator--() { data()->dec(1); }
666
667    /** Increment the stat by 1. */
668    void operator++(int) { ++*this; }
669    /** Decrement the stat by 1. */
670    void operator--(int) { --*this; }
671
672    /**
673     * Set the data value to the given value. This calls the associated storage
674     * object set function.
675     * @param v The new value.
676     */
677    template <typename U>
678    void operator=(const U &v) { data()->set(v); }
679
680    /**
681     * Increment the stat by the given value. This calls the associated
682     * storage object inc function.
683     * @param v The value to add.
684     */
685    template <typename U>
686    void operator+=(const U &v) { data()->inc(v); }
687
688    /**
689     * Decrement the stat by the given value. This calls the associated
690     * storage object dec function.
691     * @param v The value to substract.
692     */
693    template <typename U>
694    void operator-=(const U &v) { data()->dec(v); }
695
696    /**
697     * Return the number of elements, always 1 for a scalar.
698     * @return 1.
699     */
700    size_type size() const { return 1; }
701
702    Counter value() { return data()->value(); }
703
704    Result result() { return data()->result(); }
705
706    Result total() { return result(); }
707
708    bool zero() { return result() == 0.0; }
709
710    void reset() { data()->reset(this->info()); }
711    void prepare() { data()->prepare(this->info()); }
712};
713
714class ProxyInfo : public ScalarInfo
715{
716  public:
717    std::string str() const { return to_string(value()); }
718    size_type size() const { return 1; }
719    bool check() const { return true; }
720    void prepare() { }
721    void reset() { }
722    bool zero() const { return value() == 0; }
723
724    void visit(Visit &visitor) { visitor.visit(*this); }
725};
726
727template <class T>
728class ValueProxy : public ProxyInfo
729{
730  private:
731    T *scalar;
732
733  public:
734    ValueProxy(T &val) : scalar(&val) {}
735    Counter value() const { return *scalar; }
736    Result result() const { return *scalar; }
737    Result total() const { return *scalar; }
738};
739
740template <class T>
741class FunctorProxy : public ProxyInfo
742{
743  private:
744    T *functor;
745
746  public:
747    FunctorProxy(T &func) : functor(&func) {}
748    Counter value() const { return (*functor)(); }
749    Result result() const { return (*functor)(); }
750    Result total() const { return (*functor)(); }
751};
752
753template <class Derived>
754class ValueBase : public DataWrap<Derived, ScalarInfoProxy>
755{
756  private:
757    ProxyInfo *proxy;
758
759  public:
760    ValueBase() : proxy(NULL) { }
761    ~ValueBase() { if (proxy) delete proxy; }
762
763    template <class T>
764    Derived &
765    scalar(T &value)
766    {
767        proxy = new ValueProxy<T>(value);
768        this->setInit();
769        return this->self();
770    }
771
772    template <class T>
773    Derived &
774    functor(T &func)
775    {
776        proxy = new FunctorProxy<T>(func);
777        this->setInit();
778        return this->self();
779    }
780
781    Counter value() { return proxy->value(); }
782    Result result() const { return proxy->result(); }
783    Result total() const { return proxy->total(); };
784    size_type size() const { return proxy->size(); }
785
786    std::string str() const { return proxy->str(); }
787    bool zero() const { return proxy->zero(); }
788    bool check() const { return proxy != NULL; }
789    void prepare() { }
790    void reset() { }
791};
792
793//////////////////////////////////////////////////////////////////////
794//
795// Vector Statistics
796//
797//////////////////////////////////////////////////////////////////////
798
799/**
800 * A proxy class to access the stat at a given index in a VectorBase stat.
801 * Behaves like a ScalarBase.
802 */
803template <class Stat>
804class ScalarProxy
805{
806  private:
807    /** Pointer to the parent Vector. */
808    Stat &stat;
809
810    /** The index to access in the parent VectorBase. */
811    off_type index;
812
813  public:
814    /**
815     * Return the current value of this stat as its base type.
816     * @return The current value.
817     */
818    Counter value() const { return stat.data(index)->value(); }
819
820    /**
821     * Return the current value of this statas a result type.
822     * @return The current value.
823     */
824    Result result() const { return stat.data(index)->result(); }
825
826  public:
827    /**
828     * Create and initialize this proxy, do not register it with the database.
829     * @param i The index to access.
830     */
831    ScalarProxy(Stat &s, off_type i)
832        : stat(s), index(i)
833    {
834    }
835
836    /**
837     * Create a copy of the provided ScalarProxy.
838     * @param sp The proxy to copy.
839     */
840    ScalarProxy(const ScalarProxy &sp)
841        : stat(sp.stat), index(sp.index)
842    {}
843
844    /**
845     * Set this proxy equal to the provided one.
846     * @param sp The proxy to copy.
847     * @return A reference to this proxy.
848     */
849    const ScalarProxy &
850    operator=(const ScalarProxy &sp)
851    {
852        stat = sp.stat;
853        index = sp.index;
854        return *this;
855    }
856
857  public:
858    // Common operators for stats
859    /**
860     * Increment the stat by 1. This calls the associated storage object inc
861     * function.
862     */
863    void operator++() { stat.data(index)->inc(1); }
864    /**
865     * Decrement the stat by 1. This calls the associated storage object dec
866     * function.
867     */
868    void operator--() { stat.data(index)->dec(1); }
869
870    /** Increment the stat by 1. */
871    void operator++(int) { ++*this; }
872    /** Decrement the stat by 1. */
873    void operator--(int) { --*this; }
874
875    /**
876     * Set the data value to the given value. This calls the associated storage
877     * object set function.
878     * @param v The new value.
879     */
880    template <typename U>
881    void
882    operator=(const U &v)
883    {
884        stat.data(index)->set(v);
885    }
886
887    /**
888     * Increment the stat by the given value. This calls the associated
889     * storage object inc function.
890     * @param v The value to add.
891     */
892    template <typename U>
893    void
894    operator+=(const U &v)
895    {
896        stat.data(index)->inc(v);
897    }
898
899    /**
900     * Decrement the stat by the given value. This calls the associated
901     * storage object dec function.
902     * @param v The value to substract.
903     */
904    template <typename U>
905    void
906    operator-=(const U &v)
907    {
908        stat.data(index)->dec(v);
909    }
910
911    /**
912     * Return the number of elements, always 1 for a scalar.
913     * @return 1.
914     */
915    size_type size() const { return 1; }
916
917  public:
918    std::string
919    str() const
920    {
921        return csprintf("%s[%d]", stat.info()->name, index);
922    }
923};
924
925/**
926 * Implementation of a vector of stats. The type of stat is determined by the
927 * Storage class. @sa ScalarBase
928 */
929template <class Derived, class Stor>
930class VectorBase : public DataWrapVec<Derived, VectorInfoProxy>
931{
932  public:
933    typedef Stor Storage;
934    typedef typename Stor::Params Params;
935
936    /** Proxy type */
937    typedef ScalarProxy<Derived> Proxy;
938    friend class ScalarProxy<Derived>;
939    friend class DataWrapVec<Derived, VectorInfoProxy>;
940
941  protected:
942    /** The storage of this stat. */
943    Storage *storage;
944    size_type _size;
945
946  protected:
947    /**
948     * Retrieve the storage.
949     * @param index The vector index to access.
950     * @return The storage object at the given index.
951     */
952    Storage *data(off_type index) { return &storage[index]; }
953
954    /**
955     * Retrieve a const pointer to the storage.
956     * @param index The vector index to access.
957     * @return A const pointer to the storage object at the given index.
958     */
959    const Storage *data(off_type index) const { return &storage[index]; }
960
961    void
962    doInit(size_type s)
963    {
964        assert(s > 0 && "size must be positive!");
965        assert(!storage && "already initialized");
966        _size = s;
967
968        char *ptr = new char[_size * sizeof(Storage)];
969        storage = reinterpret_cast<Storage *>(ptr);
970
971        for (off_type i = 0; i < _size; ++i)
972            new (&storage[i]) Storage(this->info());
973
974        this->setInit();
975    }
976
977  public:
978    void
979    value(VCounter &vec) const
980    {
981        vec.resize(size());
982        for (off_type i = 0; i < size(); ++i)
983            vec[i] = data(i)->value();
984    }
985
986    /**
987     * Copy the values to a local vector and return a reference to it.
988     * @return A reference to a vector of the stat values.
989     */
990    void
991    result(VResult &vec) const
992    {
993        vec.resize(size());
994        for (off_type i = 0; i < size(); ++i)
995            vec[i] = data(i)->result();
996    }
997
998    /**
999     * Return a total of all entries in this vector.
1000     * @return The total of all vector entries.
1001     */
1002    Result
1003    total() const
1004    {
1005        Result total = 0.0;
1006        for (off_type i = 0; i < size(); ++i)
1007            total += data(i)->result();
1008        return total;
1009    }
1010
1011    /**
1012     * @return the number of elements in this vector.
1013     */
1014    size_type size() const { return _size; }
1015
1016    bool
1017    zero() const
1018    {
1019        for (off_type i = 0; i < size(); ++i)
1020            if (data(i)->zero())
1021                return false;
1022        return true;
1023    }
1024
1025    bool
1026    check() const
1027    {
1028        return storage != NULL;
1029    }
1030
1031  public:
1032    VectorBase()
1033        : storage(NULL)
1034    {}
1035
1036    ~VectorBase()
1037    {
1038        if (!storage)
1039            return;
1040
1041        for (off_type i = 0; i < _size; ++i)
1042            data(i)->~Storage();
1043        delete [] reinterpret_cast<char *>(storage);
1044    }
1045
1046    /**
1047     * Set this vector to have the given size.
1048     * @param size The new size.
1049     * @return A reference to this stat.
1050     */
1051    Derived &
1052    init(size_type size)
1053    {
1054        Derived &self = this->self();
1055        self.doInit(size);
1056        return self;
1057    }
1058
1059    /**
1060     * Return a reference (ScalarProxy) to the stat at the given index.
1061     * @param index The vector index to access.
1062     * @return A reference of the stat.
1063     */
1064    Proxy
1065    operator[](off_type index)
1066    {
1067        assert (index >= 0 && index < size());
1068        return Proxy(this->self(), index);
1069    }
1070};
1071
1072template <class Stat>
1073class VectorProxy
1074{
1075  private:
1076    Stat &stat;
1077    off_type offset;
1078    size_type len;
1079
1080  private:
1081    mutable VResult vec;
1082
1083    typename Stat::Storage *
1084    data(off_type index)
1085    {
1086        assert(index < len);
1087        return stat.data(offset + index);
1088    }
1089
1090    const typename Stat::Storage *
1091    data(off_type index) const
1092    {
1093        assert(index < len);
1094        return stat.data(offset + index);
1095    }
1096
1097  public:
1098    const VResult &
1099    result() const
1100    {
1101        vec.resize(size());
1102
1103        for (off_type i = 0; i < size(); ++i)
1104            vec[i] = data(i)->result();
1105
1106        return vec;
1107    }
1108
1109    Result
1110    total() const
1111    {
1112        Result total = 0.0;
1113        for (off_type i = 0; i < size(); ++i)
1114            total += data(i)->result();
1115        return total;
1116    }
1117
1118  public:
1119    VectorProxy(Stat &s, off_type o, size_type l)
1120        : stat(s), offset(o), len(l)
1121    {
1122    }
1123
1124    VectorProxy(const VectorProxy &sp)
1125        : stat(sp.stat), offset(sp.offset), len(sp.len)
1126    {
1127    }
1128
1129    const VectorProxy &
1130    operator=(const VectorProxy &sp)
1131    {
1132        stat = sp.stat;
1133        offset = sp.offset;
1134        len = sp.len;
1135        return *this;
1136    }
1137
1138    ScalarProxy<Stat>
1139    operator[](off_type index)
1140    {
1141        assert (index >= 0 && index < size());
1142        return ScalarProxy<Stat>(stat, offset + index);
1143    }
1144
1145    size_type size() const { return len; }
1146};
1147
1148template <class Derived, class Stor>
1149class Vector2dBase : public DataWrapVec2d<Derived, Vector2dInfoProxy>
1150{
1151  public:
1152    typedef Vector2dInfoProxy<Derived> Info;
1153    typedef Stor Storage;
1154    typedef typename Stor::Params Params;
1155    typedef VectorProxy<Derived> Proxy;
1156    friend class ScalarProxy<Derived>;
1157    friend class VectorProxy<Derived>;
1158    friend class DataWrapVec<Derived, Vector2dInfoProxy>;
1159    friend class DataWrapVec2d<Derived, Vector2dInfoProxy>;
1160
1161  protected:
1162    size_type x;
1163    size_type y;
1164    size_type _size;
1165    Storage *storage;
1166
1167  protected:
1168    Storage *data(off_type index) { return &storage[index]; }
1169    const Storage *data(off_type index) const { return &storage[index]; }
1170
1171  public:
1172    Vector2dBase()
1173        : storage(NULL)
1174    {}
1175
1176    ~Vector2dBase()
1177    {
1178        if (!storage)
1179            return;
1180
1181        for (off_type i = 0; i < _size; ++i)
1182            data(i)->~Storage();
1183        delete [] reinterpret_cast<char *>(storage);
1184    }
1185
1186    Derived &
1187    init(size_type _x, size_type _y)
1188    {
1189        assert(_x > 0 && _y > 0 && "sizes must be positive!");
1190        assert(!storage && "already initialized");
1191
1192        Derived &self = this->self();
1193        Info *info = this->info();
1194
1195        x = _x;
1196        y = _y;
1197        info->x = _x;
1198        info->y = _y;
1199        _size = x * y;
1200
1201        char *ptr = new char[_size * sizeof(Storage)];
1202        storage = reinterpret_cast<Storage *>(ptr);
1203
1204        for (off_type i = 0; i < _size; ++i)
1205            new (&storage[i]) Storage(info);
1206
1207        this->setInit();
1208
1209        return self;
1210    }
1211
1212    Proxy
1213    operator[](off_type index)
1214    {
1215        off_type offset = index * y;
1216        assert (index >= 0 && offset + index < size());
1217        return Proxy(this->self(), offset, y);
1218    }
1219
1220
1221    size_type
1222    size() const
1223    {
1224        return _size;
1225    }
1226
1227    bool
1228    zero() const
1229    {
1230        return data(0)->zero();
1231#if 0
1232        for (off_type i = 0; i < size(); ++i)
1233            if (!data(i)->zero())
1234                return false;
1235        return true;
1236#endif
1237    }
1238
1239    void
1240    prepare()
1241    {
1242        Info *info = this->info();
1243        size_type size = this->size();
1244
1245        for (off_type i = 0; i < size; ++i)
1246            data(i)->prepare(info);
1247
1248        info->cvec.resize(size);
1249        for (off_type i = 0; i < size; ++i)
1250            info->cvec[i] = data(i)->value();
1251    }
1252
1253    /**
1254     * Reset stat value to default
1255     */
1256    void
1257    reset()
1258    {
1259        Info *info = this->info();
1260        size_type size = this->size();
1261        for (off_type i = 0; i < size; ++i)
1262            data(i)->reset(info);
1263    }
1264
1265    bool
1266    check() const
1267    {
1268        return storage != NULL;
1269    }
1270};
1271
1272//////////////////////////////////////////////////////////////////////
1273//
1274// Non formula statistics
1275//
1276//////////////////////////////////////////////////////////////////////
1277/** The parameters for a distribution stat. */
1278struct DistParams : public StorageParams
1279{
1280    const DistType type;
1281    DistParams(DistType t) : type(t) {}
1282};
1283
1284/**
1285 * Templatized storage and interface for a distrbution stat.
1286 */
1287class DistStor
1288{
1289  public:
1290    /** The parameters for a distribution stat. */
1291    struct Params : public DistParams
1292    {
1293        /** The minimum value to track. */
1294        Counter min;
1295        /** The maximum value to track. */
1296        Counter max;
1297        /** The number of entries in each bucket. */
1298        Counter bucket_size;
1299        /** The number of buckets. Equal to (max-min)/bucket_size. */
1300        size_type buckets;
1301
1302        Params() : DistParams(Dist) {}
1303    };
1304
1305  private:
1306    /** The minimum value to track. */
1307    Counter min_track;
1308    /** The maximum value to track. */
1309    Counter max_track;
1310    /** The number of entries in each bucket. */
1311    Counter bucket_size;
1312    /** The number of buckets. Equal to (max-min)/bucket_size. */
1313    size_type buckets;
1314
1315    /** The smallest value sampled. */
1316    Counter min_val;
1317    /** The largest value sampled. */
1318    Counter max_val;
1319    /** The number of values sampled less than min. */
1320    Counter underflow;
1321    /** The number of values sampled more than max. */
1322    Counter overflow;
1323    /** The current sum. */
1324    Counter sum;
1325    /** The sum of squares. */
1326    Counter squares;
1327    /** The number of samples. */
1328    Counter samples;
1329    /** Counter for each bucket. */
1330    VCounter cvec;
1331
1332  public:
1333    DistStor(Info *info)
1334        : cvec(safe_cast<const Params *>(info->storageParams)->buckets)
1335    {
1336        reset(info);
1337    }
1338
1339    /**
1340     * Add a value to the distribution for the given number of times.
1341     * @param val The value to add.
1342     * @param number The number of times to add the value.
1343     */
1344    void
1345    sample(Counter val, int number)
1346    {
1347        if (val < min_track)
1348            underflow += number;
1349        else if (val > max_track)
1350            overflow += number;
1351        else {
1352            size_type index =
1353                (size_type)std::floor((val - min_track) / bucket_size);
1354            assert(index < size());
1355            cvec[index] += number;
1356        }
1357
1358        if (val < min_val)
1359            min_val = val;
1360
1361        if (val > max_val)
1362            max_val = val;
1363
1364        sum += val * number;
1365        squares += val * val * number;
1366        samples += number;
1367    }
1368
1369    /**
1370     * Return the number of buckets in this distribution.
1371     * @return the number of buckets.
1372     */
1373    size_type size() const { return cvec.size(); }
1374
1375    /**
1376     * Returns true if any calls to sample have been made.
1377     * @return True if any values have been sampled.
1378     */
1379    bool
1380    zero() const
1381    {
1382        return samples == Counter();
1383    }
1384
1385    void
1386    prepare(Info *info, DistData &data)
1387    {
1388        const Params *params = safe_cast<const Params *>(info->storageParams);
1389
1390        assert(params->type == Dist);
1391        data.type = params->type;
1392        data.min = params->min;
1393        data.max = params->max;
1394        data.bucket_size = params->bucket_size;
1395
1396        data.min_val = (min_val == CounterLimits::max()) ? 0 : min_val;
1397        data.max_val = (max_val == CounterLimits::min()) ? 0 : max_val;
1398        data.underflow = underflow;
1399        data.overflow = overflow;
1400
1401        size_type buckets = params->buckets;
1402        data.cvec.resize(buckets);
1403        for (off_type i = 0; i < buckets; ++i)
1404            data.cvec[i] = cvec[i];
1405
1406        data.sum = sum;
1407        data.squares = squares;
1408        data.samples = samples;
1409    }
1410
1411    /**
1412     * Reset stat value to default
1413     */
1414    void
1415    reset(Info *info)
1416    {
1417        const Params *params = safe_cast<const Params *>(info->storageParams);
1418        min_track = params->min;
1419        max_track = params->max;
1420        bucket_size = params->bucket_size;
1421
1422        min_val = CounterLimits::max();
1423        max_val = CounterLimits::min();
1424        underflow = Counter();
1425        overflow = Counter();
1426
1427        size_type size = cvec.size();
1428        for (off_type i = 0; i < size; ++i)
1429            cvec[i] = Counter();
1430
1431        sum = Counter();
1432        squares = Counter();
1433        samples = Counter();
1434    }
1435};
1436
1437/**
1438 * Templatized storage and interface for a distribution that calculates mean
1439 * and variance.
1440 */
1441class SampleStor
1442{
1443  public:
1444    struct Params : public DistParams
1445    {
1446        Params() : DistParams(Deviation) {}
1447    };
1448
1449  private:
1450    /** The current sum. */
1451    Counter sum;
1452    /** The sum of squares. */
1453    Counter squares;
1454    /** The number of samples. */
1455    Counter samples;
1456
1457  public:
1458    /**
1459     * Create and initialize this storage.
1460     */
1461    SampleStor(Info *info)
1462        : sum(Counter()), squares(Counter()), samples(Counter())
1463    { }
1464
1465    /**
1466     * Add a value the given number of times to this running average.
1467     * Update the running sum and sum of squares, increment the number of
1468     * values seen by the given number.
1469     * @param val The value to add.
1470     * @param number The number of times to add the value.
1471     */
1472    void
1473    sample(Counter val, int number)
1474    {
1475        Counter value = val * number;
1476        sum += value;
1477        squares += value * value;
1478        samples += number;
1479    }
1480
1481    /**
1482     * Return the number of entries in this stat, 1
1483     * @return 1.
1484     */
1485    size_type size() const { return 1; }
1486
1487    /**
1488     * Return true if no samples have been added.
1489     * @return True if no samples have been added.
1490     */
1491    bool zero() const { return samples == Counter(); }
1492
1493    void
1494    prepare(Info *info, DistData &data)
1495    {
1496        const Params *params = safe_cast<const Params *>(info->storageParams);
1497
1498        assert(params->type == Deviation);
1499        data.type = params->type;
1500        data.sum = sum;
1501        data.squares = squares;
1502        data.samples = samples;
1503    }
1504
1505    /**
1506     * Reset stat value to default
1507     */
1508    void
1509    reset(Info *info)
1510    {
1511        sum = Counter();
1512        squares = Counter();
1513        samples = Counter();
1514    }
1515};
1516
1517/**
1518 * Templatized storage for distribution that calculates per tick mean and
1519 * variance.
1520 */
1521class AvgSampleStor
1522{
1523  public:
1524    struct Params : public DistParams
1525    {
1526        Params() : DistParams(Deviation) {}
1527    };
1528
1529  private:
1530    /** Current total. */
1531    Counter sum;
1532    /** Current sum of squares. */
1533    Counter squares;
1534
1535  public:
1536    /**
1537     * Create and initialize this storage.
1538     */
1539    AvgSampleStor(Info *info)
1540        : sum(Counter()), squares(Counter())
1541    {}
1542
1543    /**
1544     * Add a value to the distribution for the given number of times.
1545     * Update the running sum and sum of squares.
1546     * @param val The value to add.
1547     * @param number The number of times to add the value.
1548     */
1549    void
1550    sample(Counter val, int number)
1551    {
1552        Counter value = val * number;
1553        sum += value;
1554        squares += value * value;
1555    }
1556
1557    /**
1558     * Return the number of entries, in this case 1.
1559     * @return 1.
1560     */
1561    size_type size() const { return 1; }
1562
1563    /**
1564     * Return true if no samples have been added.
1565     * @return True if the sum is zero.
1566     */
1567    bool zero() const { return sum == Counter(); }
1568
1569    void
1570    prepare(Info *info, DistData &data)
1571    {
1572        const Params *params = safe_cast<const Params *>(info->storageParams);
1573
1574        assert(params->type == Deviation);
1575        data.type = params->type;
1576        data.sum = sum;
1577        data.squares = squares;
1578        data.samples = curTick();
1579    }
1580
1581    /**
1582     * Reset stat value to default
1583     */
1584    void
1585    reset(Info *info)
1586    {
1587        sum = Counter();
1588        squares = Counter();
1589    }
1590};
1591
1592/**
1593 * Implementation of a distribution stat. The type of distribution is
1594 * determined by the Storage template. @sa ScalarBase
1595 */
1596template <class Derived, class Stor>
1597class DistBase : public DataWrap<Derived, DistInfoProxy>
1598{
1599  public:
1600    typedef DistInfoProxy<Derived> Info;
1601    typedef Stor Storage;
1602    typedef typename Stor::Params Params;
1603
1604  protected:
1605    /** The storage for this stat. */
1606    char storage[sizeof(Storage)] __attribute__ ((aligned (8)));
1607
1608  protected:
1609    /**
1610     * Retrieve the storage.
1611     * @return The storage object for this stat.
1612     */
1613    Storage *
1614    data()
1615    {
1616        return reinterpret_cast<Storage *>(storage);
1617    }
1618
1619    /**
1620     * Retrieve a const pointer to the storage.
1621     * @return A const pointer to the storage object for this stat.
1622     */
1623    const Storage *
1624    data() const
1625    {
1626        return reinterpret_cast<const Storage *>(storage);
1627    }
1628
1629    void
1630    doInit()
1631    {
1632        new (storage) Storage(this->info());
1633        this->setInit();
1634    }
1635
1636  public:
1637    DistBase() { }
1638
1639    /**
1640     * Add a value to the distribtion n times. Calls sample on the storage
1641     * class.
1642     * @param v The value to add.
1643     * @param n The number of times to add it, defaults to 1.
1644     */
1645    template <typename U>
1646    void sample(const U &v, int n = 1) { data()->sample(v, n); }
1647
1648    /**
1649     * Return the number of entries in this stat.
1650     * @return The number of entries.
1651     */
1652    size_type size() const { return data()->size(); }
1653    /**
1654     * Return true if no samples have been added.
1655     * @return True if there haven't been any samples.
1656     */
1657    bool zero() const { return data()->zero(); }
1658
1659    void
1660    prepare()
1661    {
1662        Info *info = this->info();
1663        data()->prepare(info, info->data);
1664    }
1665
1666    /**
1667     * Reset stat value to default
1668     */
1669    void
1670    reset()
1671    {
1672        data()->reset(this->info());
1673    }
1674};
1675
1676template <class Stat>
1677class DistProxy;
1678
1679template <class Derived, class Stor>
1680class VectorDistBase : public DataWrapVec<Derived, VectorDistInfoProxy>
1681{
1682  public:
1683    typedef VectorDistInfoProxy<Derived> Info;
1684    typedef Stor Storage;
1685    typedef typename Stor::Params Params;
1686    typedef DistProxy<Derived> Proxy;
1687    friend class DistProxy<Derived>;
1688    friend class DataWrapVec<Derived, VectorDistInfoProxy>;
1689
1690  protected:
1691    Storage *storage;
1692    size_type _size;
1693
1694  protected:
1695    Storage *
1696    data(off_type index)
1697    {
1698        return &storage[index];
1699    }
1700
1701    const Storage *
1702    data(off_type index) const
1703    {
1704        return &storage[index];
1705    }
1706
1707    void
1708    doInit(size_type s)
1709    {
1710        assert(s > 0 && "size must be positive!");
1711        assert(!storage && "already initialized");
1712        _size = s;
1713
1714        char *ptr = new char[_size * sizeof(Storage)];
1715        storage = reinterpret_cast<Storage *>(ptr);
1716
1717        Info *info = this->info();
1718        for (off_type i = 0; i < _size; ++i)
1719            new (&storage[i]) Storage(info);
1720
1721        this->setInit();
1722    }
1723
1724  public:
1725    VectorDistBase()
1726        : storage(NULL)
1727    {}
1728
1729    ~VectorDistBase()
1730    {
1731        if (!storage)
1732            return ;
1733
1734        for (off_type i = 0; i < _size; ++i)
1735            data(i)->~Storage();
1736        delete [] reinterpret_cast<char *>(storage);
1737    }
1738
1739    Proxy operator[](off_type index)
1740    {
1741        assert(index >= 0 && index < size());
1742        return Proxy(this->self(), index);
1743    }
1744
1745    size_type
1746    size() const
1747    {
1748        return _size;
1749    }
1750
1751    bool
1752    zero() const
1753    {
1754        for (off_type i = 0; i < size(); ++i)
1755            if (!data(i)->zero())
1756                return false;
1757        return true;
1758    }
1759
1760    void
1761    prepare()
1762    {
1763        Info *info = this->info();
1764        size_type size = this->size();
1765        info->data.resize(size);
1766        for (off_type i = 0; i < size; ++i)
1767            data(i)->prepare(info, info->data[i]);
1768    }
1769
1770    bool
1771    check() const
1772    {
1773        return storage != NULL;
1774    }
1775};
1776
1777template <class Stat>
1778class DistProxy
1779{
1780  private:
1781    Stat &stat;
1782    off_type index;
1783
1784  protected:
1785    typename Stat::Storage *data() { return stat.data(index); }
1786    const typename Stat::Storage *data() const { return stat.data(index); }
1787
1788  public:
1789    DistProxy(Stat &s, off_type i)
1790        : stat(s), index(i)
1791    {}
1792
1793    DistProxy(const DistProxy &sp)
1794        : stat(sp.stat), index(sp.index)
1795    {}
1796
1797    const DistProxy &
1798    operator=(const DistProxy &sp)
1799    {
1800        stat = sp.stat;
1801        index = sp.index;
1802        return *this;
1803    }
1804
1805  public:
1806    template <typename U>
1807    void
1808    sample(const U &v, int n = 1)
1809    {
1810        data()->sample(v, n);
1811    }
1812
1813    size_type
1814    size() const
1815    {
1816        return 1;
1817    }
1818
1819    bool
1820    zero() const
1821    {
1822        return data()->zero();
1823    }
1824
1825    /**
1826     * Proxy has no state.  Nothing to reset.
1827     */
1828    void reset() { }
1829};
1830
1831//////////////////////////////////////////////////////////////////////
1832//
1833//  Formula Details
1834//
1835//////////////////////////////////////////////////////////////////////
1836
1837/**
1838 * Base class for formula statistic node. These nodes are used to build a tree
1839 * that represents the formula.
1840 */
1841class Node : public RefCounted
1842{
1843  public:
1844    /**
1845     * Return the number of nodes in the subtree starting at this node.
1846     * @return the number of nodes in this subtree.
1847     */
1848    virtual size_type size() const = 0;
1849    /**
1850     * Return the result vector of this subtree.
1851     * @return The result vector of this subtree.
1852     */
1853    virtual const VResult &result() const = 0;
1854    /**
1855     * Return the total of the result vector.
1856     * @return The total of the result vector.
1857     */
1858    virtual Result total() const = 0;
1859
1860    /**
1861     *
1862     */
1863    virtual std::string str() const = 0;
1864};
1865
1866/** Reference counting pointer to a function Node. */
1867typedef RefCountingPtr<Node> NodePtr;
1868
1869class ScalarStatNode : public Node
1870{
1871  private:
1872    const ScalarInfo *data;
1873    mutable VResult vresult;
1874
1875  public:
1876    ScalarStatNode(const ScalarInfo *d) : data(d), vresult(1) {}
1877
1878    const VResult &
1879    result() const
1880    {
1881        vresult[0] = data->result();
1882        return vresult;
1883    }
1884
1885    Result total() const { return data->result(); };
1886
1887    size_type size() const { return 1; }
1888
1889    /**
1890     *
1891     */
1892    std::string str() const { return data->name; }
1893};
1894
1895template <class Stat>
1896class ScalarProxyNode : public Node
1897{
1898  private:
1899    const ScalarProxy<Stat> proxy;
1900    mutable VResult vresult;
1901
1902  public:
1903    ScalarProxyNode(const ScalarProxy<Stat> &p)
1904        : proxy(p), vresult(1)
1905    { }
1906
1907    const VResult &
1908    result() const
1909    {
1910        vresult[0] = proxy.result();
1911        return vresult;
1912    }
1913
1914    Result
1915    total() const
1916    {
1917        return proxy.result();
1918    }
1919
1920    size_type
1921    size() const
1922    {
1923        return 1;
1924    }
1925
1926    /**
1927     *
1928     */
1929    std::string
1930    str() const
1931    {
1932        return proxy.str();
1933    }
1934};
1935
1936class VectorStatNode : public Node
1937{
1938  private:
1939    const VectorInfo *data;
1940
1941  public:
1942    VectorStatNode(const VectorInfo *d) : data(d) { }
1943    const VResult &result() const { return data->result(); }
1944    Result total() const { return data->total(); };
1945
1946    size_type size() const { return data->size(); }
1947
1948    std::string str() const { return data->name; }
1949};
1950
1951template <class T>
1952class ConstNode : public Node
1953{
1954  private:
1955    VResult vresult;
1956
1957  public:
1958    ConstNode(T s) : vresult(1, (Result)s) {}
1959    const VResult &result() const { return vresult; }
1960    Result total() const { return vresult[0]; };
1961    size_type size() const { return 1; }
1962    std::string str() const { return to_string(vresult[0]); }
1963};
1964
1965template <class T>
1966class ConstVectorNode : public Node
1967{
1968  private:
1969    VResult vresult;
1970
1971  public:
1972    ConstVectorNode(const T &s) : vresult(s.begin(), s.end()) {}
1973    const VResult &result() const { return vresult; }
1974
1975    Result
1976    total() const
1977    {
1978        size_type size = this->size();
1979        Result tmp = 0;
1980        for (off_type i = 0; i < size; i++)
1981            tmp += vresult[i];
1982        return tmp;
1983    }
1984
1985    size_type size() const { return vresult.size(); }
1986    std::string
1987    str() const
1988    {
1989        size_type size = this->size();
1990        std::string tmp = "(";
1991        for (off_type i = 0; i < size; i++)
1992            tmp += csprintf("%s ",to_string(vresult[i]));
1993        tmp += ")";
1994        return tmp;
1995    }
1996};
1997
1998template <class Op>
1999struct OpString;
2000
2001template<>
2002struct OpString<std::plus<Result> >
2003{
2004    static std::string str() { return "+"; }
2005};
2006
2007template<>
2008struct OpString<std::minus<Result> >
2009{
2010    static std::string str() { return "-"; }
2011};
2012
2013template<>
2014struct OpString<std::multiplies<Result> >
2015{
2016    static std::string str() { return "*"; }
2017};
2018
2019template<>
2020struct OpString<std::divides<Result> >
2021{
2022    static std::string str() { return "/"; }
2023};
2024
2025template<>
2026struct OpString<std::modulus<Result> >
2027{
2028    static std::string str() { return "%"; }
2029};
2030
2031template<>
2032struct OpString<std::negate<Result> >
2033{
2034    static std::string str() { return "-"; }
2035};
2036
2037template <class Op>
2038class UnaryNode : public Node
2039{
2040  public:
2041    NodePtr l;
2042    mutable VResult vresult;
2043
2044  public:
2045    UnaryNode(NodePtr &p) : l(p) {}
2046
2047    const VResult &
2048    result() const
2049    {
2050        const VResult &lvec = l->result();
2051        size_type size = lvec.size();
2052
2053        assert(size > 0);
2054
2055        vresult.resize(size);
2056        Op op;
2057        for (off_type i = 0; i < size; ++i)
2058            vresult[i] = op(lvec[i]);
2059
2060        return vresult;
2061    }
2062
2063    Result
2064    total() const
2065    {
2066        const VResult &vec = this->result();
2067        Result total = 0.0;
2068        for (off_type i = 0; i < size(); i++)
2069            total += vec[i];
2070        return total;
2071    }
2072
2073    size_type size() const { return l->size(); }
2074
2075    std::string
2076    str() const
2077    {
2078        return OpString<Op>::str() + l->str();
2079    }
2080};
2081
2082template <class Op>
2083class BinaryNode : public Node
2084{
2085  public:
2086    NodePtr l;
2087    NodePtr r;
2088    mutable VResult vresult;
2089
2090  public:
2091    BinaryNode(NodePtr &a, NodePtr &b) : l(a), r(b) {}
2092
2093    const VResult &
2094    result() const
2095    {
2096        Op op;
2097        const VResult &lvec = l->result();
2098        const VResult &rvec = r->result();
2099
2100        assert(lvec.size() > 0 && rvec.size() > 0);
2101
2102        if (lvec.size() == 1 && rvec.size() == 1) {
2103            vresult.resize(1);
2104            vresult[0] = op(lvec[0], rvec[0]);
2105        } else if (lvec.size() == 1) {
2106            size_type size = rvec.size();
2107            vresult.resize(size);
2108            for (off_type i = 0; i < size; ++i)
2109                vresult[i] = op(lvec[0], rvec[i]);
2110        } else if (rvec.size() == 1) {
2111            size_type size = lvec.size();
2112            vresult.resize(size);
2113            for (off_type i = 0; i < size; ++i)
2114                vresult[i] = op(lvec[i], rvec[0]);
2115        } else if (rvec.size() == lvec.size()) {
2116            size_type size = rvec.size();
2117            vresult.resize(size);
2118            for (off_type i = 0; i < size; ++i)
2119                vresult[i] = op(lvec[i], rvec[i]);
2120        }
2121
2122        return vresult;
2123    }
2124
2125    Result
2126    total() const
2127    {
2128        const VResult &vec = this->result();
2129        Result total = 0.0;
2130        for (off_type i = 0; i < size(); i++)
2131            total += vec[i];
2132        return total;
2133    }
2134
2135    size_type
2136    size() const
2137    {
2138        size_type ls = l->size();
2139        size_type rs = r->size();
2140        if (ls == 1) {
2141            return rs;
2142        } else if (rs == 1) {
2143            return ls;
2144        } else {
2145            assert(ls == rs && "Node vector sizes are not equal");
2146            return ls;
2147        }
2148    }
2149
2150    std::string
2151    str() const
2152    {
2153        return csprintf("(%s %s %s)", l->str(), OpString<Op>::str(), r->str());
2154    }
2155};
2156
2157template <class Op>
2158class SumNode : public Node
2159{
2160  public:
2161    NodePtr l;
2162    mutable VResult vresult;
2163
2164  public:
2165    SumNode(NodePtr &p) : l(p), vresult(1) {}
2166
2167    const VResult &
2168    result() const
2169    {
2170        const VResult &lvec = l->result();
2171        size_type size = lvec.size();
2172        assert(size > 0);
2173
2174        vresult[0] = 0.0;
2175
2176        Op op;
2177        for (off_type i = 0; i < size; ++i)
2178            vresult[0] = op(vresult[0], lvec[i]);
2179
2180        return vresult;
2181    }
2182
2183    Result
2184    total() const
2185    {
2186        const VResult &lvec = l->result();
2187        size_type size = lvec.size();
2188        assert(size > 0);
2189
2190        Result vresult = 0.0;
2191
2192        Op op;
2193        for (off_type i = 0; i < size; ++i)
2194            vresult = op(vresult, lvec[i]);
2195
2196        return vresult;
2197    }
2198
2199    size_type size() const { return 1; }
2200
2201    std::string
2202    str() const
2203    {
2204        return csprintf("total(%s)", l->str());
2205    }
2206};
2207
2208
2209//////////////////////////////////////////////////////////////////////
2210//
2211// Visible Statistics Types
2212//
2213//////////////////////////////////////////////////////////////////////
2214/**
2215 * @defgroup VisibleStats "Statistic Types"
2216 * These are the statistics that are used in the simulator.
2217 * @{
2218 */
2219
2220/**
2221 * This is a simple scalar statistic, like a counter.
2222 * @sa Stat, ScalarBase, StatStor
2223 */
2224class Scalar : public ScalarBase<Scalar, StatStor>
2225{
2226  public:
2227    using ScalarBase<Scalar, StatStor>::operator=;
2228};
2229
2230/**
2231 * A stat that calculates the per tick average of a value.
2232 * @sa Stat, ScalarBase, AvgStor
2233 */
2234class Average : public ScalarBase<Average, AvgStor>
2235{
2236  public:
2237    using ScalarBase<Average, AvgStor>::operator=;
2238};
2239
2240class Value : public ValueBase<Value>
2241{
2242};
2243
2244/**
2245 * A vector of scalar stats.
2246 * @sa Stat, VectorBase, StatStor
2247 */
2248class Vector : public VectorBase<Vector, StatStor>
2249{
2250};
2251
2252/**
2253 * A vector of Average stats.
2254 * @sa Stat, VectorBase, AvgStor
2255 */
2256class AverageVector : public VectorBase<AverageVector, AvgStor>
2257{
2258};
2259
2260/**
2261 * A 2-Dimensional vecto of scalar stats.
2262 * @sa Stat, Vector2dBase, StatStor
2263 */
2264class Vector2d : public Vector2dBase<Vector2d, StatStor>
2265{
2266};
2267
2268/**
2269 * A simple distribution stat.
2270 * @sa Stat, DistBase, DistStor
2271 */
2272class Distribution : public DistBase<Distribution, DistStor>
2273{
2274  public:
2275    /**
2276     * Set the parameters of this distribution. @sa DistStor::Params
2277     * @param min The minimum value of the distribution.
2278     * @param max The maximum value of the distribution.
2279     * @param bkt The number of values in each bucket.
2280     * @return A reference to this distribution.
2281     */
2282    Distribution &
2283    init(Counter min, Counter max, Counter bkt)
2284    {
2285        DistStor::Params *params = new DistStor::Params;
2286        params->min = min;
2287        params->max = max;
2288        params->bucket_size = bkt;
2289        params->buckets = (size_type)ceil((max - min + 1.0) / bkt);
2290        this->setParams(params);
2291        this->doInit();
2292        return this->self();
2293    }
2294};
2295
2296/**
2297 * Calculates the mean and variance of all the samples.
2298 * @sa DistBase, SampleStor
2299 */
2300class StandardDeviation : public DistBase<StandardDeviation, SampleStor>
2301{
2302  public:
2303    /**
2304     * Construct and initialize this distribution.
2305     */
2306    StandardDeviation()
2307    {
2308        SampleStor::Params *params = new SampleStor::Params;
2309        this->doInit();
2310        this->setParams(params);
2311    }
2312};
2313
2314/**
2315 * Calculates the per tick mean and variance of the samples.
2316 * @sa DistBase, AvgSampleStor
2317 */
2318class AverageDeviation : public DistBase<AverageDeviation, AvgSampleStor>
2319{
2320  public:
2321    /**
2322     * Construct and initialize this distribution.
2323     */
2324    AverageDeviation()
2325    {
2326        AvgSampleStor::Params *params = new AvgSampleStor::Params;
2327        this->doInit();
2328        this->setParams(params);
2329    }
2330};
2331
2332/**
2333 * A vector of distributions.
2334 * @sa VectorDistBase, DistStor
2335 */
2336class VectorDistribution : public VectorDistBase<VectorDistribution, DistStor>
2337{
2338  public:
2339    /**
2340     * Initialize storage and parameters for this distribution.
2341     * @param size The size of the vector (the number of distributions).
2342     * @param min The minimum value of the distribution.
2343     * @param max The maximum value of the distribution.
2344     * @param bkt The number of values in each bucket.
2345     * @return A reference to this distribution.
2346     */
2347    VectorDistribution &
2348    init(size_type size, Counter min, Counter max, Counter bkt)
2349    {
2350        DistStor::Params *params = new DistStor::Params;
2351        params->min = min;
2352        params->max = max;
2353        params->bucket_size = bkt;
2354        params->buckets = (size_type)ceil((max - min + 1.0) / bkt);
2355        this->setParams(params);
2356        this->doInit(size);
2357        return this->self();
2358    }
2359};
2360
2361/**
2362 * This is a vector of StandardDeviation stats.
2363 * @sa VectorDistBase, SampleStor
2364 */
2365class VectorStandardDeviation
2366    : public VectorDistBase<VectorStandardDeviation, SampleStor>
2367{
2368  public:
2369    /**
2370     * Initialize storage for this distribution.
2371     * @param size The size of the vector.
2372     * @return A reference to this distribution.
2373     */
2374    VectorStandardDeviation &
2375    init(size_type size)
2376    {
2377        SampleStor::Params *params = new SampleStor::Params;
2378        this->doInit(size);
2379        this->setParams(params);
2380        return this->self();
2381    }
2382};
2383
2384/**
2385 * This is a vector of AverageDeviation stats.
2386 * @sa VectorDistBase, AvgSampleStor
2387 */
2388class VectorAverageDeviation
2389    : public VectorDistBase<VectorAverageDeviation, AvgSampleStor>
2390{
2391  public:
2392    /**
2393     * Initialize storage for this distribution.
2394     * @param size The size of the vector.
2395     * @return A reference to this distribution.
2396     */
2397    VectorAverageDeviation &
2398    init(size_type size)
2399    {
2400        AvgSampleStor::Params *params = new AvgSampleStor::Params;
2401        this->doInit(size);
2402        this->setParams(params);
2403        return this->self();
2404    }
2405};
2406
2407template <class Stat>
2408class FormulaInfoProxy : public InfoProxy<Stat, FormulaInfo>
2409{
2410  protected:
2411    mutable VResult vec;
2412    mutable VCounter cvec;
2413
2414  public:
2415    FormulaInfoProxy(Stat &stat) : InfoProxy<Stat, FormulaInfo>(stat) {}
2416
2417    size_type size() const { return this->s.size(); }
2418
2419    const VResult &
2420    result() const
2421    {
2422        this->s.result(vec);
2423        return vec;
2424    }
2425    Result total() const { return this->s.total(); }
2426    VCounter &value() const { return cvec; }
2427
2428    std::string str() const { return this->s.str(); }
2429};
2430
2431class Temp;
2432/**
2433 * A formula for statistics that is calculated when printed. A formula is
2434 * stored as a tree of Nodes that represent the equation to calculate.
2435 * @sa Stat, ScalarStat, VectorStat, Node, Temp
2436 */
2437class Formula : public DataWrapVec<Formula, FormulaInfoProxy>
2438{
2439  protected:
2440    /** The root of the tree which represents the Formula */
2441    NodePtr root;
2442    friend class Temp;
2443
2444  public:
2445    /**
2446     * Create and initialize thie formula, and register it with the database.
2447     */
2448    Formula();
2449
2450    /**
2451     * Create a formula with the given root node, register it with the
2452     * database.
2453     * @param r The root of the expression tree.
2454     */
2455    Formula(Temp r);
2456
2457    /**
2458     * Set an unitialized Formula to the given root.
2459     * @param r The root of the expression tree.
2460     * @return a reference to this formula.
2461     */
2462    const Formula &operator=(Temp r);
2463
2464    /**
2465     * Add the given tree to the existing one.
2466     * @param r The root of the expression tree.
2467     * @return a reference to this formula.
2468     */
2469    const Formula &operator+=(Temp r);
2470    /**
2471     * Return the result of the Fomula in a vector.  If there were no Vector
2472     * components to the Formula, then the vector is size 1.  If there were,
2473     * like x/y with x being a vector of size 3, then the result returned will
2474     * be x[0]/y, x[1]/y, x[2]/y, respectively.
2475     * @return The result vector.
2476     */
2477    void result(VResult &vec) const;
2478
2479    /**
2480     * Return the total Formula result.  If there is a Vector
2481     * component to this Formula, then this is the result of the
2482     * Formula if the formula is applied after summing all the
2483     * components of the Vector.  For example, if Formula is x/y where
2484     * x is size 3, then total() will return (x[1]+x[2]+x[3])/y.  If
2485     * there is no Vector component, total() returns the same value as
2486     * the first entry in the VResult val() returns.
2487     * @return The total of the result vector.
2488     */
2489    Result total() const;
2490
2491    /**
2492     * Return the number of elements in the tree.
2493     */
2494    size_type size() const;
2495
2496    void prepare() { }
2497
2498    /**
2499     * Formulas don't need to be reset
2500     */
2501    void reset();
2502
2503    /**
2504     *
2505     */
2506    bool zero() const;
2507
2508    std::string str() const;
2509};
2510
2511class FormulaNode : public Node
2512{
2513  private:
2514    const Formula &formula;
2515    mutable VResult vec;
2516
2517  public:
2518    FormulaNode(const Formula &f) : formula(f) {}
2519
2520    size_type size() const { return formula.size(); }
2521    const VResult &result() const { formula.result(vec); return vec; }
2522    Result total() const { return formula.total(); }
2523
2524    std::string str() const { return formula.str(); }
2525};
2526
2527/**
2528 * Helper class to construct formula node trees.
2529 */
2530class Temp
2531{
2532  protected:
2533    /**
2534     * Pointer to a Node object.
2535     */
2536    NodePtr node;
2537
2538  public:
2539    /**
2540     * Copy the given pointer to this class.
2541     * @param n A pointer to a Node object to copy.
2542     */
2543    Temp(NodePtr n) : node(n) { }
2544
2545    /**
2546     * Return the node pointer.
2547     * @return the node pointer.
2548     */
2549    operator NodePtr&() { return node; }
2550
2551  public:
2552    /**
2553     * Create a new ScalarStatNode.
2554     * @param s The ScalarStat to place in a node.
2555     */
2556    Temp(const Scalar &s)
2557        : node(new ScalarStatNode(s.info()))
2558    { }
2559
2560    /**
2561     * Create a new ScalarStatNode.
2562     * @param s The ScalarStat to place in a node.
2563     */
2564    Temp(const Value &s)
2565        : node(new ScalarStatNode(s.info()))
2566    { }
2567
2568    /**
2569     * Create a new ScalarStatNode.
2570     * @param s The ScalarStat to place in a node.
2571     */
2572    Temp(const Average &s)
2573        : node(new ScalarStatNode(s.info()))
2574    { }
2575
2576    /**
2577     * Create a new VectorStatNode.
2578     * @param s The VectorStat to place in a node.
2579     */
2580    Temp(const Vector &s)
2581        : node(new VectorStatNode(s.info()))
2582    { }
2583
2584    Temp(const AverageVector &s)
2585        : node(new VectorStatNode(s.info()))
2586    { }
2587
2588    /**
2589     *
2590     */
2591    Temp(const Formula &f)
2592        : node(new FormulaNode(f))
2593    { }
2594
2595    /**
2596     * Create a new ScalarProxyNode.
2597     * @param p The ScalarProxy to place in a node.
2598     */
2599    template <class Stat>
2600    Temp(const ScalarProxy<Stat> &p)
2601        : node(new ScalarProxyNode<Stat>(p))
2602    { }
2603
2604    /**
2605     * Create a ConstNode
2606     * @param value The value of the const node.
2607     */
2608    Temp(signed char value)
2609        : node(new ConstNode<signed char>(value))
2610    { }
2611
2612    /**
2613     * Create a ConstNode
2614     * @param value The value of the const node.
2615     */
2616    Temp(unsigned char value)
2617        : node(new ConstNode<unsigned char>(value))
2618    { }
2619
2620    /**
2621     * Create a ConstNode
2622     * @param value The value of the const node.
2623     */
2624    Temp(signed short value)
2625        : node(new ConstNode<signed short>(value))
2626    { }
2627
2628    /**
2629     * Create a ConstNode
2630     * @param value The value of the const node.
2631     */
2632    Temp(unsigned short value)
2633        : node(new ConstNode<unsigned short>(value))
2634    { }
2635
2636    /**
2637     * Create a ConstNode
2638     * @param value The value of the const node.
2639     */
2640    Temp(signed int value)
2641        : node(new ConstNode<signed int>(value))
2642    { }
2643
2644    /**
2645     * Create a ConstNode
2646     * @param value The value of the const node.
2647     */
2648    Temp(unsigned int value)
2649        : node(new ConstNode<unsigned int>(value))
2650    { }
2651
2652    /**
2653     * Create a ConstNode
2654     * @param value The value of the const node.
2655     */
2656    Temp(signed long value)
2657        : node(new ConstNode<signed long>(value))
2658    { }
2659
2660    /**
2661     * Create a ConstNode
2662     * @param value The value of the const node.
2663     */
2664    Temp(unsigned long value)
2665        : node(new ConstNode<unsigned long>(value))
2666    { }
2667
2668    /**
2669     * Create a ConstNode
2670     * @param value The value of the const node.
2671     */
2672    Temp(signed long long value)
2673        : node(new ConstNode<signed long long>(value))
2674    { }
2675
2676    /**
2677     * Create a ConstNode
2678     * @param value The value of the const node.
2679     */
2680    Temp(unsigned long long value)
2681        : node(new ConstNode<unsigned long long>(value))
2682    { }
2683
2684    /**
2685     * Create a ConstNode
2686     * @param value The value of the const node.
2687     */
2688    Temp(float value)
2689        : node(new ConstNode<float>(value))
2690    { }
2691
2692    /**
2693     * Create a ConstNode
2694     * @param value The value of the const node.
2695     */
2696    Temp(double value)
2697        : node(new ConstNode<double>(value))
2698    { }
2699};
2700
2701
2702/**
2703 * @}
2704 */
2705
2706inline Temp
2707operator+(Temp l, Temp r)
2708{
2709    return NodePtr(new BinaryNode<std::plus<Result> >(l, r));
2710}
2711
2712inline Temp
2713operator-(Temp l, Temp r)
2714{
2715    return NodePtr(new BinaryNode<std::minus<Result> >(l, r));
2716}
2717
2718inline Temp
2719operator*(Temp l, Temp r)
2720{
2721    return NodePtr(new BinaryNode<std::multiplies<Result> >(l, r));
2722}
2723
2724inline Temp
2725operator/(Temp l, Temp r)
2726{
2727    return NodePtr(new BinaryNode<std::divides<Result> >(l, r));
2728}
2729
2730inline Temp
2731operator-(Temp l)
2732{
2733    return NodePtr(new UnaryNode<std::negate<Result> >(l));
2734}
2735
2736template <typename T>
2737inline Temp
2738constant(T val)
2739{
2740    return NodePtr(new ConstNode<T>(val));
2741}
2742
2743template <typename T>
2744inline Temp
2745constantVector(T val)
2746{
2747    return NodePtr(new ConstVectorNode<T>(val));
2748}
2749
2750inline Temp
2751sum(Temp val)
2752{
2753    return NodePtr(new SumNode<std::plus<Result> >(val));
2754}
2755
2756/**
2757 * Enable the statistics package.  Before the statistics package is
2758 * enabled, all statistics must be created and initialized and once
2759 * the package is enabled, no more statistics can be created.
2760 */
2761void enable();
2762
2763/**
2764 * Prepare all stats for data access.  This must be done before
2765 * dumping and serialization.
2766 */
2767void prepare();
2768
2769/**
2770 * Dump all statistics data to the registered outputs
2771 */
2772void dump();
2773
2774/**
2775 * Reset all statistics to the base state
2776 */
2777void reset();
2778/**
2779 * Register a callback that should be called whenever statistics are
2780 * reset
2781 */
2782void registerResetCallback(Callback *cb);
2783
2784std::list<Info *> &statsList();
2785
2786} // namespace Stats
2787
2788#endif // __BASE_STATISTICS_HH__
2789