Changeset 737 for library/bdm/base
- Timestamp:
- 11/25/09 12:14:38 (15 years ago)
- Location:
- library/bdm/base
- Files:
-
- 8 modified
Legend:
- Unmodified
- Added
- Removed
-
library/bdm/base/bdmbase.cpp
r733 r737 19 19 } 20 20 21 string RV::show_all() {22 23 for(str2int_map::const_iterator iter=MAP.begin(); iter!=MAP.end(); iter++){24 os << "key: " << iter->first << " val: " << iter->second <<endl;25 26 21 string RV::show_all() { 22 ostringstream os; 23 for ( str2int_map::const_iterator iter = MAP.begin(); iter != MAP.end(); iter++ ) { 24 os << "key: " << iter->first << " val: " << iter->second << endl; 25 } 26 return os.str(); 27 27 }; 28 28 … … 31 31 int id; 32 32 str2int_map::const_iterator iter = MAP.find ( name ); 33 if ( iter == MAP.end() || name.length() ==0) { //add new RV33 if ( iter == MAP.end() || name.length() == 0 ) { //add new RV 34 34 id = MAP.size() + 1; 35 35 //debug … … 49 49 NAMES ( id ) = name; 50 50 SIZES ( id ) = size; 51 bdm_assert (size>0, "RV "+ name +" does not exists. Default size (-1) can not be assigned ");51 bdm_assert ( size > 0, "RV " + name + " does not exists. Default size (-1) can not be assigned " ); 52 52 } else { 53 53 id = iter->second; 54 if ( size>0 && name.length()>0){55 bdm_assert ( SIZES ( id ) == size, "RV " + name + " of size " + num2str (SIZES(id)) + " exists, requested size " + num2str(size) + "can not be assigned" );54 if ( size > 0 && name.length() > 0 ) { 55 bdm_assert ( SIZES ( id ) == size, "RV " + name + " of size " + num2str ( SIZES ( id ) ) + " exists, requested size " + num2str ( size ) + "can not be assigned" ); 56 56 } 57 57 } … … 368 368 369 369 void RV::to_setting ( Setting &set ) const { 370 Array<string> names(len); 371 ivec sizes(len); 372 for (int i=0; i<len;i++){names(i)=name(i);sizes(i)=size(i);} 373 UI::save(names,set,"names"); 374 UI::save(sizes,set,"sizes"); 375 UI::save(times,set,"times"); 370 Array<string> names ( len ); 371 ivec sizes ( len ); 372 for ( int i = 0; i < len; i++ ) { 373 names ( i ) = name ( i ); 374 sizes ( i ) = size ( i ); 375 } 376 UI::save ( names, set, "names" ); 377 UI::save ( sizes, set, "sizes" ); 378 UI::save ( times, set, "times" ); 376 379 } 377 380 … … 402 405 void BM::bayes_batch ( const mat &Data, const mat &Cond ) { 403 406 for ( int t = 0; t < Data.cols(); t++ ) { 404 bayes ( Data.get_col ( t ), Cond.get_col (t) );405 } 406 } 407 } 407 bayes ( Data.get_col ( t ), Cond.get_col ( t ) ); 408 } 409 } 410 } -
library/bdm/base/bdmbase.h
r733 r737 149 149 friend std::ostream &operator<< ( std::ostream &os, const RV &rv ); 150 150 151 string to_string() const {ostringstream o; o << *this; return o.str();} 152 151 string to_string() const { 152 ostringstream o; 153 o << *this; 154 return o.str(); 155 } 156 153 157 //! total size of a random variable 154 158 int _dsize() const { … … 183 187 //! returns name of a scalar at position scalat, i.e. it can be in the middle of vector name, in that case it adds "_%d" to it 184 188 std::string scalarname ( int scalat ) const { 185 bdm_assert(scalat<dsize,"Wrong input index"); 186 int id=0; 187 int scalid=0; 188 while (scalid+SIZES(ids(id))<=scalat) { scalid+=SIZES(ids(id)); id++;}; 189 bdm_assert ( scalat < dsize, "Wrong input index" ); 190 int id = 0; 191 int scalid = 0; 192 while ( scalid + SIZES ( ids ( id ) ) <= scalat ) { 193 scalid += SIZES ( ids ( id ) ); 194 id++; 195 }; 189 196 //now id is the id of variable of interest 190 if ( size(id)==1)197 if ( size ( id ) == 1 ) 191 198 return NAMES ( ids ( id ) ); 192 199 else 193 return NAMES ( ids ( id ) ) + "_" + num2str(scalat-scalid);200 return NAMES ( ids ( id ) ) + "_" + num2str ( scalat - scalid ); 194 201 195 202 } … … 233 240 } 234 241 //! create new RV from the current one with time shifted by given value 235 RV copy_t (int dt) const {236 RV tmp =*this;237 tmp.t_plus (dt);242 RV copy_t ( int dt ) const { 243 RV tmp = *this; 244 tmp.t_plus ( dt ); 238 245 return tmp; 239 246 } … … 266 273 //! Minimum time-offset 267 274 int mint() const { 268 return times.length() >0 ? min (times) : 0;275 return times.length() > 0 ? min ( times ) : 0; 269 276 } 270 277 //! Minimum time-offset of ids of given RVs 271 int mint (const RV &rv) const {272 bvec belong =zeros_b(len);273 for ( int r=0; r<rv.length(); r++){274 belong = belong | ( ids == rv.id(r));275 } 276 return times.length() >0 ? min (get_from_bvec(times,belong)) : 0;278 int mint ( const RV &rv ) const { 279 bvec belong = zeros_b ( len ); 280 for ( int r = 0; r < rv.length(); r++ ) { 281 belong = belong | ( ids == rv.id ( r ) ); 282 } 283 return times.length() > 0 ? min ( get_from_bvec ( times, belong ) ) : 0; 277 284 } 278 285 //!@} … … 281 288 282 289 \code 283 class = 'RV'; 290 class = 'RV'; 284 291 names = {'a', 'b', 'c', ...}; // UNIQUE IDENTIFIER same names = same variable 285 // names are also used when storing results 292 // names are also used when storing results 286 293 --- optional --- 287 294 sizes = [1, 2, 3, ...]; // size of each name. default = ones() … … 292 299 void from_setting ( const Setting &set ); 293 300 294 void to_setting ( Setting &set ) const;301 void to_setting ( Setting &set ) const; 295 302 296 303 //! Invalidate all named RVs. Use before initializing any RV instances, with care... … … 312 319 */ 313 320 class logger : public root { 314 protected: 315 //! RVs of all logged variables. 316 Array<RV> entries; 317 //! Names of logged quantities, e.g. names of algorithm variants 318 Array<string> names; 319 //!separator of prefixes of entries 320 const string separator; 321 //! Root Setting for storing Settings 322 Config setting_conf; 323 //! list of Settings for specific ids 324 Array<Setting*> settings; 325 public: 326 //!Default constructor 327 logger(const string separator0) : entries ( 0 ), names ( 0 ), separator(separator0) {} 328 329 //! returns an identifier which will be later needed for calling the \c logit() function 330 //! For empty RV it returns -1, this entry will be ignored by \c logit(). 331 virtual int add_vector ( const RV &rv, string prefix = "" ) { 332 int id; 333 if ( rv._dsize() > 0 ) { 334 id = entries.length(); 335 names = concat ( names, prefix ); // diff 336 entries.set_length ( id + 1, true ); 337 entries ( id ) = rv; 338 } else { 339 id = -1; 340 } 341 return id; // identifier of the last entry 342 } 343 virtual int add_setting(const string &prefix){ 344 Setting &root=setting_conf.getRoot(); 345 int id=root.getLength(); //root must be group!! 346 if (prefix.length()>0){ 347 settings.set_length(id+1,true); 348 settings(id) = &root.add(prefix, Setting::TypeList); 349 } else {id=-1;} 350 return id; 351 } 352 353 //! log this vector 354 virtual void log_vector ( int id, const vec &v ) { 355 bdm_error ( "Not implemented" ); 356 }; 357 358 virtual Setting & log_to_setting (int id){ 359 return settings(id)->add(Setting::TypeGroup); 360 } 361 362 //! log this double 363 virtual void logit ( int id, const double &d ) { 364 bdm_error ( "Not implemented" ); 365 }; 366 367 //! Shifts storage position for another time step. 368 virtual void step() { 369 bdm_error ( "Not implemneted" ); 370 }; 371 372 //! Finalize storing information 373 virtual void finalize() {}; 374 375 //! Initialize the storage 376 virtual void init() {}; 377 378 //!separator of prefixes for this logger 379 const string& prefix_sep() {return separator;} 321 protected: 322 //! RVs of all logged variables. 323 Array<RV> entries; 324 //! Names of logged quantities, e.g. names of algorithm variants 325 Array<string> names; 326 //!separator of prefixes of entries 327 const string separator; 328 //! Root Setting for storing Settings 329 Config setting_conf; 330 //! list of Settings for specific ids 331 Array<Setting*> settings; 332 public: 333 //!Default constructor 334 logger ( const string separator0 ) : entries ( 0 ), names ( 0 ), separator ( separator0 ) {} 335 336 //! returns an identifier which will be later needed for calling the \c logit() function 337 //! For empty RV it returns -1, this entry will be ignored by \c logit(). 338 virtual int add_vector ( const RV &rv, string prefix = "" ) { 339 int id; 340 if ( rv._dsize() > 0 ) { 341 id = entries.length(); 342 names = concat ( names, prefix ); // diff 343 entries.set_length ( id + 1, true ); 344 entries ( id ) = rv; 345 } else { 346 id = -1; 347 } 348 return id; // identifier of the last entry 349 } 350 virtual int add_setting ( const string &prefix ) { 351 Setting &root = setting_conf.getRoot(); 352 int id = root.getLength(); //root must be group!! 353 if ( prefix.length() > 0 ) { 354 settings.set_length ( id + 1, true ); 355 settings ( id ) = &root.add ( prefix, Setting::TypeList ); 356 } else { 357 id = -1; 358 } 359 return id; 360 } 361 362 //! log this vector 363 virtual void log_vector ( int id, const vec &v ) { 364 bdm_error ( "Not implemented" ); 365 }; 366 367 virtual Setting & log_to_setting ( int id ) { 368 return settings ( id )->add ( Setting::TypeGroup ); 369 } 370 371 //! log this double 372 virtual void logit ( int id, const double &d ) { 373 bdm_error ( "Not implemented" ); 374 }; 375 376 //! Shifts storage position for another time step. 377 virtual void step() { 378 bdm_error ( "Not implemneted" ); 379 }; 380 381 //! Finalize storing information 382 virtual void finalize() {}; 383 384 //! Initialize the storage 385 virtual void init() {}; 386 387 //!separator of prefixes for this logger 388 const string& prefix_sep() { 389 return separator; 390 } 380 391 }; 381 392 … … 429 440 //! @{ 430 441 431 pdf() : dimc ( 0 ), rvc(), dim (0), rv() { }432 433 pdf ( const pdf &m ) : dimc ( m.dimc ), rvc ( m.rvc ), dim ( m.dim), rv( m.rv ) { }434 442 pdf() : dimc ( 0 ), rvc(), dim ( 0 ), rv() { } 443 444 pdf ( const pdf &m ) : dimc ( m.dimc ), rvc ( m.rvc ), dim ( m.dim ), rv ( m.rv ) { } 445 435 446 //! copy of the current object - make sure to implement 436 virtual pdf* _copy_() const {return new pdf(*this);} 447 virtual pdf* _copy_() const { 448 return new pdf ( *this ); 449 } 437 450 //!@} 438 451 … … 488 501 489 502 //! access function 490 void set_dim(int d) {dim=d;} 503 void set_dim ( int d ) { 504 dim = d; 505 } 491 506 //! access function 492 void set_dimc(int d) {dimc=d;} 507 void set_dimc ( int d ) { 508 dimc = d; 509 } 493 510 //! Load from structure with elements: 494 511 //! \code … … 535 552 @{*/ 536 553 epdf() {}; 537 epdf ( const epdf &e ) : pdf (e) {};554 epdf ( const epdf &e ) : pdf ( e ) {}; 538 555 void set_parameters ( int dim0 ) { 539 556 dim = dim0; 540 557 } 541 epdf* _copy_() const {return new epdf(*this);} 558 epdf* _copy_() const { 559 return new epdf ( *this ); 560 } 542 561 //!@} 543 562 … … 603 622 //! #1 mean 604 623 //! #2 mean + lower & upper bound 605 void log_register (logger &L, const string &prefix){624 void log_register ( logger &L, const string &prefix ) { 606 625 RV r; 607 626 if ( isnamed() ) { … … 610 629 r = RV ( "", dimension() ); 611 630 }; 612 root::log_register (L,prefix);613 631 root::log_register ( L, prefix ); 632 614 633 // log full data 615 if ( log_level==10) {616 logrec->ids.set_size (1);617 logrec->ids (0) = logrec->L.add_setting(prefix);634 if ( log_level == 10 ) { 635 logrec->ids.set_size ( 1 ); 636 logrec->ids ( 0 ) = logrec->L.add_setting ( prefix ); 618 637 } else { 619 // log only 620 logrec->ids.set_size (3);621 if ( log_level >0){622 logrec->ids (0) = logrec->L.add_vector ( r, prefix + logrec->L.prefix_sep()+ "mean" );638 // log only 639 logrec->ids.set_size ( 3 ); 640 if ( log_level > 0 ) { 641 logrec->ids ( 0 ) = logrec->L.add_vector ( r, prefix + logrec->L.prefix_sep() + "mean" ); 623 642 } 624 if ( log_level >1){625 logrec->ids (1) = logrec->L.add_vector ( r, prefix + logrec->L.prefix_sep()+ "lb" );626 logrec->ids (2) = logrec->L.add_vector ( r, prefix + logrec->L.prefix_sep()+ "ub" );643 if ( log_level > 1 ) { 644 logrec->ids ( 1 ) = logrec->L.add_vector ( r, prefix + logrec->L.prefix_sep() + "lb" ); 645 logrec->ids ( 2 ) = logrec->L.add_vector ( r, prefix + logrec->L.prefix_sep() + "ub" ); 627 646 } 628 647 } 629 648 } 630 649 void log_write() const { 631 if ( log_level==10){632 to_setting (logrec->L.log_to_setting(logrec->ids(0)));650 if ( log_level == 10 ) { 651 to_setting ( logrec->L.log_to_setting ( logrec->ids ( 0 ) ) ); 633 652 } else { 634 if ( log_level>0) {635 logrec->L.log_vector ( logrec->ids(0), mean() );653 if ( log_level > 0 ) { 654 logrec->L.log_vector ( logrec->ids ( 0 ), mean() ); 636 655 } 637 if (log_level>1) { 638 vec lb; vec ub; 639 qbounds(lb,ub); 640 logrec->L.log_vector( logrec->ids(1), lb ); 641 logrec->L.log_vector( logrec->ids(2), ub ); 656 if ( log_level > 1 ) { 657 vec lb; 658 vec ub; 659 qbounds ( lb, ub ); 660 logrec->L.log_vector ( logrec->ids ( 1 ), lb ); 661 logrec->L.log_vector ( logrec->ids ( 2 ), ub ); 642 662 } 643 663 } … … 704 724 //! Efficient version of samplecond 705 725 virtual mat samplecond_mat ( const vec &cond, int N ); 706 726 707 727 void validate() { 708 728 iepdf.validate(); 709 if (rv._dsize()< iepdf._rv()._dsize()) {rv=iepdf._rv();}; 729 if ( rv._dsize() < iepdf._rv()._dsize() ) { 730 rv = iepdf._rv(); 731 }; 710 732 dim = iepdf.dimension(); 711 733 } … … 789 811 } 790 812 //! for future use 791 virtual ~datalink() {}813 virtual ~datalink() {} 792 814 }; 793 815 … … 829 851 if ( v2h_up.length() > 0 ) { 830 852 history.shift_right ( 0, v2h_up.length() ); 831 history.set_subvector ( 0, val_up(v2h_up) );853 history.set_subvector ( 0, val_up ( v2h_up ) ); 832 854 } 833 855 } … … 854 876 ivec valid_ids = rv.findself_ids ( rv_up ); 855 877 RV rv_hist = rv.subselect ( find ( valid_ids >= 0 ) ); // select only rvs that are in rv_up 856 RV rv_hist0 = rv_hist.remove_time();// these RVs will form history at time =0878 RV rv_hist0 = rv_hist.remove_time(); // these RVs will form history at time =0 857 879 // now we need to know what is needed from Up 858 880 rv_hist = rv_hist.expand_delayes(); // full regressor - including time 0 859 Hrv =rv_hist.subt(rv_hist0); // remove time 0881 Hrv = rv_hist.subt ( rv_hist0 ); // remove time 0 860 882 history = zeros ( Hrv._dsize() ); 861 883 862 884 // decide if we need to copy val to history 863 if ( Hrv._dsize() >0) {864 v2h_up = rv_hist0.dataind (rv_up); // indeces of elements of rv_up to be copied885 if ( Hrv._dsize() > 0 ) { 886 v2h_up = rv_hist0.dataind ( rv_up ); // indeces of elements of rv_up to be copied 865 887 } // else v2h_up is empty 866 888 867 889 Hrv.dataind ( rv, h2v_hist, h2v_down ); 868 890 … … 871 893 } 872 894 //! set history of variable given by \c rv1 to values of \c hist. 873 void set_history (const RV& rv1, const vec &hist0){874 bdm_assert (rv1._dsize()==hist0.length(),"hist is not compatible with given rv1");895 void set_history ( const RV& rv1, const vec &hist0 ) { 896 bdm_assert ( rv1._dsize() == hist0.length(), "hist is not compatible with given rv1" ); 875 897 ivec ind_H; 876 898 ivec ind_h0; 877 Hrv.dataind (rv1, ind_H, ind_h0); // find indeces of rv in878 set_subvector (history, ind_H, hist0(ind_h0)); // copy given hist to appropriate places899 Hrv.dataind ( rv1, ind_H, ind_h0 ); // find indeces of rv in 900 set_subvector ( history, ind_H, hist0 ( ind_h0 ) ); // copy given hist to appropriate places 879 901 } 880 902 }; … … 957 979 vec get_cond ( const vec &val_up, const vec &cond_up ) { 958 980 vec tmp ( condsize ); 959 fill_cond ( val_up, cond_up, tmp );981 fill_cond ( val_up, cond_up, tmp ); 960 982 return tmp; 961 983 } 962 //! fill condition 963 void fill_cond ( const vec &val_up, const vec &cond_up, vec& cond_out ){964 bdm_assert_debug (cond_out.length()>=condsize,"dl.fill_cond: cond_out is too small");984 //! fill condition 985 void fill_cond ( const vec &val_up, const vec &cond_up, vec& cond_out ) { 986 bdm_assert_debug ( cond_out.length() >= condsize, "dl.fill_cond: cond_out is too small" ); 965 987 set_subvector ( cond_out, v2c_lo, val_up ( v2c_up ) ); 966 988 set_subvector ( cond_out, c2c_lo, cond_up ( c2c_up ) ); … … 976 998 /*! \brief Abstract class for discrete-time sources of data. 977 999 978 The class abstracts operations of: 979 \li data aquisition, 980 \li data-preprocessing, such as scaling of data, 1000 The class abstracts operations of: 1001 \li data aquisition, 1002 \li data-preprocessing, such as scaling of data, 981 1003 \li data resampling from the task of estimation and control. 982 1004 Moreover, for controlled systems, it is able to receive the desired control action and perform it in the next step. (Or as soon as possible). 983 1005 984 1006 The DataSource has three main data interaction structures: 985 \li input, \f$ u_t \f$, 1007 \li input, \f$ u_t \f$, 986 1008 \li output \f$ y_t \f$, 987 1009 \li data, \f$ d_t=[y_t,u_t, \ldots ]\f$ a collection of all inputs and outputs and possibly some internal variables too. … … 991 1013 class DS : public root { 992 1014 protected: 993 1015 //! size of data returned by \c getdata() 994 1016 int dtsize; 995 1017 //! size of data 996 1018 int utsize; 997 998 1019 //!size of output 1020 int ytsize; 999 1021 //!Description of data returned by \c getdata(). 1000 1022 RV Drv; 1001 1023 //!Description of data witten by by \c write(). 1002 1024 RV Urv; // 1003 1004 1025 //!Description of output data 1026 RV Yrv; // 1005 1027 public: 1006 1028 //! default constructors 1007 DS() : dtsize(0),utsize(0),ytsize(0),Drv(), Urv(),Yrv() {log_level=1;}; 1029 DS() : dtsize ( 0 ), utsize ( 0 ), ytsize ( 0 ), Drv(), Urv(), Yrv() { 1030 log_level = 1; 1031 }; 1008 1032 1009 1033 //! Returns maximum number of provided data, by default it is set to maximum allowed length, shorter DS should overload this method! See, MemDS.max_length(). 1010 virtual int max_length() {return std::numeric_limits< int >::max();} 1034 virtual int max_length() { 1035 return std::numeric_limits< int >::max(); 1036 } 1011 1037 //! Returns full vector of observed data=[output, input] 1012 1038 virtual void getdata ( vec &dt ) const { … … 1019 1045 1020 1046 //! Accepts action variable and schedule it for application. 1021 virtual void write ( const vec &ut ) {1047 virtual void write ( const vec &ut ) { 1022 1048 bdm_error ( "abstract class" ); 1023 1049 } 1024 1050 1025 1051 //! Accepts action variables at specific indeces 1026 virtual void write ( const vec &ut, const ivec &indeces ) {1052 virtual void write ( const vec &ut, const ivec &indeces ) { 1027 1053 bdm_error ( "abstract class" ); 1028 1054 } 1029 1055 1030 1056 //! Moves from \f$ t \f$ to \f$ t+1 \f$, i.e. perfroms the actions and reads response of the system. 1031 virtual void step() 1032 { 1057 virtual void step() { 1033 1058 bdm_error ( "abstract class" ); 1034 1059 } 1035 1060 1036 1061 //! Register DS for logging into logger L 1037 virtual void log_register ( logger &L, const string &prefix ) {1062 virtual void log_register ( logger &L, const string &prefix ) { 1038 1063 bdm_assert ( ytsize == Yrv._dsize(), "invalid DS: ytsize (" + num2str ( ytsize ) + ") different from Drv " + num2str ( Yrv._dsize() ) ); 1039 1064 bdm_assert ( utsize == Urv._dsize(), "invalid DS: utsize (" + num2str ( utsize ) + ") different from Urv " + num2str ( Urv._dsize() ) ); 1040 1065 1041 root::log_register (L,prefix);1042 //we know that 1043 if ( log_level >0){1044 logrec->ids.set_size (2);1045 logrec->ids (0) = logrec->L.add_vector ( Yrv, prefix );1046 logrec->ids (1) = logrec->L.add_vector ( Urv, prefix );1066 root::log_register ( L, prefix ); 1067 //we know that 1068 if ( log_level > 0 ) { 1069 logrec->ids.set_size ( 2 ); 1070 logrec->ids ( 0 ) = logrec->L.add_vector ( Yrv, prefix ); 1071 logrec->ids ( 1 ) = logrec->L.add_vector ( Urv, prefix ); 1047 1072 } 1048 1073 } 1049 1074 //! Register DS for logging into logger L 1050 1075 virtual void log_write ( ) const { 1051 if ( log_level >0) {1052 vec tmp ( Yrv._dsize() + Urv._dsize() );1076 if ( log_level > 0 ) { 1077 vec tmp ( Yrv._dsize() + Urv._dsize() ); 1053 1078 getdata ( tmp ); 1054 1079 // d is first in getdata 1055 logrec->L.log_vector ( logrec->ids (0), tmp.left ( Yrv._dsize() ) );1080 logrec->L.log_vector ( logrec->ids ( 0 ), tmp.left ( Yrv._dsize() ) ); 1056 1081 // u follows after d in getdata 1057 logrec->L.log_vector ( logrec->ids (1), tmp.mid ( Yrv._dsize(), Urv._dsize() ) );1082 logrec->L.log_vector ( logrec->ids ( 1 ), tmp.mid ( Yrv._dsize(), Urv._dsize() ) ); 1058 1083 } 1059 1084 } … … 1071 1096 } 1072 1097 //! set random variables 1073 virtual void set_drv ( const RV &yrv, const RV &urv) {1098 virtual void set_drv ( const RV &yrv, const RV &urv ) { 1074 1099 Yrv = yrv; 1075 Drv = concat (yrv,urv);1100 Drv = concat ( yrv, urv ); 1076 1101 Urv = urv; 1077 1102 } … … 1085 1110 \f] 1086 1111 where: 1087 * \f$ y_t \f$ is the variable 1112 * \f$ y_t \f$ is the variable 1088 1113 Access to the resulting posterior density is via function \c posterior(). 1089 1114 … … 1109 1134 //! size of the conditioning vector 1110 1135 int dimc; 1111 1136 1112 1137 //!Logarithm of marginalized data likelihood. 1113 1138 double ll; … … 1119 1144 //! @{ 1120 1145 1121 BM() : yrv(), dimy(0),rvc(),dimc(0), ll ( 0 ), evalll ( true ) { };1146 BM() : yrv(), dimy ( 0 ), rvc(), dimc ( 0 ), ll ( 0 ), evalll ( true ) { }; 1122 1147 // BM ( const BM &B ) : yrv ( B.yrv ), dimy(B.dimy), rvc ( B.rvc ),dimc(B.dimc), ll ( B.ll ), evalll ( B.evalll ) {} 1123 1148 //! \brief Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually! 1124 1149 //! Prototype: \code BM* _copy_() const {return new BM(*this);} \endcode 1125 virtual BM* _copy_() const { return NULL; }; 1150 virtual BM* _copy_() const { 1151 return NULL; 1152 }; 1126 1153 //!@} 1127 1154 … … 1132 1159 @param dt vector of input data 1133 1160 */ 1134 virtual void bayes ( const vec &yt, const vec &cond =empty_vec ) = 0;1161 virtual void bayes ( const vec &yt, const vec &cond = empty_vec ) = 0; 1135 1162 //! Batch Bayes rule (columns of Dt are observations) 1136 virtual void bayes_batch ( const mat &Dt, const vec &cond =empty_vec );1163 virtual void bayes_batch ( const mat &Dt, const vec &cond = empty_vec ); 1137 1164 //! Batch Bayes rule (columns of Dt are observations, columns of Cond are conditions) 1138 1165 virtual void bayes_batch ( const mat &Dt, const mat &Cond ); 1139 1166 //! Evaluates predictive log-likelihood of the given data record 1140 //! I.e. marginal likelihood of the data with the posterior integrated out. 1141 //! This function evaluates only \f$ y_t \f$, condition is assumed to be the last used in bayes(). 1167 //! I.e. marginal likelihood of the data with the posterior integrated out. 1168 //! This function evaluates only \f$ y_t \f$, condition is assumed to be the last used in bayes(). 1142 1169 //! See bdm::BM::predictor for conditional version. 1143 1170 virtual double logpred ( const vec &yt ) const { … … 1170 1197 //! \name Access to attributes 1171 1198 //!@{ 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1199 //! access function 1200 const RV& _rvc() const { 1201 return rvc; 1202 } 1203 //! access function 1204 int dimensionc() const { 1205 return dimc; 1206 } 1207 //! access function 1208 int dimensiony() const { 1209 return dimy; 1210 } 1211 //! access function 1212 int dimension() const { 1213 return posterior().dimension(); 1214 } 1215 //! access function 1189 1216 const RV& _yrv() const { 1190 1217 return yrv; … … 1196 1223 //! access to rv of the posterior 1197 1224 void set_rv ( const RV &rv ) { 1198 const_cast<epdf&> (posterior()).set_rv ( rv );1225 const_cast<epdf&> ( posterior() ).set_rv ( rv ); 1199 1226 } 1200 1227 //! access function 1201 1228 void set_dim ( int dim ) { 1202 const_cast<epdf&> (posterior()).set_dim ( dim );1229 const_cast<epdf&> ( posterior() ).set_dim ( dim ); 1203 1230 } 1204 1231 //! return internal log-likelihood of the last data vector … … 1220 1247 virtual void set_options ( const string &opt ) { 1221 1248 if ( opt.find ( "logfull" ) != string::npos ) { 1222 const_cast<epdf&> (posterior()).set_log_level(10) ;1249 const_cast<epdf&> ( posterior() ).set_log_level ( 10 ) ; 1223 1250 } else { 1224 1251 if ( opt.find ( "logbounds" ) != string::npos ) { 1225 const_cast<epdf&> (posterior()).set_log_level(2) ;1252 const_cast<epdf&> ( posterior() ).set_log_level ( 2 ) ; 1226 1253 } else { 1227 const_cast<epdf&> (posterior()).set_log_level(1) ;1254 const_cast<epdf&> ( posterior() ).set_log_level ( 1 ) ; 1228 1255 } 1229 1256 if ( opt.find ( "logll" ) != string::npos ) { … … 1238 1265 //! * x = level of the posterior (typically 0/1/2 for nothing/mean/bounds) 1239 1266 virtual void log_register ( logger &L, const string &prefix = "" ) { 1240 root::log_register (L,prefix);1241 1242 const_cast<epdf&> (posterior()).log_register(L, prefix+L.prefix_sep()+"apost");1243 1244 if ( (log_level) > 0){1245 logrec->ids.set_size (1);1246 logrec->ids (0) = L.add_vector(RV("",1), prefix+L.prefix_sep()+"ll");1267 root::log_register ( L, prefix ); 1268 1269 const_cast<epdf&> ( posterior() ).log_register ( L, prefix + L.prefix_sep() + "apost" ); 1270 1271 if ( ( log_level ) > 0 ) { 1272 logrec->ids.set_size ( 1 ); 1273 logrec->ids ( 0 ) = L.add_vector ( RV ( "", 1 ), prefix + L.prefix_sep() + "ll" ); 1247 1274 } 1248 1275 } … … 1250 1277 virtual void log_write ( ) const { 1251 1278 posterior().log_write(); 1252 if (log_level >0) { logrec->L.logit ( logrec->ids ( 0 ), ll );} 1279 if ( log_level > 0 ) { 1280 logrec->L.logit ( logrec->ids ( 0 ), ll ); 1281 } 1253 1282 } 1254 1283 //!@} … … 1264 1293 shared_ptr<RV> r3 = UI::build<RV> ( set, "rv", UI::optional ); 1265 1294 if ( r3 ) { 1266 set_rv (*r3);1267 } 1268 1295 set_rv ( *r3 ); 1296 } 1297 1269 1298 string opt; 1270 1299 if ( UI::get ( opt, set, "options", UI::optional ) ) { -
library/bdm/base/datasources.cpp
r695 r737 18 18 for ( i = 0; i < indeces.length(); i++ ) { 19 19 j = indeces ( i ); 20 dt ( i ) = Data ( rowid ( j ), time 20 dt ( i ) = Data ( rowid ( j ), time ); 21 21 } 22 22 } … … 28 28 } 29 29 30 void MemDS::set_drv ( const RV &drv, const RV &urv ) {30 void MemDS::set_drv ( const RV &drv, const RV &urv ) { 31 31 bdm_assert_debug ( drv._dsize() == rowid.length(), "MemDS::set_rvs incompatible drv" ); 32 32 bdm_assert_debug ( urv._dsize() == 0, "MemDS does not support urv." ); 33 33 34 DS::set_drv (drv,urv);34 DS::set_drv ( drv, urv ); 35 35 } 36 36 37 MemDS::MemDS ( mat &Dat, ivec &rowid0 ) : rowid ( rowid0 ) {37 MemDS::MemDS ( mat &Dat, ivec &rowid0 ) : rowid ( rowid0 ) { 38 38 bdm_assert_debug ( max ( rowid ) <= Dat.rows(), "MemDS rowid is too high for given Dat." ); 39 39 … … 45 45 // //shift history 46 46 // H.shift_right ( 0, dt_size ); 47 // 47 // 48 48 // H.set_subvector ( dt_size - utsize, U ); // write U after Drv 49 // 49 // 50 50 // //get regressor 51 51 // rgr = rgrlnk.pushdown ( H ); 52 52 // // Eval Y 53 53 // H.set_subvector ( 0, model.samplecond ( rgr ) ); 54 // 54 // 55 55 // } 56 // 56 // 57 57 // void ArxDS::from_setting ( const Setting &set ) { 58 58 // shared_ptr<RV> yrv = UI::build<RV> ( set, "y" , UI::compulsory ); 59 59 // shared_ptr<RV> urv = UI::build<RV> ( set, "u" , UI::compulsory ); 60 60 // shared_ptr<RV> rrv = UI::build<RV> ( set, "rgr" , UI::compulsory ); 61 // 61 // 62 62 // mat Th; 63 63 // UI::get ( Th, set, "theta", UI::compulsory ); 64 // 64 // 65 65 // vec mu0; 66 66 // if ( !UI::get ( mu0, set, "offset" ) ) 67 67 // mu0 = zeros ( yrv->_dsize() ); 68 // 68 // 69 69 // mat sqR; 70 70 // UI::get ( sqR, set, "r", UI::compulsory ); 71 71 // set_parameters ( Th, mu0, sqR ); 72 72 // set_drv ( *yrv, *urv, *rrv ); 73 // 73 // 74 74 // if ( set.exists ( "opt" ) ) 75 75 // set_options ( set["opt"] ); … … 118 118 time = 0; 119 119 //rowid and delays are ignored 120 rowid = linspace (0,Data.rows()-1);120 rowid = linspace ( 0, Data.rows() - 1 ); 121 121 set_drv ( *rvtmp, RV() ); 122 122 } … … 128 128 //todo test if IM->rvc contains IM->rv 129 129 //todo test if OM->rvc contains IM->rv 130 131 UI::get (xt,set,"x0",UI::optional);132 130 131 UI::get ( xt, set, "x0", UI::optional ); 132 133 133 // prepare urv 134 134 validate(); 135 135 } 136 136 137 void StateDS::validate() {138 Yrv = concat (OM->_rv() , IM->_rv()); // export also true state137 void StateDS::validate() { 138 Yrv = concat ( OM->_rv() , IM->_rv() ); // export also true state 139 139 ytsize = Yrv._dsize(); 140 141 RV tmp =concat(OM->_rvc(), IM->_rvc()); // what i not in rvc142 Urv = tmp.subt (Yrv); // remove dt,xt and143 Urv = Urv.subt (Yrv.copy_t(-1)); // remove dt,xt and144 utsize = Urv._dsize();145 146 set_drv (Yrv,Urv);140 141 RV tmp = concat ( OM->_rvc(), IM->_rvc() ); // what i not in rvc 142 Urv = tmp.subt ( Yrv ); // remove dt,xt and 143 Urv = Urv.subt ( Yrv.copy_t ( -1 ) ); // remove dt,xt and 144 utsize = Urv._dsize(); 145 146 set_drv ( Yrv, Urv ); 147 147 dtsize = utsize + ytsize; 148 148 149 149 dt.set_length ( dtsize ); 150 if ( xt.length()!= IM->dimension() ) {151 xt =zeros(IM->dimension());150 if ( xt.length() != IM->dimension() ) { 151 xt = zeros ( IM->dimension() ); 152 152 } 153 153 ut.set_length ( Urv._dsize() ); 154 154 155 155 //create data links 156 u2imc.set_connection (IM->_rvc(), Urv);157 u2omc.set_connection (OM->_rvc(), Urv);156 u2imc.set_connection ( IM->_rvc(), Urv ); 157 u2omc.set_connection ( OM->_rvc(), Urv ); 158 158 } -
library/bdm/base/datasources.h
r723 r737 28 28 */ 29 29 class MemDS : public DS { 30 protected: 31 //! internal matrix of data 32 mat Data; 33 //! active column in the Data matrix 34 int time; 35 //! vector of rows that are presented in Dt 36 ivec rowid; 37 38 public: 39 int max_length() {return Data.cols();} 40 void getdata ( vec &dt ) const; 41 void getdata ( vec &dt, const ivec &indeces ); 42 void set_drv (const RV &drv,const RV &urv ); 43 44 void write ( const vec &ut ) { 45 bdm_error ( "MemDS::write is not supported" ); 30 protected: 31 //! internal matrix of data 32 mat Data; 33 //! active column in the Data matrix 34 int time; 35 //! vector of rows that are presented in Dt 36 ivec rowid; 37 38 public: 39 int max_length() { 40 return Data.cols(); 41 } 42 void getdata ( vec &dt ) const; 43 void getdata ( vec &dt, const ivec &indeces ); 44 void set_drv ( const RV &drv, const RV &urv ); 45 46 void write ( const vec &ut ) { 47 bdm_error ( "MemDS::write is not supported" ); 48 } 49 50 void write ( const vec &ut, const ivec &indices ) { 51 bdm_error ( "MemDS::write is not supported" ); 52 } 53 54 void step(); 55 //!Default constructor 56 MemDS () {}; 57 //! Convenience constructor 58 MemDS ( mat &Dat, ivec &rowid0 ); 59 /*! Create object from the following structure 60 \code 61 { class = "MemDS"; 62 Data = (...); // Data matrix or data vector 63 --- optional --- 64 drv = {class="RV"; ...} // Identification how rows of the matrix Data will be known to others 65 time = 0; // Index of the first column to user_info, 66 rowid = [1,2,3...]; // ids of rows to be used 67 } 68 \endcode 69 70 If the optional fields are not given, they will be filled as follows: 71 \code 72 rowid= [0, 1, 2, ...number_of_rows_of_Data]; 73 drv = {names=("ch0", "ch1", "ch2", ..."number_of_rows_of_Data"); 74 sizes=( 1 1 1 ...); 75 times=( 0 0 0 ...); 76 }; 77 time = 0; 78 \endcode 79 If \c rowid is given, \c drv will be named after indeces in rowids. 80 81 Hence the data provided by method \c getdata() will be full column of matrix Data starting from the first record. 82 */ 83 void from_setting ( const Setting &set ) { 84 UI::get ( Data, set, "Data", UI::compulsory ); 85 if ( !UI::get ( time, set, "time", UI::optional ) ) { 86 time = 0; 46 87 } 47 48 void write ( const vec &ut, const ivec &indices ) { 49 bdm_error ( "MemDS::write is not supported" ); 88 if ( !UI::get ( rowid, set, "rowid", UI::optional ) ) { 89 rowid = linspace ( 0, Data.rows() - 1 ); 50 90 } 51 52 void step(); 53 //!Default constructor 54 MemDS () {}; 55 //! Convenience constructor 56 MemDS ( mat &Dat, ivec &rowid0); 57 /*! Create object from the following structure 58 \code 59 { class = "MemDS"; 60 Data = (...); // Data matrix or data vector 61 --- optional --- 62 drv = {class="RV"; ...} // Identification how rows of the matrix Data will be known to others 63 time = 0; // Index of the first column to user_info, 64 rowid = [1,2,3...]; // ids of rows to be used 91 shared_ptr<RV> r = UI::build<RV> ( set, "drv", UI::optional ); 92 if ( !r ) { 93 r = new RV(); 94 for ( int i = 0; i < rowid.length(); i++ ) { 95 r->add ( RV ( "ch" + num2str ( rowid ( i ) ), 1, 0 ) ); 96 } 65 97 } 66 \endcode 67 68 If the optional fields are not given, they will be filled as follows: 69 \code 70 rowid= [0, 1, 2, ...number_of_rows_of_Data]; 71 drv = {names=("ch0", "ch1", "ch2", ..."number_of_rows_of_Data"); 72 sizes=( 1 1 1 ...); 73 times=( 0 0 0 ...); 74 }; 75 time = 0; 76 \endcode 77 If \c rowid is given, \c drv will be named after indeces in rowids. 78 79 Hence the data provided by method \c getdata() will be full column of matrix Data starting from the first record. 80 */ 81 void from_setting(const Setting &set){ 82 UI::get(Data, set, "Data", UI::compulsory); 83 if(!UI::get(time, set,"time", UI::optional)) {time =0;} 84 if(!UI::get(rowid, set, "rowid",UI::optional)) {rowid =linspace(0,Data.rows()-1);} 85 shared_ptr<RV> r=UI::build<RV>(set,"drv",UI::optional); 86 if (!r) {r=new RV(); 87 for (int i=0; i<rowid.length(); i++){ r->add(RV("ch"+num2str(rowid(i)), 1, 0));} 88 } 89 set_drv(*r,RV()); //empty urv 90 dtsize=r->_dsize(); 91 ytsize = dtsize; 92 utsize=0; 93 } 94 }; 95 UIREGISTER(MemDS); 98 set_drv ( *r, RV() ); //empty urv 99 dtsize = r->_dsize(); 100 ytsize = dtsize; 101 utsize = 0; 102 } 103 }; 104 UIREGISTER ( MemDS ); 96 105 97 106 /*! \brief Simulate data from a static pdf (epdf) … … 101 110 102 111 class EpdfDS: public DS { 103 104 105 106 107 108 109 110 dt=iepdf->sample();111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 iepdf=UI::build<epdf> ( set,"epdf",UI::compulsory );131 bdm_assert(iepdf->isnamed(), "Input epdf must be named, check if RV is given correctly");132 dt = zeros(iepdf->dimension());133 dtsize=dt.length();134 ytsize=dt.length();135 set_drv(iepdf->_rv(),RV());136 utsize =0;137 138 139 140 141 112 protected: 113 //! internal pointer to epdf from which we samplecond 114 shared_ptr<epdf> iepdf; 115 //! internal storage of data sample 116 vec dt; 117 public: 118 void step() { 119 dt = iepdf->sample(); 120 } 121 void getdata ( vec &dt_out ) const { 122 dt_out = dt; 123 } 124 void getdata ( vec &dt_out, const ivec &ids ) { 125 dt_out = dt ( ids ); 126 } 127 const RV& _drv() const { 128 return iepdf->_rv(); 129 } 130 131 /*! 132 \code 133 class = "EpdfDS"; 134 epdf = {class="epdf_offspring", ...}// uncondtitional density to sample from 135 \endcode 136 137 */ 138 void from_setting ( const Setting &set ) { 139 iepdf = UI::build<epdf> ( set, "epdf", UI::compulsory ); 140 bdm_assert ( iepdf->isnamed(), "Input epdf must be named, check if RV is given correctly" ); 141 dt = zeros ( iepdf->dimension() ); 142 dtsize = dt.length(); 143 ytsize = dt.length(); 144 set_drv ( iepdf->_rv(), RV() ); 145 utsize = 0; 146 validate(); 147 } 148 void validate() { 149 dt = iepdf->sample(); 150 } 142 151 }; 143 152 UIREGISTER ( EpdfDS ); … … 146 155 Still having only one density but allowing conditioning on either input or delayed values. 147 156 */ 148 class PdfDS :public DS { 149 protected: 150 //! internal pointer to epdf from which we samplecond 151 shared_ptr<pdf> ipdf; 152 //! internal storage of data sample 153 vec yt; 154 //! input vector 155 vec ut; 156 //! datalink between ut and regressor 157 datalink_buffered ut2rgr; 158 //! datalink between yt and regressor 159 datalink_buffered yt2rgr; 160 //! numeric values of regressor 161 vec rgr; 162 163 public: 164 void step() { 165 yt2rgr.store_data(yt); // y is now history 166 ut2rgr.filldown ( ut,rgr ); 167 yt2rgr.filldown ( yt,rgr ); 168 yt=ipdf->samplecond ( rgr ); 169 ut2rgr.store_data(ut); //u is now history 157 class PdfDS : public DS { 158 protected: 159 //! internal pointer to epdf from which we samplecond 160 shared_ptr<pdf> ipdf; 161 //! internal storage of data sample 162 vec yt; 163 //! input vector 164 vec ut; 165 //! datalink between ut and regressor 166 datalink_buffered ut2rgr; 167 //! datalink between yt and regressor 168 datalink_buffered yt2rgr; 169 //! numeric values of regressor 170 vec rgr; 171 172 public: 173 void step() { 174 yt2rgr.store_data ( yt ); // y is now history 175 ut2rgr.filldown ( ut, rgr ); 176 yt2rgr.filldown ( yt, rgr ); 177 yt = ipdf->samplecond ( rgr ); 178 ut2rgr.store_data ( ut ); //u is now history 179 } 180 void getdata ( vec &dt_out ) const { 181 bdm_assert_debug ( dt_out.length() >= utsize + ytsize, "Short output vector" ); 182 dt_out.set_subvector ( 0, yt ); 183 dt_out.set_subvector ( ytsize, ut ); 184 } 185 void write ( const vec &ut0 ) { 186 ut = ut0; 187 } 188 void write ( const vec &ut0, const ivec &ind ) { 189 set_subvector ( ut, ind, ut0 ); 190 } 191 192 /*! 193 \code 194 class = "PdfDS"; 195 pdf = {class="pdf_offspring", ...}; // pdf to simulate 196 --- optional --- 197 init_rv = {class="RV",names=...}; // define what rv to initialize - typically delayed values! 198 init_values = [...]; // vector of initial values corresponding to init_rv 199 \endcode 200 201 If init_rv is not given, init_values are set to zero. 202 */ 203 void from_setting ( const Setting &set ) { 204 ipdf = UI::build<pdf> ( set, "pdf", UI::compulsory ); 205 206 Yrv = ipdf->_rv(); 207 // get unique rvs form rvc 208 RV rgrv0 = ipdf->_rvc().remove_time(); 209 // input is what in not in Yrv 210 Urv = rgrv0.subt ( Yrv ); 211 set_drv ( Yrv, Urv ); 212 // connect input and output to rvc 213 ut2rgr.set_connection ( ipdf->_rvc(), Urv ); 214 yt2rgr.set_connection ( ipdf->_rvc(), Yrv ); 215 216 //set history - if given 217 shared_ptr<RV> rv_ini = UI::build<RV> ( set, "init_rv", UI::optional ); 218 if ( rv_ini ) { // check if 219 vec val; 220 UI::get ( val, set, "init_values", UI::optional ); 221 if ( val.length() != rv_ini->_dsize() ) { 222 bdm_error ( "init_rv and init_values fields have incompatible sizes" ); 223 } else { 224 ut2rgr.set_history ( *rv_ini, val ); 225 yt2rgr.set_history ( *rv_ini, val ); 226 } 170 227 } 171 void getdata ( vec &dt_out ) const { 172 bdm_assert_debug(dt_out.length()>=utsize+ytsize,"Short output vector"); 173 dt_out.set_subvector(0, yt); 174 dt_out.set_subvector(ytsize, ut); 175 } 176 void write(const vec &ut0){ut=ut0;} 177 void write(const vec &ut0, const ivec &ind){set_subvector(ut,ind,ut0);} 178 179 /*! 180 \code 181 class = "PdfDS"; 182 pdf = {class="pdf_offspring", ...}; // pdf to simulate 183 --- optional --- 184 init_rv = {class="RV",names=...}; // define what rv to initialize - typically delayed values! 185 init_values = [...]; // vector of initial values corresponding to init_rv 186 \endcode 187 188 If init_rv is not given, init_values are set to zero. 189 */ 190 void from_setting ( const Setting &set ) { 191 ipdf=UI::build<pdf> ( set,"pdf",UI::compulsory ); 192 193 Yrv = ipdf->_rv(); 194 // get unique rvs form rvc 195 RV rgrv0=ipdf->_rvc().remove_time(); 196 // input is what in not in Yrv 197 Urv=rgrv0.subt(Yrv); 198 set_drv(Yrv, Urv); 199 // connect input and output to rvc 200 ut2rgr.set_connection(ipdf->_rvc(), Urv); 201 yt2rgr.set_connection(ipdf->_rvc(), Yrv); 202 203 //set history - if given 204 shared_ptr<RV> rv_ini=UI::build<RV>(set,"init_rv",UI::optional); 205 if(rv_ini){ // check if 206 vec val; 207 UI::get(val, set, "init_values", UI::optional); 208 if (val.length()!=rv_ini->_dsize()){ 209 bdm_error("init_rv and init_values fields have incompatible sizes"); 210 } else { 211 ut2rgr.set_history(*rv_ini, val); 212 yt2rgr.set_history(*rv_ini, val); 213 } 214 } 215 216 yt = zeros ( ipdf->dimension() ); 217 rgr = zeros ( ipdf->dimensionc() ); 218 ut = zeros(Urv._dsize()); 219 220 ytsize=yt.length(); 221 utsize=ut.length(); 222 dtsize = ytsize+utsize; 223 validate(); 224 } 225 void validate() { 226 //taken from sample() - shift of history is not done here 227 ut2rgr.filldown ( ut,rgr ); 228 yt2rgr.filldown ( yt,rgr ); 229 yt=ipdf->samplecond ( rgr ); 230 } 228 229 yt = zeros ( ipdf->dimension() ); 230 rgr = zeros ( ipdf->dimensionc() ); 231 ut = zeros ( Urv._dsize() ); 232 233 ytsize = yt.length(); 234 utsize = ut.length(); 235 dtsize = ytsize + utsize; 236 validate(); 237 } 238 void validate() { 239 //taken from sample() - shift of history is not done here 240 ut2rgr.filldown ( ut, rgr ); 241 yt2rgr.filldown ( yt, rgr ); 242 yt = ipdf->samplecond ( rgr ); 243 } 231 244 }; 232 245 UIREGISTER ( PdfDS ); … … 237 250 class FileDS: public MemDS { 238 251 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 void log_register(logger &L, const string &prefix){};255 256 252 public: 253 void getdata ( vec &dt ) { 254 dt = Data.get_col ( time ); 255 } 256 257 void getdata ( vec &dt, const ivec &indices ) { 258 vec tmp = Data.get_col ( time ); 259 dt = tmp ( indices ); 260 } 261 262 //! returns number of data in the file; 263 int ndat() { 264 return Data.cols(); 265 } 266 //! no sense to log this type 267 void log_register ( logger &L, const string &prefix ) {}; 268 //! no sense to log this type 269 void log_write ( ) const {}; 257 270 }; 258 271 … … 265 278 class ITppFileDS: public FileDS { 266 279 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 280 public: 281 //! Convenience constructor 282 ITppFileDS ( const string &fname, const string &varname ) : FileDS() { 283 it_file it ( fname ); 284 it << Name ( varname ); 285 it >> Data; 286 time = 0; 287 //rowid and delays are ignored 288 }; 289 290 ITppFileDS () : FileDS() { 291 }; 292 293 void from_setting ( const Setting &set ); 294 295 // TODO dodelat void to_setting( Setting &set ) const; 283 296 284 297 }; … … 296 309 class CsvFileDS: public FileDS { 297 310 298 299 300 311 public: 312 //! Constructor - create DS from a CSV file. 313 CsvFileDS ( const string& fname, const string& orientation = "BY_COL" ); 301 314 }; 302 315 … … 307 320 //! State-space data source simulating two densities 308 321 class StateDS : public DS { 309 protected: 310 //!conditional pdf of the state evolution \f$ f(x_t|x_{t-1}) \f$ 311 shared_ptr<pdf> IM; 312 313 //!conditional pdf of the observations \f$ f(d_t|x_t) \f$ 314 shared_ptr<pdf> OM; 315 316 //! result storage 317 vec dt; 318 //! state storage 319 vec xt; 320 //! input storage 321 vec ut; 322 323 //! datalink from ut to IM.rvc 324 datalink_part u2imc; 325 //! datalink from ut to OM.rvc 326 datalink_part u2omc; 327 public: 328 void getdata ( vec &dt0 ) const { 329 dt0 = dt; 330 } 331 void write (const vec &ut0 ) { 332 ut = ut0; 333 } 334 335 void getdata ( vec &dt0, const ivec &indices ) { 336 dt0 = dt ( indices ); 337 } 338 339 virtual void step() { 340 vec imc(IM->dimensionc()); 341 imc.set_subvector(0,xt); 342 u2imc.filldown(ut,imc); 343 xt = IM->samplecond ( imc ); 344 345 vec omc(OM->dimensionc()); 346 omc.set_subvector(0,xt); 347 u2omc.filldown(ut,omc); 348 vec yt; 349 yt = OM->samplecond ( omc ); 350 //fill all data 351 dt.set_subvector(0,yt); 352 dt.set_subvector(yt.length(),xt); 353 dt.set_subvector(ytsize,ut); 354 } 355 356 //! set parameters 357 void set_parameters(shared_ptr<pdf> IM0, shared_ptr<pdf> OM0){ 358 IM=IM0; 359 OM = OM0; 360 } 361 void set_initx(const vec &x0){xt=x0;} 362 363 /*! UI for stateDS 364 365 The DS is constructed from a structure with fields: 366 \code 367 class = "stateDS"; 368 //Internal model 369 IM = { type = "pdf-offspring"; }; 370 //Observation model 371 OM = { type = "pdf-offspring"; } 372 //initial state 373 x0 = [...]; //vector of data 374 \endcode 375 Both models must have defined \c rv. and \c rvc 376 Random variables not found in any rv are considered to be inputs. 377 */ 378 void from_setting ( const Setting &set ); 379 380 // TODO dodelat void to_setting( Setting &set ) const; 381 382 void validate(); 322 protected: 323 //!conditional pdf of the state evolution \f$ f(x_t|x_{t-1}) \f$ 324 shared_ptr<pdf> IM; 325 326 //!conditional pdf of the observations \f$ f(d_t|x_t) \f$ 327 shared_ptr<pdf> OM; 328 329 //! result storage 330 vec dt; 331 //! state storage 332 vec xt; 333 //! input storage 334 vec ut; 335 336 //! datalink from ut to IM.rvc 337 datalink_part u2imc; 338 //! datalink from ut to OM.rvc 339 datalink_part u2omc; 340 public: 341 void getdata ( vec &dt0 ) const { 342 dt0 = dt; 343 } 344 void write ( const vec &ut0 ) { 345 ut = ut0; 346 } 347 348 void getdata ( vec &dt0, const ivec &indices ) { 349 dt0 = dt ( indices ); 350 } 351 352 virtual void step() { 353 vec imc ( IM->dimensionc() ); 354 imc.set_subvector ( 0, xt ); 355 u2imc.filldown ( ut, imc ); 356 xt = IM->samplecond ( imc ); 357 358 vec omc ( OM->dimensionc() ); 359 omc.set_subvector ( 0, xt ); 360 u2omc.filldown ( ut, omc ); 361 vec yt; 362 yt = OM->samplecond ( omc ); 363 //fill all data 364 dt.set_subvector ( 0, yt ); 365 dt.set_subvector ( yt.length(), xt ); 366 dt.set_subvector ( ytsize, ut ); 367 } 368 369 //! set parameters 370 void set_parameters ( shared_ptr<pdf> IM0, shared_ptr<pdf> OM0 ) { 371 IM = IM0; 372 OM = OM0; 373 } 374 void set_initx ( const vec &x0 ) { 375 xt = x0; 376 } 377 378 /*! UI for stateDS 379 380 The DS is constructed from a structure with fields: 381 \code 382 class = "stateDS"; 383 //Internal model 384 IM = { type = "pdf-offspring"; }; 385 //Observation model 386 OM = { type = "pdf-offspring"; } 387 //initial state 388 x0 = [...]; //vector of data 389 \endcode 390 Both models must have defined \c rv. and \c rvc 391 Random variables not found in any rv are considered to be inputs. 392 */ 393 void from_setting ( const Setting &set ); 394 395 // TODO dodelat void to_setting( Setting &set ) const; 396 397 void validate(); 383 398 }; 384 399 -
library/bdm/base/loggers.cpp
r728 r737 22 22 // avoid uninitialized memory 23 23 for ( int j = 0; j < vectors ( i ).rows(); ++j ) { 24 for ( int k = 0; k < vectors ( i ).cols(); ++k ) {25 vectors ( i ) (j, k) = 0;24 for ( int k = 0; k < vectors ( i ).cols(); ++k ) { 25 vectors ( i ) ( j, k ) = 0; 26 26 } 27 27 } … … 49 49 void memlog::from_setting ( const Setting &set ) { 50 50 // TODO tady se natvrdo ocekava existence stringu, nejsou zadne defaulty.. je to tak OK? 51 UI::get (maxlen, set,"maxlen",UI::compulsory);52 UI::get (filename,set,"filename");51 UI::get ( maxlen, set, "maxlen", UI::compulsory ); 52 UI::get ( filename, set, "filename" ); 53 53 } 54 54 -
library/bdm/base/loggers.h
r728 r737 36 36 public: 37 37 //! convenience constructor 38 memlog ( int maxlen0, string fn = "" ) : logger("_"), maxlen ( maxlen0 ), ind ( 0 ), vectors ( 0 ), filename ( fn ) {}38 memlog ( int maxlen0, string fn = "" ) : logger ( "_" ), maxlen ( maxlen0 ), ind ( 0 ), vectors ( 0 ), filename ( fn ) {} 39 39 40 40 //!Default constructor 41 memlog() : logger ("_"), maxlen ( 0 ), ind ( 0 ), vectors ( 0 ) {}41 memlog() : logger ( "_" ), maxlen ( 0 ), ind ( 0 ), vectors ( 0 ) {} 42 42 43 43 //! Initialize storage … … 67 67 void finalize() { 68 68 if ( filename.length() > 0 ) { 69 itsave ( ( filename+".it").c_str());70 if ( settings.length()>0){71 setting_conf.writeFile ( (filename+".cfg").c_str());69 itsave ( ( filename + ".it" ).c_str() ); 70 if ( settings.length() > 0 ) { 71 setting_conf.writeFile ( ( filename + ".cfg" ).c_str() ); 72 72 } 73 73 } 74 74 75 75 }; 76 76 … … 100 100 All data records are written out to std from where they could be send to file 101 101 */ 102 class stdlog: public memlog{ 103 public: 104 //! default constructor 105 stdlog():memlog(1){}; 106 107 void init() { 108 memlog::init(); 109 for (int i=0; i<entries.length();i++){ 110 if (entries(i)._dsize()==1) { 111 cout << names(i) << entries(i).name(0) << "\t"; 102 class stdlog: public memlog { 103 public: 104 //! default constructor 105 stdlog() : memlog ( 1 ) {}; 106 107 void init() { 108 memlog::init(); 109 for ( int i = 0; i < entries.length(); i++ ) { 110 if ( entries ( i )._dsize() == 1 ) { 111 cout << names ( i ) << entries ( i ).name ( 0 ) << "\t"; 112 } else 113 for ( int j = 0; j < vectors ( i ).cols(); j++ ) { 114 cout << names ( i ) << entries ( i ).scalarname ( j ) << "\t"; 112 115 } 113 else 114 for (int j=0; j<vectors(i).cols(); j++){ 115 cout << names(i) << entries(i).scalarname(j) << "\t"; 116 } 116 } 117 cout << endl; 118 119 120 } 121 //!writes everything out 122 void step() { 123 for ( int i = 0; i < vectors.length(); i++ ) { 124 for ( int j = 0; j < vectors ( i ).cols(); j++ ) { 125 cout << vectors ( i ) ( 0, j ) << "\t"; 117 126 } 118 cout << endl;119 120 121 127 } 122 //!writes everything out 123 void step() { 124 for (int i=0; i<vectors.length();i++){ 125 for (int j=0; j<vectors(i).cols(); j++){ 126 cout << vectors(i)(0,j) << "\t"; 127 } 128 } 129 cout << endl; 130 } 131 /*! \brief UI for stdlog 132 133 TODO dat tam kam patri, a to celej blok 134 135 \code 136 logger = { 137 class = "stdlog"; // no parameterization needed 138 } 139 \endcode 140 */ 141 void from_setting ( const Setting &set ){ 142 } 143 128 cout << endl; 129 } 130 /*! \brief UI for stdlog 131 132 TODO dat tam kam patri, a to celej blok 133 134 \code 135 logger = { 136 class = "stdlog"; // no parameterization needed 137 } 138 \endcode 139 */ 140 void from_setting ( const Setting &set ) { 141 } 142 144 143 }; 145 UIREGISTER (stdlog);144 UIREGISTER ( stdlog ); 146 145 147 146 /*! -
library/bdm/base/user_info.cpp
r735 r737 15 15 namespace bdm { 16 16 17 string UIException::format_message ( const string &reason, const string &path ) {17 string UIException::format_message ( const string &reason, const string &path ) { 18 18 stringstream ss; 19 19 ss << reason; … … 78 78 void UI::MappedUI::add_class ( const string &class_name, const type_info * const class_type_info, const UI* const ui ) { 79 79 pair< StringToUIMap::iterator, bool> inres = 80 81 StringToUIMap::value_type( class_name, ui ) );80 mapped_strings().insert ( 81 StringToUIMap::value_type ( class_name, ui ) ); 82 82 if ( inres.second ) { 83 83 mapped_type_infos().insert ( 84 85 84 TypeInfoToStringMap::value_type ( 85 class_type_info, class_name ) ); 86 86 } 87 87 } … … 198 198 : element.add ( name, Setting::TypeList ); 199 199 200 Setting &tag= set.add ( Setting::TypeString );201 tag ="matrix";202 200 Setting &tag = set.add ( Setting::TypeString ); 201 tag = "matrix"; 202 203 203 Setting &cols = set.add ( Setting::TypeInt ); 204 204 cols = matrix.cols(); … … 310 310 from_setting ( matrix, link.result ); 311 311 312 if ( matrix.cols() != 1 && matrix.rows() != 1 && matrix.cols() !=0)312 if ( matrix.cols() != 1 && matrix.rows() != 1 && matrix.cols() != 0 ) 313 313 throw UISettingException ( "UIException: the vector length is invalid, it seems to be rather a matrix.", link.result ); 314 314 -
library/bdm/base/user_info.h
r728 r737 48 48 */ 49 49 UIException ( const string &message ) : 50 message ( message ) {50 message ( message ) { 51 51 } 52 52 … … 63 63 Setting path in addition to the message. 64 64 */ 65 static string format_message ( const string &reason, const string &path );65 static string format_message ( const string &reason, const string &path ); 66 66 }; 67 67 … … 72 72 public: 73 73 //! Use this constructor when you can pass the problematical Setting as a parameter 74 UISettingException ( const string &message, const Setting &element ) :75 UIException ( format_message ( message, string ( element.getPath() ) ) ) {74 UISettingException ( const string &message, const Setting &element ) : 75 UIException ( format_message ( message, string ( element.getPath() ) ) ) { 76 76 } 77 77 78 78 //! This constructor is for other occasions, when only path of problematical Setting is known 79 UISettingException ( const string &message, const string &path ) :80 UIException ( format_message ( message, path ) ) {79 UISettingException ( const string &message, const string &path ) : 80 UIException ( format_message ( message, path ) ) { 81 81 } 82 82 … … 90 90 public: 91 91 //! Use this constructor when you can pass the problematical Setting as a parameter 92 UIClassException ( const string &message, const Setting &element ) :93 UIException ( format_message ( message, string ( element.getPath() ) ) ) {92 UIClassException ( const string &message, const Setting &element ) : 93 UIException ( format_message ( message, string ( element.getPath() ) ) ) { 94 94 } 95 95 96 96 //! This constructor is for other occasions, when only path of problematical Setting is known 97 UIClassException ( const string &message, const string &path ) :98 UIException ( format_message ( message, path ) ) {97 UIClassException ( const string &message, const string &path ) : 98 UIException ( format_message ( message, path ) ) { 99 99 } 100 100 … … 337 337 msg += class_name; 338 338 msg += ".from_setting(Setting&) has thrown a SettingException."; 339 throw UISettingException (msg, sttng_xcptn.getPath());340 } catch ( std::runtime_error &e) {339 throw UISettingException ( msg, sttng_xcptn.getPath() ); 340 } catch ( std::runtime_error &e ) { 341 341 delete instance; 342 342 instance = 0; … … 345 345 msg += " says: "; 346 346 msg += e.what(); 347 throw UISettingException (msg, link.result);348 } catch ( ...) {347 throw UISettingException ( msg, link.result ); 348 } catch ( ... ) { 349 349 delete instance; 350 350 instance = 0; 351 351 throw; 352 352 } 353 }353 } 354 354 355 355 //! This method converts a Setting into a descendant of class … … 383 383 template<class T> static void from_setting ( T &variable_to_load, const Setting &element ) { 384 384 std::string msg = "UIException: from_setting is not implemented for type "; 385 msg += typeid (T).name();385 msg += typeid ( T ).name(); 386 386 msg += '.'; 387 387 throw UISettingException ( msg, element ); … … 441 441 } 442 442 443 //! The new instance of type T* is constructed and initialized with values stored in the given Setting 443 //! The new instance of type T* is constructed and initialized with values stored in the given Setting 444 444 //! 445 445 //! Handy in mex files. Use with care. 446 template<class T>447 static shared_ptr<T> build ( const Setting &element, SettingPresence settingPresence = optional ) { 448 shared_ptr<T> instance;449 from_setting<T> ( instance, element);450 return instance;451 }446 template<class T> 447 static shared_ptr<T> build ( const Setting &element, SettingPresence settingPresence = optional ) { 448 shared_ptr<T> instance; 449 from_setting<T> ( instance, element ); 450 return instance; 451 } 452 452 453 453 //!@} … … 481 481 stream << "UIException: the compulsory Setting with the index " << index << " is missing."; 482 482 stream << index; 483 throw UISettingException ( stream.str(), element );483 throw UISettingException ( stream.str(), element ); 484 484 } 485 485 } … … 560 560 msg += class_name; 561 561 msg += ".to_setting(Setting&) has thrown a SettingException."; 562 throw UISettingException (msg, sttng_xcptn.getPath());562 throw UISettingException ( msg, sttng_xcptn.getPath() ); 563 563 } 564 564 } … … 597 597 598 598 //! for future use 599 virtual ~UI() {}599 virtual ~UI() {} 600 600 }; 601 601 … … 645 645 #define UIREGISTER2(class_name, temp_name) static bdm::ParticularUI<class_name<temp_name> > UI##class_name##_##temp_name( QUOTEME(class_name<temp_name>) ) 646 646 #else 647 #define UIREGISTER2(class_name,temp_name) 647 #define UIREGISTER2(class_name,temp_name) 648 648 #endif 649 649