Changeset 190

Show
Ignore:
Timestamp:
10/22/08 10:46:38 (16 years ago)
Author:
smidl
Message:

adaptation of merger for changes and creation of datalink class

Files:
1 added
6 modified

Legend:

Unmodified
Added
Removed
  • bdm/estim/merger.cpp

    r186 r190  
    3333        vec &w = eSmp._w(); //aux 
    3434 
    35         mat Smp_ex =ones ( rv.count() +1,Ns ); // Extended samples The last row is ones for the ARX model 
     35        mat Smp_ex =ones ( rv.count() +1,Ns ); // Extended samples for the ARX model - the last row is ones  
    3636        for ( int i=0;i<Ns;i++ ) {      set_col_part ( Smp_ex,i,Smp ( i ) );} 
    3737 
     
    4949                 V0, rv.count() *rv.count() +3.0 ); //initial guess of Mix: zero mean, large variance 
    5050 
    51  
    52  
    5351        // ============= MAIN LOOP ================== 
    5452        bool converged=false; 
     
    6260                //Re-Initialize Mixture model 
    6361                Mix.init ( &A0, Smp_ex, Nc ); 
    64                 Mix.bayesB ( Smp_ex ); 
     62                Mix.bayesB ( Smp_ex, ones(Ns));//w*Ns ); 
    6563                Mpred = Mix.predictor(rv); // Allocation => must be deleted at the end!! 
    6664         
     
    152150                // ==== stopping rule === 
    153151                niter++; 
    154                 converged = ( niter>6); 
     152                converged = ( niter>20); 
    155153        } 
    156154 
  • bdm/estim/merger.h

    r182 r190  
    4141                        compositepdf ( S ), epdf ( getrv ( false ) ), 
    4242                        Mix ( Array<BMEF*> ( 0 ),vec ( 0 ) ) 
    43         {setindices(rv); beta=2.0; Ns=100; Nc=10;} 
     43        {setindices(rv); beta=2.0; Ns=100; Nc=10; Mix.set_method(EM);} 
    4444        //! Set internal parameters used in approximation 
    4545        void set_parameters ( double beta0, int Ns0, int Nc0 ) {        beta=beta0;Ns=Ns0;Nc=Nc0;} 
  • bdm/stat/libBM.h

    r183 r190  
    1515 
    1616#include <itpp/itbase.h> 
     17#include "../itpp_ext.h" 
    1718//#include <std> 
    1819 
     
    2021 
    2122//! Structure of RV (used internally), i.e. expanded RVs 
    22 class str{ 
     23class str { 
    2324public: 
    2425        //! vector id ids (non-unique!) 
     
    2728        ivec times; 
    2829        //!Default constructor 
    29         str(ivec ids0, ivec times0):ids(ids0),times(times0){ 
    30                 it_assert_debug(times0.length()==ids0.length(),"Incompatible input"); 
     30        str ( ivec ids0, ivec times0 ) :ids ( ids0 ),times ( times0 ) { 
     31                it_assert_debug ( times0.length() ==ids0.length(),"Incompatible input" ); 
    3132        }; 
    3233}; 
     
    5556private: 
    5657        //! auxiliary function used in constructor 
    57         void init (ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times ); 
    58 public: 
    59         //! Full constructor  
     58        void init ( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times ); 
     59public: 
     60        //! Full constructor 
    6061        RV ( Array<std::string> in_names, ivec in_sizes, ivec in_times ); 
    6162        //! Constructor with times=0 
     
    7778 
    7879        //! Find indexes of self in another rv, \return ivec of the same size as self. 
    79         ivec findself (const RV &rv2 ) const; 
     80        ivec findself ( const RV &rv2 ) const; 
    8081        //! Compare if \c rv2 is identical to this \c RV 
    81         bool equal (const RV &rv2 ) const; 
     82        bool equal ( const RV &rv2 ) const; 
    8283        //! Add (concat) another variable to the current one, \return true if all rv2 were added, false if rv2 is in conflict 
    8384        bool add ( const RV &rv2 ); 
     
    9293        //! generate \c str from rv, by expanding sizes 
    9394        str tostr() const; 
    94         //! when this rv is a part of bigger rv, this function returns indeces of self in the data vector of the bigger crv.   
     95        //! when this rv is a part of bigger rv, this function returns indeces of self in the data vector of the bigger crv. 
    9596        //! Then, data can be copied via: data_of_this = cdata(ind); 
    96         ivec dataind(const RV &crv) const; 
    97         //! generate mutual indeces when copying data betwenn self and crv.  
     97        ivec dataind ( const RV &crv ) const; 
     98        //! generate mutual indeces when copying data betwenn self and crv. 
    9899        //! Data are copied via: data_of_this(selfi) = data_of_rv2(rv2i) 
    99         void dataind(const RV &rv2, ivec &selfi, ivec &rv2i) const; 
     100        void dataind ( const RV &rv2, ivec &selfi, ivec &rv2i ) const; 
    100101 
    101102        //!access function 
     
    110111        //!access function 
    111112        std::string name ( int at ) {return names ( at );}; 
    112          
    113         //!access function 
    114         void set_id ( int at, int id0 ) {ids ( at )=id0;}; 
    115         //!access function 
    116         void set_size ( int at, int size0 ) {sizes ( at )=size0; tsize=sum(sizes);}; 
    117         //!access function 
    118         void set_time ( int at, int time0 ) {times ( at )=time0;}; 
    119  
    120         //!Assign unused ids to this rv  
     113 
     114        //!access function 
     115        void set_id ( int at, int id0 ) {ids ( at ) =id0;}; 
     116        //!access function 
     117        void set_size ( int at, int size0 ) {sizes ( at ) =size0; tsize=sum ( sizes );}; 
     118        //!access function 
     119        void set_time ( int at, int time0 ) {times ( at ) =time0;}; 
     120 
     121        //!Assign unused ids to this rv 
    121122        void newids(); 
    122123}; 
     
    164165//      //! Returns the required moment of the epdf 
    165166//      virtual vec moment ( const int order = 1 ); 
    166          
     167 
    167168        //! Returns a sample, \f$x\f$ from density \f$epdf(rv)\f$ 
    168169        virtual vec sample () const =0; 
     
    178179        virtual vec evalpdflog_m ( const mat &Val ) const { 
    179180                vec x ( Val.cols() ); 
    180                 for ( int i=0;i<Val.cols();i++ ) {x ( i ) =evalpdflog( Val.get_col(i) ) ;} 
     181                for ( int i=0;i<Val.cols();i++ ) {x ( i ) =evalpdflog ( Val.get_col ( i ) ) ;} 
    181182                return x; 
    182183        } 
    183184        //! Return conditional density on the given RV, the remaining rvs will be in conditioning 
    184         virtual mpdf* condition(const RV &rv) const  {it_warning("Not implemented"); return NULL;} 
     185        virtual mpdf* condition ( const RV &rv ) const  {it_warning ( "Not implemented" ); return NULL;} 
    185186        //! Return marginal density on the given RV, the remainig rvs are intergrated out 
    186         virtual epdf* marginal(const RV &rv) const {it_warning("Not implemented"); return NULL;} 
     187        virtual epdf* marginal ( const RV &rv ) const {it_warning ( "Not implemented" ); return NULL;} 
    187188 
    188189        //! return expected value 
     
    194195        const RV& _rv() const {return rv;} 
    195196        //! modifier function - useful when copying epdfs 
    196         void _renewrv(const RV &in_rv){rv=in_rv;} 
     197        void _renewrv ( const RV &in_rv ) {rv=in_rv;} 
    197198        //! 
    198199}; 
     
    215216//      virtual fnc moment ( const int order = 1 ); 
    216217        //! Returns a sample from the density conditioned on \c cond, \f$x \sim epdf(rv|cond)\f$. \param cond is numeric value of \c rv \param ll is a return value of log-likelihood of the sample. 
    217         virtual vec samplecond (const vec &cond, double &ll ) {this->condition ( cond ); 
    218         vec temp= ep->sample(); 
    219         ll=ep->evalpdflog ( temp );return temp;}; 
     218        virtual vec samplecond ( const vec &cond, double &ll ) { 
     219                this->condition ( cond ); 
     220                vec temp= ep->sample(); 
     221                ll=ep->evalpdflog ( temp );return temp; 
     222        }; 
    220223        //! Returns \param N samples from the density conditioned on \c cond, \f$x \sim epdf(rv|cond)\f$. \param cond is numeric value of \c rv \param ll is a return value of log-likelihood of the sample. 
    221         virtual mat samplecond (const vec &cond, vec &ll, int N ) { 
     224        virtual mat samplecond ( const vec &cond, vec &ll, int N ) { 
    222225                this->condition ( cond ); 
    223                 mat temp ( rv.count(),N ); vec smp ( rv.count() );  
     226                mat temp ( rv.count(),N ); vec smp ( rv.count() ); 
    224227                for ( int i=0;i<N;i++ ) {smp=ep->sample() ;temp.set_col ( i, smp );ll ( i ) =ep->evalpdflog ( smp );} 
    225228                return temp; 
    226229        }; 
    227230        //! Update \c ep so that it represents this mpdf conditioned on \c rvc = cond 
    228         virtual void condition ( const vec &cond ) {it_error("Not implemented");}; 
     231        virtual void condition ( const vec &cond ) {it_error ( "Not implemented" );}; 
    229232 
    230233        //! Shortcut for conditioning and evaluation of the internal epdf. In some cases,  this operation can be implemented efficiently. 
     
    237240        mpdf ( const RV &rv0, const RV &rvc0 ) :rv ( rv0 ),rvc ( rvc0 ) {}; 
    238241        //! access function 
    239         RV _rvc() {return rvc;} 
     242        RV _rvc() const {return rvc;} 
    240243        //! access function 
    241         RV _rv() {return rv;} 
     244        RV _rv() const {return rv;} 
    242245        //!access function 
    243246        epdf& _epdf() {return *ep;} 
    244247}; 
    245248 
    246 /*! \brief Unconditional mpdf, allows using epdf in the role of mpdf.  
     249//!DataLink is a connection between epdf and its superordinate (Up) 
     250//! It is assumed that my val is fully present in "Up" 
     251class datalink { 
     252protected: 
     253        //! Remember how long val should be 
     254        int valsize; 
     255        //! Remember how long val of "Up" should be 
     256        int valupsize; 
     257        //! val-to-val link, indeces of the upper val 
     258        ivec v2v_up; 
     259        public: 
     260        //! Constructor 
     261        datalink ( const RV &rv, const RV &rv_up ) : 
     262                valsize(rv.count()), valupsize(rv_up.count()), v2v_up ( rv.dataind ( rv_up ) )  {it_assert_debug(v2v_up.length()==valsize,"rv is not fully in rv_up");} 
     263        //! Get val for myself from val of "Up" 
     264        vec get_val ( const vec &val_up ) {it_assert_debug(valupsize==val_up.length(),"Wrong val_up"); return get_vec ( val_up,v2v_up );} 
     265        //! Fill val of "Up" by my pieces 
     266        void fill_val ( vec &val_up, const vec &val ) {it_assert_debug(valsize==val.length(),"Wrong val");it_assert_debug(valupsize==val_up.length(),"Wrong val_up");set_subvector ( val_up, v2v_up, val );} 
     267}; 
     268 
     269//!DataLink is a connection between mpdf and its superordinate (Up) 
     270//! This class links  
     271class datalink_mpdf: public datalink { 
     272protected: 
     273        //!upper_val-to-local_cond link, indeces of the upper val 
     274        ivec v2c_up; 
     275        //!upper_val-to-local_cond link, ideces of the local cond 
     276        ivec v2c_lo; 
     277        //!cond-to-cond link, indeces of the upper cond 
     278        ivec c2c_up; 
     279        //!cond-to-cond link, indeces of the local cond 
     280        ivec c2c_lo; 
     281        //! size of cond 
     282        int csize; 
     283public: 
     284        //! Constructor 
     285        datalink_mpdf ( const mpdf &Me, const mpdf &Up ) : 
     286                        datalink ( Me._rv(),Up._rv() ) { 
     287                //establish v2c connection 
     288                Me._rvc().dataind ( Up._rv(), v2c_lo, v2c_up ); 
     289                //establish c2c connection 
     290                Me._rvc().dataind ( Up._rvc(), c2c_lo, c2c_up ); 
     291                csize = Me._rvc().count(); 
     292        } 
     293        //! Get cond for myself from val and cond of "Up" 
     294        vec get_cond ( const vec &val_up, const vec &cond_up ) { 
     295                vec tmp(csize); 
     296                set_subvector(tmp,v2c_lo,val_up(v2c_up)); 
     297                set_subvector(tmp,c2c_lo,cond_up(c2c_up)); 
     298                return tmp; 
     299        } 
     300        //! Fill  
     301 
     302}; 
     303 
     304/*! \brief Unconditional mpdf, allows using epdf in the role of mpdf. 
    247305 
    248306WARNING: the class does not check validity of the \c ep pointer nor its existence. 
     
    251309public: 
    252310        //!Default constructor 
    253         mepdf (epdf &em ) :mpdf ( em._rv(),RV() ) {ep=&em;}; 
    254         void condition(const vec &cond){} 
    255 }; 
    256  
    257 //!\brief Abstract composition of pdfs, a base for specific classes  
    258 class compositepdf{ 
    259         protected: 
    260                 //!Number of mpdfs in the composite 
    261                 int n; 
    262                 //! Elements of composition 
    263                 Array<mpdf*> mpdfs; 
    264                 //! Indeces of rvs in common rv 
    265                 Array<ivec> rvsinrv; 
    266                 //! Indeces of rvc in common rv 
    267                 Array<ivec> irvcs_rv; 
    268                 //! Indeces of common rv in rvc 
    269                 Array<ivec> irv_rvcs; 
    270         public: 
    271                 compositepdf(Array<mpdf*> A0): n(A0.length()), mpdfs(A0), rvsinrv(n), irvcs_rv(n),irv_rvcs(n){}; 
    272                 //! find common rv, flag \param checkoverlap modifies whether overlaps are acceptable 
    273                 RV getrv(bool checkoverlap=false); 
    274                 //! common rvc of all mpdfs is written to rvc 
    275                 void setrvc(const RV &rv, RV &rvc); 
    276                 //! fill all rv*inrv* according to  
    277                 void setindices(const RV &rv); 
     311        mepdf ( epdf &em ) :mpdf ( em._rv(),RV() ) {ep=&em;}; 
     312        void condition ( const vec &cond ) {} 
     313}; 
     314 
     315//!\brief Abstract composition of pdfs, a base for specific classes 
     316class compositepdf { 
     317protected: 
     318        //!Number of mpdfs in the composite 
     319        int n; 
     320        //! Elements of composition 
     321        Array<mpdf*> mpdfs; 
     322        //! Indeces of rvs in common rv 
     323        Array<ivec> rvsinrv; 
     324        //! Indeces of rvc in common rv 
     325        Array<ivec> irvcs_rv; 
     326        //! Indeces of common rv in rvc 
     327        Array<ivec> irv_rvcs; 
     328public: 
     329        compositepdf ( Array<mpdf*> A0 ) : n ( A0.length() ), mpdfs ( A0 ), rvsinrv ( n ), irvcs_rv ( n ),irv_rvcs ( n ) {}; 
     330        //! find common rv, flag \param checkoverlap modifies whether overlaps are acceptable 
     331        RV getrv ( bool checkoverlap=false ); 
     332        //! common rvc of all mpdfs is written to rvc 
     333        void setrvc ( const RV &rv, RV &rvc ); 
     334        //! fill all rv*inrv* according to 
     335        void setindices ( const RV &rv ); 
    278336}; 
    279337 
     
    327385 
    328386        //!Default constructor 
    329         BM ( const RV &rv0, double ll0=0,bool evalll0=true ) :rv ( rv0 ), ll ( ll0 ),evalll ( evalll0) {//Fixme: test rv 
     387        BM ( const RV &rv0, double ll0=0,bool evalll0=true ) :rv ( rv0 ), ll ( ll0 ),evalll ( evalll0 ) {//Fixme: test rv 
    330388        }; 
    331389        //!Copy constructor 
    332         BM (const BM &B) : rv(B.rv), ll(B.ll), evalll(B.evalll) {} 
     390        BM ( const BM &B ) : rv ( B.rv ), ll ( B.ll ), evalll ( B.evalll ) {} 
    333391 
    334392        /*! \brief Incremental Bayes rule 
     
    337395        virtual void bayes ( const vec &dt ) = 0; 
    338396        //! Batch Bayes rule (columns of Dt are observations) 
    339         virtual void bayesB (const mat &Dt ); 
     397        virtual void bayesB ( const mat &Dt ); 
    340398        //! Returns a pointer to the epdf representing posterior density on parameters. Use with care! 
    341399        virtual const epdf& _epdf() const =0; 
     
    343401        //! Evaluates predictive log-likelihood of the given data record 
    344402        //! I.e. marginal likelihood of the data with the posterior integrated out. 
    345         virtual double logpred(const vec &dt)const{it_error("Not implemented");return 0.0;} 
     403        virtual double logpred ( const vec &dt ) const{it_error ( "Not implemented" );return 0.0;} 
    346404        //! Matrix version of logpred 
    347         vec logpred_m(const mat &dt)const{vec tmp(dt.cols());for(int i=0;i<dt.cols();i++){tmp(i)=logpred(dt.get_col(i));}return tmp;} 
    348          
     405        vec logpred_m ( const mat &dt ) const{vec tmp ( dt.cols() );for ( int i=0;i<dt.cols();i++ ) {tmp ( i ) =logpred ( dt.get_col ( i ) );}return tmp;} 
     406 
    349407        //!Constructs a predictive density (marginal density on data) 
    350         virtual epdf* predictor(const RV &rv){it_error("Not implemented");return NULL;}; 
    351          
     408        virtual epdf* predictor ( const RV &rv ) {it_error ( "Not implemented" );return NULL;}; 
     409 
    352410        //! Destructor for future use; 
    353411        virtual ~BM() {}; 
     
    356414        //!access function 
    357415        double _ll() const {return ll;} 
    358         //!access function  
    359         void set_evalll(bool evl0){evalll=evl0;} 
    360          
     416        //!access function 
     417        void set_evalll ( bool evl0 ) {evalll=evl0;} 
     418 
    361419        //! Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually! 
    362420        //! Prototype: BM* _copy_(){BM Tmp*=new Tmp(this*);  return Tmp; } 
    363         virtual BM* _copy_(bool changerv=false){it_error("function _copy_ not implemented for this BM"); return NULL;}; 
     421        virtual BM* _copy_ ( bool changerv=false ) {it_error ( "function _copy_ not implemented for this BM" ); return NULL;}; 
    364422}; 
    365423 
  • matlab/merger_iter_debug.m

    r184 r190  
    33ndat = 1000; % check if true! 
    44 
     5XL = [-1 4]; 
     6YL= XL; 
     7 
    58figure(1); 
    6 for it=0:6 
     9for it=0:20 
    710    figure(it+1) 
    811    subplot(2,2,1); 
    9     hold off 
    1012    si = num2str(it); 
    11     eval(['plot3(Smp' si '(1,:),Smp' si '(2,:),exp(Mpdf' si '),''r.'')']); 
    12     if i==0, title('Proposal & mix'); end 
    13     set(gca,'XLim',[-10,10]); 
     13    eval(['contour_2(Smp' si '(1,:),Smp' si '(2,:),exp(Mpdf' si '))']); 
     14    title('Proposal density '); 
     15    set(gca,'XLim',XL); 
     16    set(gca,'YLim',YL); 
    1417         
    1518    subplot(2,2,2); 
    16     hold off 
    1719    eval(['contour_2(Smp' si '(1,:),Smp' si '(2,:),exp(lW' si '(1,:)))']); 
    18 %    hold on 
    19 %    eval(['plot3(Smp' si '(1,:),Smp' si '(2,:),w' si ',''r.'')']); 
    20     if i==0, title('Weighed Smp'); end 
     20    title('First source');  
     21    set(gca,'XLim',XL); 
     22    set(gca,'YLim',YL); 
    2123     
    2224    subplot(2,2,3); 
    23     hold off 
    2425    eval(['contour_2(Smp' si '(1,:),Smp' si '(2,:),exp(lW' si '(2,:)))']); 
    25 %    eval(['plot3(Smp' si '(1,:),Smp' si '(2,:),w' si ',''.'')']); 
    26 %    hold on 
    27 %    eval(['plot3(Smp' si '(1,:),Smp' si '(2,:),w_is_' si ',''r.'')']); 
    28     if i==0, title('Weighed Smp'); end 
     26    title('Second source'); 
     27    set(gca,'XLim',XL); 
     28    set(gca,'YLim',YL); 
    2929     
    3030     
    3131    subplot(2,2,4); 
    3232    eval(['contour_2(Smp' si '(1,:),Smp' si '(2,:),w' si ')']); 
    33     if i==0, title('Resampled hist'); end 
     33    title('Merged density');  
     34    set(gca,'XLim',XL); 
     35    set(gca,'YLim',YL); 
    3436     
    35   %  keyboard 
    3637end 
    3738 
     
    4344figure(it+2); 
    4445M1 = reshape(exp(Res1),Npoints,Npoints); 
    45 contour(XG,YG,M1); 
     46contour(XG,YG,M1,7); 
    4647 
    4748figure(it+3); 
    48 M2 = reshape(exp(Res2),Npoints,Npoints); 
    49 contour(XG,YG,M2); 
    50  
    51 figure(it+4); 
    52 L1 = reshape(exp(lf1),Npoints,Npoints); 
    53 contour(XG,YG,L1); 
     49hold off 
     50mm = max(max(Res2)); 
     51for i=1:size(Res2,1) 
     52    M2 = reshape(Res2(i,:),Npoints,Npoints); 
     53    contour(XG,YG,M2,[0:mm/7:mm]); 
     54    hold on 
     55end 
  • tests/CMakeLists.txt

    r182 r190  
    2626# BASIC TESTS 
    2727TEST(rv_test) 
     28TEST(datalink_test) 
    2829TEST(loggers_test) 
    2930 
  • tests/merger_iter_test.cpp

    r188 r190  
    1111int main() { 
    1212 
     13        RNG_randomize(); 
     14         
    1315        RV x ( "{x }","1" ); 
    1416        RV y ( "{y }","1" ); 
     
    1618        RV xy=x; xy.add(y); 
    1719         
    18 //      enorm<fsqmat> f1 ( xy ); 
    19 //      enorm<fsqmat> f2 ( x ); 
    20  
    21         enorm<ldmat> f(xy); 
    22         f.set_parameters ( "1 1",mat ( "1.2 1; 1 1.2" ) ); 
    23          
    24         mpdf* f1=f.condition(x); 
    25         mpdf* f2=f.condition(y); 
    26         cout << *(mlnorm<ldmat>*)f1 <<endl; 
    27         cout << *(mlnorm<ldmat>*)f2 <<endl; 
    28          
    29 //      f1.set_parameters ( "1 1",mat ( "1.2 1; 1 1.2" ) ); 
    30 //      f2.set_parameters ( "2",mat ( "20" ) ); 
     20        enorm<fsqmat> f1 ( xy ); 
     21        enorm<fsqmat> f2 ( x ); 
     22                 
     23        f1.set_parameters ( "0 0",mat ( "0.5 0; 0 0.5" ) ); 
     24        f2.set_parameters ( "3",mat ( "0.5" ) ); 
    3125         
    3226        Array<mpdf* > A ( 2 ); 
    33 /*      mepdf A1(f1); 
    34         mepdf A2(f2);*/ 
    35         A ( 0 ) =f1; 
    36         A ( 1 ) =f2; 
     27        mepdf A1(f1); 
     28        mepdf A2(f2); 
     29        A ( 0 ) =&A1; 
     30        A ( 1 ) =&A2; 
    3731         
    3832        int Npoints=100; 
     
    4842        merger M ( A ); 
    4943        enorm<fsqmat> g0(xy); 
    50         g0.set_parameters(vec("1 1"),mat("100 0; 0 100")); 
     44        g0.set_parameters(vec("1 1"),mat("1 0; 0 1")); 
    5145         
    52         M.set_parameters(1.2,200,1); 
     46        M.set_parameters(1.2,200,2); 
    5347        M.merge(&g0); 
    5448         
     
    5751         
    5852        vec Res1 = M.evalpdflog_m(Grid); 
    59         vec Res2 = MP->evalpdflog_m(Grid); 
     53        mat Res2 = ((emix*)MP)->evalpdflog_M(Grid); 
    6054         
    6155        it_file it("merger_iter_test.it");