Changeset 32 for bdm/stat

Show
Ignore:
Timestamp:
03/03/08 13:00:32 (16 years ago)
Author:
smidl
Message:

test KF : estimation of R in KF is not possible! Likelihood of y_t is growing when R -> 0

Location:
bdm/stat
Files:
4 modified

Legend:

Unmodified
Added
Removed
  • bdm/stat/libBM.cpp

    r27 r32  
    77using std::cout; 
    88 
    9 void RV::init( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times, ivec in_obs ) { 
     9void RV::init( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times ) { 
    1010        // 
    1111        int i; 
     
    1616                ( len != in_names.length() ) || \ 
    1717                ( len != in_sizes.length() ) || \ 
    18                 ( len != in_times.length() ) || \ 
    19                 ( len != in_obs.length() ) ) { 
     18                ( len != in_times.length() )) { 
    2019                it_error( "RV::RV inconsistent length of input vectors." ); 
    2120        } 
     
    2524        sizes = in_sizes; 
    2625        times = in_times; 
    27         obs = in_obs; 
    2826        size = 0; 
    2927        for(i=0;i<len;i++){size+=sizes(i);} 
    3028}; 
    3129 
    32 RV::RV ( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times, ivec in_obs ) { 
    33         init ( in_ids, in_names, in_sizes, in_times, in_obs ); 
     30RV::RV ( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times ) { 
     31        init ( in_ids, in_names, in_sizes, in_times ); 
    3432} 
    3533 
    36 RV::RV () {}; 
     34RV::RV () : size(0),len(0){}; 
     35 
     36void RV::add (const RV &rv2) { 
     37        // TODO 
     38        size+=rv2.size; 
     39        len +=rv2.len; 
     40        ids=concat(ids,rv2.ids); 
     41        sizes=concat(sizes,rv2.sizes); 
     42        times=concat(times,rv2.times); 
     43        names=concat(names,rv2.names); 
     44//      return *this; 
     45}; 
    3746 
    3847RV::RV ( ivec in_ids ) { 
     
    4655        } 
    4756 
    48         init ( in_ids, A, ones_i( len ), zeros_i( len ), zeros_i( len ) ); 
     57        init ( in_ids, A, ones_i( len ), zeros_i( len ) ); 
    4958} 
    5059 
    5160RV RV::subselect(ivec ind){ 
    52         return RV(ids(ind), names(to_Arr(ind)), sizes(ind), times(ind), obs(ind)); 
     61        return RV(ids(ind), names(to_Arr(ind)), sizes(ind), times(ind)); 
    5362} 
    5463 
     
    5665 
    5766RV RV::operator()(ivec ind){ 
    58         return RV(ids(ind), names(to_Arr(ind)), sizes(ind), times(ind), obs(ind)); 
     67        return RV(ids(ind), names(to_Arr(ind)), sizes(ind), times(ind)); 
    5968} 
    6069 
     
    7786        return indlist; 
    7887} 
     88 
     89RV concat(const RV &rv1, const RV &rv2 ){ 
     90        RV pom = rv1; 
     91        pom.add(rv2);  
     92        return pom; 
     93} 
  • bdm/stat/libBM.h

    r28 r32  
    2424* More?... 
    2525*/ 
     26 
    2627class RV { 
     28protected: 
    2729        //! size = sum of sizes 
    2830        int size; 
     
    3638 
    3739private: 
    38         void init ( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times, ivec in_obs ); 
     40        void init ( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times); 
    3941public: 
    4042        //! Full constructor which is called by the others 
    41         RV ( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times, ivec in_obs ); 
     43        RV ( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times); 
    4244        //! default constructor 
    4345        RV ( ivec ids ); 
    4446        //! Empty constructor will be set later 
    4547        RV (); 
    46          
     48 
    4749        //! Printing output e.g. for debugging. 
    4850        friend std::ostream &operator<< ( std::ostream &os, const RV &rv ); 
     
    5052        //! Return length (number of scalars) of the RV. 
    5153        int count() const {return size;} ; 
     54 
    5255        //TODO why not inline and later?? 
    53          
     56 
    5457        //! Find indexes of another rv in self 
    55         ivec find(RV rv2); 
     58        ivec find ( RV rv2 ); 
    5659        //! Add (concat) another variable to the current one 
    57         RV add(RV rv2); 
     60        void add (const RV &rv2 ); 
     61        //! Add (concat) another variable to the current one 
     62        friend RV concat (const RV &rv1, const RV &rv2 ); 
    5863        //! Subtract  another variable from the current one 
    59         RV subt(RV rv2); 
     64        RV subt ( RV rv2 ); 
    6065        //! Select only variables at indeces ind 
    61         RV subselect(ivec ind); 
     66        RV subselect ( ivec ind ); 
    6267        //! Select only variables at indeces ind 
    63         RV operator()(ivec ind); 
     68        RV operator() ( ivec ind ); 
    6469        //! Generate new \c RV with \c time shifted by delta. 
    65         void t(int delta); 
    66         //! generate a list of indeces, i.e. which  
     70        void t ( int delta ); 
     71        //! generate a list of indeces, i.e. which 
    6772        ivec indexlist(); 
    6873}; 
    6974 
    7075 
    71  
    72  
    7376//! Class representing function $f(x)$ of variable $x$ represented by \c rv 
     77 
    7478class fnc { 
    7579protected: 
    7680        int dimy; 
    77 public:  
     81public: 
    7882        //! function evaluates numerical value of $f(x)$ at $x=cond$ 
    79         virtual vec eval(const vec &cond) 
    80         { 
    81                 return vec(0); 
     83        virtual vec eval ( const vec &cond ) { 
     84                return vec ( 0 ); 
    8285        }; //Fixme: virtual? 
    8386 
    8487        //! access function 
    85         int _dimy()const{return dimy;} 
    86  
    87                 //! Destructor for future use; 
    88                 virtual ~fnc(){}; 
     88        int _dimy() const{return dimy;} 
     89 
     90        //! Destructor for future use; 
     91        virtual ~fnc() {}; 
    8992}; 
    9093 
    9194 
    9295//! Probability density function with numerical statistics, e.g. posterior density. 
     96 
    9397class epdf { 
     98protected: 
    9499        RV rv; 
    95100public: 
    96101        //!default constructor 
    97         epdf():rv(ivec(0)){}; 
     102        epdf() :rv ( ivec ( 0 ) ) {}; 
     103 
     104        //!default constructor 
     105        epdf ( const RV &rv0 ) :rv ( rv0 ) {}; 
     106 
    98107        //! Returns the required moment of the epdf 
    99108//      virtual vec moment ( const int order = 1 ); 
    100109        //! Returns a sample from the density, \f$x \sim epdf(rv)\f$ 
    101         virtual vec sample ()=0; 
     110        virtual vec sample () const =0; 
    102111        //! Compute probability of argument \c val 
    103         virtual double eval(const vec &val){return 0.0;}; 
     112        virtual double eval ( const vec &val ) const {return exp(this->evalpdflog(val));}; 
     113 
    104114        //! Compute log-probability of argument \c val 
    105         virtual double evalpdflog(const vec &val){return 0.0;}; 
    106  
    107                 //! Destructor for future use; 
    108                 virtual ~epdf(){}; 
    109 }; 
     115        virtual double evalpdflog ( const vec &val ) const =0; 
     116 
     117        //! return expected value  
     118        virtual vec mean() const =0; 
     119         
     120        //! Destructor for future use; 
     121        virtual ~epdf() {}; 
     122        //! access function 
     123        RV _rv() const {return rv;} 
     124}; 
     125 
    110126 
    111127//! Conditional probability density, e.g. modeling some dependencies. 
     128//TODO Samplecond can be generalized 
     129 
    112130class mpdf { 
     131protected: 
    113132        //! modeled random variable 
    114133        RV rv; 
    115134        //! random variable in condition 
    116135        RV rvc; 
     136        //! pointer to internal epdf 
     137        epdf* ep; 
    117138public: 
    118139 
    119140        //! Returns the required moment of the epdf 
    120141//      virtual fnc moment ( const int order = 1 ); 
    121         //! Returns a sample from the density conditioned on \c cond, $x \sim epdf(rv|cond)$ 
    122         virtual vec samplecond (vec &cond, double lik){return vec(0);}; 
    123         virtual void condition (vec &cond){}; 
    124  
    125                 //! Destructor for future use; 
    126                 virtual ~mpdf(){}; 
     142        //! Returns a sample from the density conditioned on \c cond, $x \sim epdf(rv|cond)$. \param ll is a return value of log-likelihood of the sample. 
     143        virtual vec samplecond ( vec &cond, double &ll ) {this->condition(cond);vec temp= ep->sample();ll=ep->evalpdflog(temp);return temp;}; 
     144 
     145        virtual void condition ( const vec &cond ) {}; 
     146         
     147        virtual double evalcond (const vec &dt, const vec &cond ) {this->condition(cond);return ep->eval(dt);}; 
     148 
     149        //! Destructor for future use; 
     150        virtual ~mpdf() {}; 
     151 
     152        //! Default constructor 
     153        mpdf ( const RV &rv0, const RV &rvc0 ) :rv ( rv0 ),rvc ( rvc0 ) {}; 
     154        //! access function 
     155        RV _rvc(){return rvc;} 
     156        //!access function 
     157        epdf& _epdf(){return *ep;} 
    127158}; 
    128159 
     
    133164 
    134165*/ 
     166 
    135167class DS { 
    136168protected: 
    137169        //!Observed variables, returned by \c getdata(). 
    138         RV Drv;  
     170        RV Drv; 
    139171        //!Action variables, accepted by \c write(). 
    140172        RV Urv; // 
    141173public: 
    142         //! Returns full vector of observed data  
    143         void getdata(vec &dt); 
     174        //! Returns full vector of observed data 
     175        void getdata ( vec &dt ); 
    144176        //! Returns data records at indeces. 
    145         void getdata(vec &dt, ivec &indeces); 
     177        void getdata ( vec &dt, ivec &indeces ); 
    146178        //! Accepts action variable and schedule it for application. 
    147         void write(vec &ut); 
    148         //! Accepts action variables at specific indeces         
    149         void write(vec &ut, ivec &indeces); 
    150         /*! \brief Method that assigns random variables to the datasource.  
     179        void write ( vec &ut ); 
     180        //! Accepts action variables at specific indeces 
     181        void write ( vec &ut, ivec &indeces ); 
     182        /*! \brief Method that assigns random variables to the datasource. 
    151183        Typically, the datasource will be constructed without knowledge of random variables. This method will associate existing variables with RVs. 
    152          
     184 
    153185        (Inherited from m3k, may be deprecated soon). 
    154186        */ 
    155         void linkrvs(RV &drv, RV &urv); 
    156          
    157         //! Moves from $t$ to $t+1$, i.e. perfroms the actions and reads response of the system.  
     187        void linkrvs ( RV &drv, RV &urv ); 
     188 
     189        //! Moves from $t$ to $t+1$, i.e. perfroms the actions and reads response of the system. 
    158190        void step(); 
    159                  
     191 
    160192}; 
    161193 
    162194/*! \brief Bayesian Model of the world, i.e. all uncertainty is modeled by probabilities. 
    163          
    164 */ 
     195 
     196*/ 
     197 
    165198class BM { 
    166 public: 
     199protected: 
     200        //!Random variable of the posterior 
     201        RV rv; 
    167202        //!Logarithm of marginalized data likelihood. 
    168         double ll; 
     203 double ll; 
    169204        //!  If true, the filter will compute likelihood of the data record and store it in \c ll . Set to false if you want to save time. 
    170205        bool evalll; 
     206public: 
    171207 
    172208        //!Default constructor 
    173         BM():ll(0),evalll(true){}; 
    174          
     209        BM(const RV &rv0) :rv(rv0), ll ( 0 ),evalll ( true ) {//Fixme: test rv  
     210        }; 
     211 
    175212        /*! \brief Incremental Bayes rule 
    176213        @param dt vector of input data 
    177214        */ 
    178         virtual void bayes ( const vec &dt) = 0; 
     215        virtual void bayes ( const vec &dt ) = 0; 
    179216        //! Batch Bayes rule (columns of Dt are observations) 
    180217        void bayes ( mat Dt ); 
    181218        //! Returns a pointer to the epdf representing posterior density on parameters. Use with care! 
    182         virtual epdf* _epdf()=0; 
    183  
    184                 //! Destructor for future use; 
    185                 virtual ~BM(){}; 
     219        virtual epdf& _epdf()=0; 
     220 
     221        //! Destructor for future use; 
     222        virtual ~BM() {}; 
     223        //!access function 
     224        const RV& _rv() const {return rv;} 
     225        //!access function 
     226        double _ll() const {return ll;} 
     227}; 
     228 
     229/*! 
     230\brief Conditional Bayesian Filter 
     231 
     232Evaluates conditional filtering density $f(rv|rvc,data)$ for a given \c rvc which is specified in each step by calling function \c condition. 
     233 
     234This is an interface class used to assure that certain BM has operation \c condition . 
     235 
     236*/ 
     237 
     238class BMcond { 
     239protected: 
     240        RV rvc; 
     241public: 
     242        //! Substitute \c val for \c rvc. 
     243        virtual void condition ( const vec &val ) =0; 
     244        BMcond(RV &rv0):rvc(rv0){}; 
     245        virtual ~BMcond(){}; 
     246        const RV& _rvc() const {return rvc;} 
    186247}; 
    187248 
  • bdm/stat/libEF.cpp

    r14 r32  
    11#include <itpp/itbase.h> 
     2#include <itpp/base/bessel.h> 
    23#include "libEF.h" 
     4#include <math.h> 
    35 
    46using namespace itpp; 
    57 
     8Uniform_RNG UniRNG; 
     9Normal_RNG NorRNG; 
     10Gamma_RNG GamRNG; 
     11 
    612using std::cout; 
    713 
     14vec egamma::sample() const { 
     15        vec smp ( rv.count() ); 
     16        int i; 
     17 
     18        for ( i=0; i<rv.count(); i++ ) { 
     19                GamRNG.setup ( alpha ( i ),beta ( i ) ); 
     20                smp ( i ) = GamRNG(); 
     21        } 
     22 
     23        return smp; 
     24} 
     25 
     26mat egamma::sample ( int N ) const { 
     27        mat Smp ( rv.count(),N ); 
     28        int i,j; 
     29 
     30        for ( i=0; i<rv.count(); i++ ) { 
     31                GamRNG.setup ( alpha ( i ),beta ( i ) ); 
     32 
     33                for ( j=0; j<N; j++ ) { 
     34                        Smp ( i,j ) = GamRNG(); 
     35                } 
     36        } 
     37 
     38        return Smp; 
     39} 
     40 
     41double egamma::evalpdflog ( const vec &val ) const { 
     42        double res = 0.0; //will be added 
     43        int i; 
     44 
     45        for ( i=0; i<rv.count(); i++ ) { 
     46                res += ( alpha ( i ) - 1 ) *std::log ( val ( i ) ) + alpha ( i ) *std::log ( beta ( i ) ) - beta ( i ) *val ( i ) - lgamma ( alpha ( i ) ); 
     47        } 
     48 
     49        return res; 
     50} 
     51 
     52//MGamma 
     53mgamma::mgamma ( const RV &rv,const RV &rvc ) : mEF ( rv,rvc ), epdf ( rv ) {vec* tmp; epdf._param ( tmp,_beta );}; 
     54 
     55void mgamma::set_parameters ( double k0 ) { 
     56        k=k0; 
     57        ep = &epdf; 
     58        epdf.set_parameters ( k*ones ( rv.count() ),*_beta ); 
     59}; 
     60 
     61vec mgamma::samplecond ( vec &cond, double &ll ) { 
     62        *_beta=k / cond ; 
     63        vec smp = epdf.sample(); 
     64        ll = epdf.evalpdflog ( smp ); 
     65        return smp; 
     66}; 
     67 
     68//Fixme repetition of mlnorm.samplecond. 
     69mat mgamma::samplecond ( vec &cond, vec &lik, int n ) { 
     70        int i; 
     71        int dim = rv.count(); 
     72        mat Smp ( dim,n ); 
     73        vec smp ( dim ); 
     74        this->condition ( cond ); 
     75 
     76        for ( i=0; i<n; i++ ) { 
     77                smp = epdf.sample(); 
     78                lik ( i ) = epdf.eval ( smp ); 
     79                Smp.set_col ( i ,smp ); 
     80        } 
     81 
     82        return Smp; 
     83}; 
     84 
     85ivec eEmp::resample ( RESAMPLING_METHOD method ) { 
     86        ivec ind=zeros_i ( n ); 
     87        ivec N_babies = zeros_i ( n ); 
     88        vec cumDist = cumsum ( w ); 
     89        vec u ( n ); 
     90        int i,j,parent; 
     91        double u0; 
     92 
     93        switch ( method ) { 
     94        case MULTINOMIAL: 
     95                u ( n - 1 ) = pow ( UniRNG.sample(), 1.0 / n ); 
     96 
     97                for ( i = n - 2;i >= 0;i-- ) { 
     98                        u ( i ) = u ( i + 1 ) * pow ( UniRNG.sample(), 1.0 / ( i + 1 ) ); 
     99                } 
     100 
     101                break; 
     102 
     103        case STRATIFIED: 
     104 
     105                for ( i = 0;i < n;i++ ) { 
     106                        u ( i ) = ( i + UniRNG.sample() ) / n; 
     107                } 
     108 
     109                break; 
     110 
     111        case SYSTEMATIC: 
     112                u0 = UniRNG.sample(); 
     113 
     114                for ( i = 0;i < n;i++ ) { 
     115                        u ( i ) = ( i + u0 ) / n; 
     116                } 
     117 
     118                break; 
     119 
     120        default: 
     121                it_error ( "PF::resample(): Unknown resampling method" ); 
     122        } 
     123 
     124        // U is now full 
     125        j = 0; 
     126 
     127        for ( i = 0;i < n;i++ ) { 
     128                while ( u ( i ) > cumDist ( j ) ) j++; 
     129 
     130                N_babies ( j ) ++; 
     131        } 
     132 
     133        // We have assigned new babies for each Particle 
     134        // Now, we fill the resulting index such that: 
     135        // * particles with at least one baby should not move * 
     136        // This assures that reassignment can be done inplace; 
     137 
     138        // find the first parent; 
     139        parent=0; while ( N_babies ( parent ) ==0 ) parent++; 
     140 
     141        // Build index 
     142        for ( i = 0;i < n;i++ ) { 
     143                if ( N_babies ( i ) > 0 ) { 
     144                        ind ( i ) = i; 
     145                        N_babies ( i ) --; //this index was now replicated; 
     146                } else { 
     147                        // test if the parent has been fully replicated 
     148                        // if yes, find the next one 
     149                        while ( ( N_babies ( parent ) ==0 ) || ( N_babies ( parent ) ==1 && parent>i ) ) parent++; 
     150 
     151                        // Replicate parent 
     152                        ind ( i ) = parent; 
     153 
     154                        N_babies ( parent ) --; //this index was now replicated; 
     155                } 
     156 
     157        } 
     158 
     159        // copy the internals according to ind 
     160        for ( i=0;i<n;i++ ) { 
     161                if ( ind ( i ) !=i ) { 
     162                        samples ( i ) =samples ( ind ( i ) ); 
     163                } 
     164                w ( i ) = 1.0/n; 
     165        } 
     166 
     167        return ind; 
     168} 
     169 
     170void eEmp::set_parameters ( const vec &w0, epdf* epdf0 ) { 
     171//it_assert_debug(rv==epdf0->rv(),"Wrong epdf0"); 
     172        w=w0; 
     173        w/=sum ( w0 );//renormalize 
     174        n=w.length(); 
     175        samples.set_size ( n ); 
     176 
     177        for ( int i=0;i<n;i++ ) {samples ( i ) =epdf0->sample();} 
     178} 
  • bdm/stat/libEF.h

    r28 r32  
    1717#include "../math/libDC.h" 
    1818#include "libBM.h" 
     19#include "../itpp_ext.h" 
    1920//#include <std> 
    2021 
    2122using namespace itpp; 
    2223 
     24 
     25//! Global Uniform_RNG 
     26extern Uniform_RNG UniRNG; 
     27extern Normal_RNG NorRNG; 
     28extern Gamma_RNG GamRNG; 
     29 
     30 
    2331/*! 
    2432* \brief General conjugate exponential family posterior density. 
     
    3038 
    3139public: 
     40//      eEF() :epdf() {}; 
    3241        //! default constructor 
    33         eEF() :epdf() {}; 
     42        eEF ( const RV &rv ) :epdf ( rv ) {}; 
    3443 
    3544        virtual void tupdate ( double phi, mat &vbar, double nubar ) {}; 
     
    4150 
    4251public: 
    43  
     52        mEF ( const RV &rv0, const RV &rvc0 ) :mpdf ( rv0,rvc0 ) {}; 
    4453}; 
    4554 
     
    6170        //! indicator if \c _iR is chached 
    6271        bool cached; 
    63         //! Random number generator for sampling; Fixme: what about *static* correct ? 
    64         Normal_RNG RNG; 
    6572        //! dimension (redundant from rv.count() for easier coding ) 
    6673        int dim; 
    6774public: 
    68         enorm() :eEF() {}; 
     75//      enorm() :eEF() {}; 
    6976 
    7077        enorm ( RV &rv ); 
     
    7481        void dupdate ( mat &v,double nu=1.0 ); 
    7582 
    76         vec sample(); 
    77         mat sample ( int N ); 
    78         double eval ( const vec &val ); 
    79         double evalpdflog ( const vec &val ); 
     83        vec sample() const; 
     84        mat sample ( int N ) const; 
     85        double eval ( const vec &val ) const ; 
     86        double evalpdflog ( const vec &val ) const; 
     87        vec mean()const {return mu;} 
    8088 
    8189//Access methods 
     
    94102 
    95103/*! 
    96  \brief 
    97 */ 
    98 template<class sq_T> 
    99  
     104 \brief Gamma posterior density 
     105 
     106 Multvariate Gamma density as product of independent univariate densities. 
     107 \f[ 
     108 f(x|a,b) = \prod f(x_i|a_i,b_i) 
     109 \f] 
     110*/ 
     111 
     112class egamma : public eEF { 
     113protected: 
     114        vec alpha; 
     115        vec beta; 
     116public : 
     117        //! Default constructor 
     118        egamma ( const RV &rv ) :eEF ( rv ) {}; 
     119        //! Sets parameters 
     120        void set_parameters ( const vec &a, const vec &b ) {alpha=a,beta=b;}; 
     121        vec sample() const; 
     122        mat sample ( int N ) const; 
     123        double evalpdflog ( const vec &val ) const; 
     124        //! Returns poiter to alpha and beta. Potentially dengerous: use with care! 
     125        void _param ( vec* &a, vec* &b ) {a=&alpha;b=&beta;}; 
     126        vec mean()const {vec pom(alpha); pom/=beta; return pom;} 
     127}; 
     128 
     129//! Weighted mixture of epdfs with external owned components. 
     130class emix : public epdf { 
     131protected: 
     132        int n; 
     133        vec &w; 
     134        Array<epdf*> Coms; 
     135public: 
     136//! Default constructor 
     137        emix ( const RV &rv, vec &w0): epdf(rv), n(w0.length()), w(w0), Coms(n) {}; 
     138        void set_parameters( int &i, double wi, epdf* ep){w(i)=wi;Coms(i)=ep;} 
     139        vec mean(){vec pom; for(int i=0;i<n;i++){pom+=Coms(i)->mean()*w(i);} return pom;}; 
     140        vec sample() {it_error ( "Not implemented" );return 0;} 
     141}; 
     142 
     143//!  Uniform distributed density on a rectangular support 
     144 
     145class euni: public epdf { 
     146protected: 
     147//! lower bound on support 
     148        vec low; 
     149//! upper bound on support 
     150        vec high; 
     151//! internal 
     152        vec distance; 
     153//! normalizing coefficients 
     154        double nk,lnk; 
     155public: 
     156        euni ( const RV rv ) :epdf ( rv ) {} 
     157        double eval ( const vec &val ) const  {return nk;} 
     158        double evalpdflog ( const vec &val ) const  {return lnk;} 
     159        vec sample() const { 
     160                vec smp ( rv.count() ); UniRNG.sample_vector ( rv.count(),smp ); 
     161                return low+distance*smp; 
     162        } 
     163        void set_parameters ( const vec &low0, const vec &high0 ) { 
     164                distance = high0-low0; 
     165                it_assert_debug ( min ( distance ) >0.0,"bad support" ); 
     166                low = low0; 
     167                high = high0; 
     168                nk = prod ( 1.0/distance ); 
     169                lnk = log ( nk ); 
     170        } 
     171        vec mean() const {vec pom=high; pom-=low; pom/=2.0; return pom;} 
     172}; 
     173 
     174 
     175/*! 
     176 \brief Normal distributed linear function with linear function of mean value; 
     177 
     178 Mean value $mu=A*rvc$. 
     179*/ 
     180template<class sq_T> 
    100181class mlnorm : public mEF { 
    101182        enorm<sq_T> epdf; 
     183        vec* _mu; //cached epdf.mu; 
    102184        mat A; 
    103185public: 
    104186        //! Constructor 
    105         mlnorm ( RV &rv,RV &rvc, mat &A, sq_T &R ); 
     187        mlnorm ( RV &rv,RV &rvc ); 
     188        void set_parameters ( const  mat &A, const sq_T &R ); 
    106189        //!Generate one sample of the posterior 
    107190        vec samplecond ( vec &cond, double &lik ); 
     191        //!Generate matrix of samples of the posterior 
    108192        mat samplecond ( vec &cond, vec &lik, int n ); 
    109193        void condition ( vec &cond ); 
    110194}; 
    111195 
     196/*! 
     197\brief  Gamma random walk 
     198 
     199Mean value, $\mu$, of this density is given by \c rvc . 
     200Standard deviation of the random walk is proportional to one $k$-th the mean. 
     201This is achieved by setting $\alpha=k$ and $\beta=k/\mu$. 
     202 
     203The standard deviation of the walk is then: $\mu/\sqrt(k)$. 
     204*/ 
     205class mgamma : public mEF { 
     206        egamma epdf; 
     207        double k; 
     208        vec* _beta; 
     209 
     210public: 
     211        //! Constructor 
     212        mgamma ( const RV &rv,const RV &rvc ); 
     213        void set_parameters ( double k ); 
     214        //!Generate one sample of the posterior 
     215        vec samplecond ( vec &cond, double &lik ); 
     216        //!Generate matrix of samples of the posterior 
     217        mat samplecond ( vec &cond, vec &lik, int n ); 
     218        void condition ( const vec &val ) {*_beta=k/val;}; 
     219}; 
     220 
     221//! Switch between various resampling methods. 
     222enum RESAMPLING_METHOD { MULTINOMIAL = 0, STRATIFIED = 1, SYSTEMATIC = 3 }; 
     223/*! 
     224\brief Weighted empirical density 
     225 
     226Used e.g. in particle filters. 
     227*/ 
     228class eEmp: public epdf { 
     229protected : 
     230        //! Number of particles 
     231        int n; 
     232        vec w; 
     233        Array<vec> samples; 
     234public: 
     235        eEmp ( const RV &rv0 ,int n0) :epdf ( rv0 ),n(n0),w(n),samples(n) {}; 
     236        void set_parameters ( const vec &w0, epdf* pdf0 ); 
     237        //! Potentially dangerous, use with care. 
     238        vec& _w()  {return w;}; 
     239        Array<vec>& _samples() {return samples;}; 
     240        //! Function performs resampling, i.e. removal of low-weight samples and duplication of high-weight samples such that the new samples represent the same density. 
     241        ivec resample ( RESAMPLING_METHOD method = SYSTEMATIC ); 
     242        vec sample() const {it_error ( "Not implemented" );return 0;} 
     243        double evalpdflog(const vec &val) const {it_error ( "Not implemented" );return 0.0;} 
     244        vec mean()const {vec pom=zeros(rv.count());  
     245                for (int i=0;i<n;i++){pom+=samples(i)*w(i);} 
     246                return pom; 
     247        } 
     248}; 
     249 
     250 
    112251//////////////////////// 
    113252 
    114253template<class sq_T> 
    115 enorm<sq_T>::enorm ( RV &rv ) :eEF(), mu ( rv.count() ),R(rv.count()),_iR(rv.count()),cached ( false ),dim ( rv.count() ) {}; 
     254enorm<sq_T>::enorm ( RV &rv ) :eEF(rv), mu ( rv.count() ),R ( rv.count() ),_iR ( rv.count() ),cached ( false ),dim ( rv.count() ) {}; 
    116255 
    117256template<class sq_T> 
     
    120259        mu = mu0; 
    121260        R = R0; 
    122         if(_iR.rows()!=R.rows()) _iR=R; // memory allocation! 
     261        if ( _iR.rows() !=R.rows() ) _iR=R; // memory allocation! 
    123262        R.inv ( _iR ); //update cache 
    124263        cached=true; 
     
    136275 
    137276template<class sq_T> 
    138 vec enorm<sq_T>::sample() { 
     277vec enorm<sq_T>::sample() const { 
    139278        vec x ( dim ); 
    140         RNG.sample_vector ( dim,x ); 
     279        NorRNG.sample_vector ( dim,x ); 
    141280        vec smp = R.sqrt_mult ( x ); 
    142281 
     
    146285 
    147286template<class sq_T> 
    148 mat enorm<sq_T>::sample ( int N ) { 
     287mat enorm<sq_T>::sample ( int N )const { 
    149288        mat X ( dim,N ); 
    150289        vec x ( dim ); 
     
    153292 
    154293        for ( i=0;i<N;i++ ) { 
    155                 RNG.sample_vector ( dim,x ); 
     294                NorRNG.sample_vector ( dim,x ); 
    156295                pom = R.sqrt_mult ( x ); 
    157296                pom +=mu; 
     
    163302 
    164303template<class sq_T> 
    165 double enorm<sq_T>::eval ( const vec &val ) { 
    166         return exp ( evalpdflog ( val ) ); 
    167 }; 
    168  
    169 template<class sq_T> 
    170 double enorm<sq_T>::evalpdflog ( const vec &val ) { 
    171         if ( !cached ) {R.inv ( _iR );cached=true;} 
    172  
    173         return -0.5* ( R.cols() *0.79817986835811504957 +R.logdet() +_iR.qform ( mu-val ) ); 
    174 }; 
    175  
    176  
    177 template<class sq_T> 
    178 mlnorm<sq_T>::mlnorm ( RV &rv,RV &rvc, mat &A, sq_T &R ) { 
    179         int dim = rv.count(); 
    180         vec mu ( dim ); 
    181  
    182         epdf = enorm<sq_T> ( rv,mu,R ); 
     304double enorm<sq_T>::eval ( const vec &val ) const { 
     305        double pdfl,e; 
     306        pdfl = evalpdflog ( val ); 
     307        e = exp ( pdfl ); 
     308        return e; 
     309}; 
     310 
     311template<class sq_T> 
     312double enorm<sq_T>::evalpdflog ( const vec &val ) const { 
     313        if ( !cached ) {it_error("this should not happen, see cached");} 
     314 
     315        // 1.83787706640935 = log(2pi) 
     316        return -0.5* ( R.cols() * 1.83787706640935 +R.logdet() +_iR.qform ( mu-val ) ); 
     317}; 
     318 
     319 
     320template<class sq_T> 
     321mlnorm<sq_T>::mlnorm ( RV &rv0,RV &rvc0 ) :mEF ( rv0,rvc0 ),epdf ( rv ),A ( rv0.count(),rv0.count() ) { 
     322        _mu = epdf._mu(); 
     323} 
     324 
     325template<class sq_T> 
     326void mlnorm<sq_T>::set_parameters ( const mat &A0, const sq_T &R0 ) { 
     327        epdf.set_parameters ( zeros ( rv.count() ),R0 ); 
     328        A = A0; 
    183329} 
    184330 
     
    199345        this->condition ( cond ); 
    200346 
    201         for ( i=0; i<dim; i++ ) { 
     347        for ( i=0; i<n; i++ ) { 
    202348                smp = epdf.sample(); 
    203349                lik ( i ) = epdf.eval ( smp ); 
     
    210356template<class sq_T> 
    211357void mlnorm<sq_T>::condition ( vec &cond ) { 
    212         epdf.mu = A*cond; 
     358        *_mu = A*cond; 
    213359//R is already assigned; 
    214360} 
     
    216362/////////// 
    217363 
    218 //#ifdef HAVE_EXTERN_TEMPLATE 
    219  
    220 //  extern template class enorm<fsqmat>; 
    221 //  extern template class enorm<ldmat>; 
    222 //#endif 
    223364 
    224365#endif //EF_H