Changeset 190
- Timestamp:
- 10/22/08 10:46:38 (16 years ago)
- Files:
-
- 1 added
- 6 modified
Legend:
- Unmodified
- Added
- Removed
-
bdm/estim/merger.cpp
r186 r190 33 33 vec &w = eSmp._w(); //aux 34 34 35 mat Smp_ex =ones ( rv.count() +1,Ns ); // Extended samples The last row is ones for the ARX model35 mat Smp_ex =ones ( rv.count() +1,Ns ); // Extended samples for the ARX model - the last row is ones 36 36 for ( int i=0;i<Ns;i++ ) { set_col_part ( Smp_ex,i,Smp ( i ) );} 37 37 … … 49 49 V0, rv.count() *rv.count() +3.0 ); //initial guess of Mix: zero mean, large variance 50 50 51 52 53 51 // ============= MAIN LOOP ================== 54 52 bool converged=false; … … 62 60 //Re-Initialize Mixture model 63 61 Mix.init ( &A0, Smp_ex, Nc ); 64 Mix.bayesB ( Smp_ex );62 Mix.bayesB ( Smp_ex, ones(Ns));//w*Ns ); 65 63 Mpred = Mix.predictor(rv); // Allocation => must be deleted at the end!! 66 64 … … 152 150 // ==== stopping rule === 153 151 niter++; 154 converged = ( niter> 6);152 converged = ( niter>20); 155 153 } 156 154 -
bdm/estim/merger.h
r182 r190 41 41 compositepdf ( S ), epdf ( getrv ( false ) ), 42 42 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);} 44 44 //! Set internal parameters used in approximation 45 45 void set_parameters ( double beta0, int Ns0, int Nc0 ) { beta=beta0;Ns=Ns0;Nc=Nc0;} -
bdm/stat/libBM.h
r183 r190 15 15 16 16 #include <itpp/itbase.h> 17 #include "../itpp_ext.h" 17 18 //#include <std> 18 19 … … 20 21 21 22 //! Structure of RV (used internally), i.e. expanded RVs 22 class str {23 class str { 23 24 public: 24 25 //! vector id ids (non-unique!) … … 27 28 ivec times; 28 29 //!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" ); 31 32 }; 32 33 }; … … 55 56 private: 56 57 //! 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 ); 59 public: 60 //! Full constructor 60 61 RV ( Array<std::string> in_names, ivec in_sizes, ivec in_times ); 61 62 //! Constructor with times=0 … … 77 78 78 79 //! 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; 80 81 //! Compare if \c rv2 is identical to this \c RV 81 bool equal ( const RV &rv2 ) const;82 bool equal ( const RV &rv2 ) const; 82 83 //! Add (concat) another variable to the current one, \return true if all rv2 were added, false if rv2 is in conflict 83 84 bool add ( const RV &rv2 ); … … 92 93 //! generate \c str from rv, by expanding sizes 93 94 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. 95 96 //! 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. 98 99 //! 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; 100 101 101 102 //!access function … … 110 111 //!access function 111 112 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 121 122 void newids(); 122 123 }; … … 164 165 // //! Returns the required moment of the epdf 165 166 // virtual vec moment ( const int order = 1 ); 166 167 167 168 //! Returns a sample, \f$x\f$ from density \f$epdf(rv)\f$ 168 169 virtual vec sample () const =0; … … 178 179 virtual vec evalpdflog_m ( const mat &Val ) const { 179 180 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 ) ) ;} 181 182 return x; 182 183 } 183 184 //! 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;} 185 186 //! 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;} 187 188 188 189 //! return expected value … … 194 195 const RV& _rv() const {return rv;} 195 196 //! 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;} 197 198 //! 198 199 }; … … 215 216 // virtual fnc moment ( const int order = 1 ); 216 217 //! 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 }; 220 223 //! 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 ) { 222 225 this->condition ( cond ); 223 mat temp ( rv.count(),N ); vec smp ( rv.count() ); 226 mat temp ( rv.count(),N ); vec smp ( rv.count() ); 224 227 for ( int i=0;i<N;i++ ) {smp=ep->sample() ;temp.set_col ( i, smp );ll ( i ) =ep->evalpdflog ( smp );} 225 228 return temp; 226 229 }; 227 230 //! 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" );}; 229 232 230 233 //! Shortcut for conditioning and evaluation of the internal epdf. In some cases, this operation can be implemented efficiently. … … 237 240 mpdf ( const RV &rv0, const RV &rvc0 ) :rv ( rv0 ),rvc ( rvc0 ) {}; 238 241 //! access function 239 RV _rvc() {return rvc;}242 RV _rvc() const {return rvc;} 240 243 //! access function 241 RV _rv() {return rv;}244 RV _rv() const {return rv;} 242 245 //!access function 243 246 epdf& _epdf() {return *ep;} 244 247 }; 245 248 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" 251 class datalink { 252 protected: 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 271 class datalink_mpdf: public datalink { 272 protected: 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; 283 public: 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. 247 305 248 306 WARNING: the class does not check validity of the \c ep pointer nor its existence. … … 251 309 public: 252 310 //!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 260 261 262 263 264 265 266 267 268 269 270 271 compositepdf(Array<mpdf*> A0): n(A0.length()), mpdfs(A0), rvsinrv(n), irvcs_rv(n),irv_rvcs(n){};272 273 RV getrv(bool checkoverlap=false);274 275 void setrvc(const RV &rv, RV &rvc);276 //! fill all rv*inrv* according to277 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 316 class compositepdf { 317 protected: 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; 328 public: 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 ); 278 336 }; 279 337 … … 327 385 328 386 //!Default constructor 329 BM ( const RV &rv0, double ll0=0,bool evalll0=true ) :rv ( rv0 ), ll ( ll0 ),evalll ( evalll0 ) {//Fixme: test rv387 BM ( const RV &rv0, double ll0=0,bool evalll0=true ) :rv ( rv0 ), ll ( ll0 ),evalll ( evalll0 ) {//Fixme: test rv 330 388 }; 331 389 //!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 ) {} 333 391 334 392 /*! \brief Incremental Bayes rule … … 337 395 virtual void bayes ( const vec &dt ) = 0; 338 396 //! Batch Bayes rule (columns of Dt are observations) 339 virtual void bayesB ( const mat &Dt );397 virtual void bayesB ( const mat &Dt ); 340 398 //! Returns a pointer to the epdf representing posterior density on parameters. Use with care! 341 399 virtual const epdf& _epdf() const =0; … … 343 401 //! Evaluates predictive log-likelihood of the given data record 344 402 //! 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;} 346 404 //! 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 349 407 //!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 352 410 //! Destructor for future use; 353 411 virtual ~BM() {}; … … 356 414 //!access function 357 415 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 361 419 //! Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually! 362 420 //! 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;}; 364 422 }; 365 423 -
matlab/merger_iter_debug.m
r184 r190 3 3 ndat = 1000; % check if true! 4 4 5 XL = [-1 4]; 6 YL= XL; 7 5 8 figure(1); 6 for it=0: 69 for it=0:20 7 10 figure(it+1) 8 11 subplot(2,2,1); 9 hold off10 12 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); 14 17 15 18 subplot(2,2,2); 16 hold off17 19 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'); end20 title('First source'); 21 set(gca,'XLim',XL); 22 set(gca,'YLim',YL); 21 23 22 24 subplot(2,2,3); 23 hold off24 25 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); 29 29 30 30 31 31 subplot(2,2,4); 32 32 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); 34 36 35 % keyboard36 37 end 37 38 … … 43 44 figure(it+2); 44 45 M1 = reshape(exp(Res1),Npoints,Npoints); 45 contour(XG,YG,M1 );46 contour(XG,YG,M1,7); 46 47 47 48 figure(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); 49 hold off 50 mm = max(max(Res2)); 51 for i=1:size(Res2,1) 52 M2 = reshape(Res2(i,:),Npoints,Npoints); 53 contour(XG,YG,M2,[0:mm/7:mm]); 54 hold on 55 end -
tests/CMakeLists.txt
r182 r190 26 26 # BASIC TESTS 27 27 TEST(rv_test) 28 TEST(datalink_test) 28 29 TEST(loggers_test) 29 30 -
tests/merger_iter_test.cpp
r188 r190 11 11 int main() { 12 12 13 RNG_randomize(); 14 13 15 RV x ( "{x }","1" ); 14 16 RV y ( "{y }","1" ); … … 16 18 RV xy=x; xy.add(y); 17 19 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" ) ); 31 25 32 26 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; 37 31 38 32 int Npoints=100; … … 48 42 merger M ( A ); 49 43 enorm<fsqmat> g0(xy); 50 g0.set_parameters(vec("1 1"),mat("1 00 0; 0 100"));44 g0.set_parameters(vec("1 1"),mat("1 0; 0 1")); 51 45 52 M.set_parameters(1.2,200, 1);46 M.set_parameters(1.2,200,2); 53 47 M.merge(&g0); 54 48 … … 57 51 58 52 vec Res1 = M.evalpdflog_m(Grid); 59 vec Res2 = MP->evalpdflog_m(Grid);53 mat Res2 = ((emix*)MP)->evalpdflog_M(Grid); 60 54 61 55 it_file it("merger_iter_test.it");