Changeset 270 for bdm/stat

Show
Ignore:
Timestamp:
02/16/09 10:02:08 (15 years ago)
Author:
smidl
Message:

Changes in the very root classes!
* rv and rvc are no longer compulsory,
* samplecond does not return ll
* BM has drv

Location:
bdm/stat
Files:
12 modified

Legend:

Unmodified
Added
Removed
  • bdm/stat/emix.cpp

    r254 r270  
    55void emix::set_parameters ( const vec &w0, const Array<epdf*> &Coms0, bool copy ) { 
    66        w = w0/sum ( w0 ); 
     7        dim = Coms0(0)->dimension(); 
    78        int i; 
    89        for ( i=0;i<w.length();i++ ) { 
    9                 it_assert_debug ( rv.equal ( Coms0 ( i )->_rv() ),"RVs do not match!" ); 
     10                it_assert_debug ( dim== ( Coms0 ( i )->dimension() ),"Component sizes do not match!" ); 
    1011        } 
    1112        if ( copy ) { 
     
    3536 
    3637emix* emix::marginal(const RV &rv) const{ 
     38        it_assert_debug(isnamed(), "rvs are not assigned"); 
     39                         
    3740        Array<epdf*> Cn(Coms.length()); 
    3841        for(int i=0;i<Coms.length();i++){Cn(i)=Coms(i)->marginal(rv);} 
    39         emix* tmp = new emix(rv); 
     42        emix* tmp = new emix(); 
    4043        tmp->set_parameters(w,Cn,false); 
    4144        tmp->ownComs(); 
     
    4447 
    4548mratio* emix::condition(const RV &rv) const{ 
     49        it_assert_debug(isnamed(), "rvs are not assigned"); 
    4650        return new mratio(this,rv); 
    4751}; 
  • bdm/stat/emix.h

    r254 r270  
    4747        //!Default constructor. By default, the given epdf is not copied! 
    4848        //! It is assumed that this function will be used only temporarily. 
    49         mratio ( const epdf* nom0, const RV &rv, bool copy=false ) :mpdf ( rv,nom0->_rv().subt ( rv ) ), dl ( rv,rvc,nom0->_rv() ) { 
     49        mratio ( const epdf* nom0, const RV &rv, bool copy=false ) :mpdf ( ), dl ( rv,rvc,nom0->_rv() ) { 
     50                ep->set_rv(_rv()); 
     51                set_rvc(nom0->_rv().subt ( rv ) ); 
    5052                if ( copy ) { 
    5153//                      nom = nom0->_copy_(); 
     
    6264        double evallogcond ( const vec &val, const vec &cond ) { 
    6365                double tmp; 
    64                 vec nom_val ( rv.count() +rvc.count() ); 
    65                 dl.fill_val_cond ( nom_val,val,cond ); 
     66                vec nom_val ( ep->dimension() + dimc ); 
     67                dl.pushup_cond ( nom_val,val,cond ); 
    6668                tmp = exp ( nom->evallog ( nom_val ) - den->evallog ( cond ) ); 
    6769                it_assert_debug(std::isfinite(tmp),"Infinite value"); 
     
    9496public: 
    9597        //!Default constructor 
    96         emix ( const RV &rv ) : epdf ( rv ) {}; 
     98        emix (  ) : epdf ( ) {}; 
    9799        //! Set weights \c w and components \c Coms 
    98100        //!By default Coms are copied inside. Parameter \c copy can be set to false if Coms live externally. Use method ownComs() if Coms should be destroyed by the destructor. 
    99         void set_parameters ( const vec &w, const Array<epdf*> &Coms, bool copy=true ); 
     101        void set_parameters ( const vec &w, const Array<epdf*> &Coms, bool copy=false ); 
    100102 
    101103        vec sample() const; 
    102104        vec mean() const { 
    103                 int i; vec mu = zeros ( rv.count() ); 
     105                int i; vec mu = zeros ( dim); 
    104106                for ( i = 0;i < w.length();i++ ) {mu += w ( i ) * Coms ( i )->mean(); } 
    105107                return mu; 
     
    107109        vec variance() const { 
    108110                //non-central moment 
    109                 vec mom2 = zeros(rv.count()); 
     111                vec mom2 = zeros(dim); 
    110112                for ( int i = 0;i < w.length();i++ ) {mom2 += w ( i ) * pow(Coms ( i )->mean(),2); } 
    111113                //central moment 
     
    165167        //! Data link for each mpdfs 
    166168        Array<datalink_m2m*> dls; 
     169        //! dummy ep 
     170        epdf dummy; 
    167171public: 
    168172        /*!\brief Constructor from list of mFacs, 
    169173        */ 
    170         mprod ( Array<mpdf*> mFacs ) : compositepdf ( mFacs ), mpdf ( getrv ( true ),RV() ), epdfs ( n ), dls ( n ) { 
    171                 setrvc ( rv,rvc ); 
     174        mprod ( Array<mpdf*> mFacs ) : compositepdf ( mFacs ), mpdf (), epdfs ( n ), dls ( n ) { 
     175                ep=&dummy; 
     176                RV rv=getrv(true); 
     177                set_rv(rv);dummy.set_parameters(rv._dsize()); 
     178                setrvc ( ep->_rv(),rvc ); 
    172179                // rv and rvc established = > we can link them with mpdfs 
    173180                for ( int i = 0;i < n;i++ ) { 
    174                         dls ( i ) = new datalink_m2m ( mpdfs ( i )->_rv(), mpdfs ( i )->_rvc(), rv, rvc ); 
     181                        dls ( i ) = new datalink_m2m ( mpdfs ( i )->_rv(), mpdfs ( i )->_rvc(), _rv(), _rvc() ); 
    175182                } 
    176183 
     
    182189        double evallogcond ( const vec &val, const vec &cond ) { 
    183190                int i; 
    184                 double res = 1.0; 
     191                double res = 0.0; 
    185192                for ( i = n - 1;i >= 0;i-- ) { 
    186193                        /*                      if ( mpdfs(i)->_rvc().count() >0) { 
     
    188195                                                } 
    189196                                                // add logarithms 
    190                                                 res += epdfs ( i )->evallog ( dls ( i )->get_val ( val ) );*/ 
    191                         res *= mpdfs ( i )->evallogcond ( 
    192                                    dls ( i )->get_val ( val ), 
     197                                                res += epdfs ( i )->evallog ( dls ( i )->pushdown ( val ) );*/ 
     198                        res += mpdfs ( i )->evallogcond ( 
     199                                   dls ( i )->pushdown ( val ), 
    193200                                   dls ( i )->get_cond ( val, cond ) 
    194201                               ); 
     
    196203                return res; 
    197204        } 
    198         vec samplecond ( const vec &cond, double &ll ) { 
     205        //TODO smarter... 
     206        vec samplecond ( const vec &cond ) { 
    199207                //! Ugly hack to help to discover if mpfs are not in proper order. Correct solution = check that explicitely. 
    200                 vec smp= std::numeric_limits<double>::infinity() * ones ( rv.count() ); 
     208                vec smp= std::numeric_limits<double>::infinity() * ones ( ep->dimension() ); 
    201209                vec smpi; 
    202                 ll = 0; 
    203210                // Hard assumption here!!! We are going backwards, to assure that samples that are needed from smp are already generated! 
    204211                for ( int i = ( n - 1 );i >= 0;i-- ) { 
    205                         if ( mpdfs ( i )->_rvc().count() ) { 
     212                        if ( mpdfs ( i )->dimensionc() ) { 
    206213                                mpdfs ( i )->condition ( dls ( i )->get_cond ( smp ,cond ) ); // smp is val here!! 
    207214                        } 
    208215                        smpi = epdfs ( i )->sample(); 
    209216                        // copy contribution of this pdf into smp 
    210                         dls ( i )->fill_val ( smp, smpi ); 
     217                        dls ( i )->pushup ( smp, smpi ); 
    211218                        // add ith likelihood contribution 
    212                         ll+=epdfs ( i )->evallog ( smpi ); 
    213219                } 
    214220                return smp; 
    215221        } 
    216         mat samplecond ( const vec &cond, vec &ll, int N ) { 
    217                 mat Smp ( rv.count(),N ); 
    218                 for ( int i=0;i<N;i++ ) {Smp.set_col ( i,samplecond ( cond,ll ( i ) ) );} 
     222        mat samplecond ( const vec &cond, int N ) { 
     223                mat Smp ( dimension(),N ); 
     224                for ( int i=0;i<N;i++ ) {Smp.set_col ( i,samplecond ( cond ) );} 
    219225                return Smp; 
    220226        } 
     
    229235        Array<const epdf*> epdfs; 
    230236        //! Array of indeces 
    231         Array<datalink_e2e*> dls; 
    232 public: 
    233         eprod ( const Array<const epdf*> epdfs0 ) : epdf ( RV() ),epdfs ( epdfs0 ),dls ( epdfs.length() ) { 
     237        Array<datalink*> dls; 
     238public: 
     239        eprod ( const Array<const epdf*> epdfs0 ) : epdf ( ),epdfs ( epdfs0 ),dls ( epdfs.length() ) { 
    234240                bool independent=true; 
    235241                for ( int i=0;i<epdfs.length();i++ ) { 
     
    238244                } 
    239245                for ( int i=0;i<epdfs.length();i++ ) { 
    240                         dls ( i ) = new datalink_e2e ( epdfs ( i )->_rv() , rv ); 
     246                        dls ( i ) = new datalink ( epdfs ( i )->_rv() , rv ); 
    241247                } 
    242248        } 
    243249 
    244250        vec mean() const { 
    245                 vec tmp ( rv.count() ); 
     251                vec tmp ( dim ); 
    246252                for ( int i=0;i<epdfs.length();i++ ) { 
    247253                        vec pom = epdfs ( i )->mean(); 
    248                         dls ( i )->fill_val ( tmp, pom ); 
     254                        dls ( i )->pushup ( tmp, pom ); 
    249255                } 
    250256                return tmp; 
    251257        } 
    252258        vec variance() const { 
    253                 vec tmp ( rv.count() ); //second moment 
     259                vec tmp ( dim ); //second moment 
    254260                for ( int i=0;i<epdfs.length();i++ ) { 
    255261                        vec pom = epdfs ( i )->mean(); 
    256                         dls ( i )->fill_val ( tmp, pow(pom,2) ); 
     262                        dls ( i )->pushup ( tmp, pow(pom,2) ); 
    257263                } 
    258264                return tmp-pow(mean(),2); 
    259265        } 
    260266        vec sample() const { 
    261                 vec tmp ( rv.count() ); 
     267                vec tmp ( dim ); 
    262268                for ( int i=0;i<epdfs.length();i++ ) { 
    263269                        vec pom = epdfs ( i )->sample(); 
    264                         dls ( i )->fill_val ( tmp, pom ); 
     270                        dls ( i )->pushup ( tmp, pom ); 
    265271                } 
    266272                return tmp; 
     
    269275                double tmp=0; 
    270276                for ( int i=0;i<epdfs.length();i++ ) { 
    271                         tmp+=epdfs ( i )->evallog ( dls ( i )->get_val ( val ) ); 
     277                        tmp+=epdfs ( i )->evallog ( dls ( i )->pushdown ( val ) ); 
    272278                } 
    273279                it_assert_debug(std::isfinite(tmp),"Infinite"); 
     
    293299public: 
    294300        //!Default constructor 
    295         mmix ( RV &rv, RV &rvc ) : mpdf ( rv, rvc ), Epdf ( rv ) {ep = &Epdf;}; 
     301        mmix ( ) : mpdf ( ), Epdf () {ep = &Epdf;}; 
    296302        //! Set weights \c w and components \c R 
    297303        void set_parameters ( const vec &w, const Array<mpdf*> &Coms ) { 
  • bdm/stat/libBM.cpp

    r265 r270  
    55//! Space of basic BDM structures 
    66namespace bdm { 
    7  
    8 using std::cout; 
    9  
    10 static int RVcounter=0; 
     7         
     8const int RV_BUFFER_STEP=1; 
     9RVmap RV_MAP; 
     10Array<string> RV_NAMES(RV_BUFFER_STEP); 
     11ivec RV_SIZES(RV_BUFFER_STEP); 
    1112 
    1213RV RV0=RV(); 
    1314 
    14 void RV::init ( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times ) { 
     15int RV::init ( const string &name, int size ) { 
    1516        //Refer 
    16         int i; 
    17         len = in_ids.length(); 
    18         //PRUDENT_MODE 
    19         // All vetors should be of same length 
    20         if ( ( len != in_names.length() ) || \ 
    21                 ( len != in_sizes.length() ) || \ 
    22                 ( len != in_times.length() ) ) { 
    23                 it_error ( "RV::RV inconsistent length of input vectors." ); 
    24         } 
    25  
    26         ids = in_ids; 
    27         names = in_names; 
    28         sizes = in_sizes; 
     17        int id; 
     18        RVmap::const_iterator iter = RV_MAP.find ( name ); 
     19        if ( iter == RV_MAP.end() ) { 
     20                id=RV_MAP.size()+1; 
     21                RV_MAP.insert ( make_pair ( name,id ) ); //add new rv 
     22                if (id>=RV_NAMES.length()){ 
     23                        RV_NAMES.set_length(id+RV_BUFFER_STEP,true); 
     24                        RV_SIZES.set_length(id+RV_BUFFER_STEP,true); 
     25                } 
     26                RV_NAMES(id)=name; 
     27                RV_SIZES(id)=size; 
     28        } 
     29        else { 
     30                id = iter->second; 
     31                it_warning ("RV of name " + name + "already exists" ); 
     32        } 
     33        return id; 
     34}; 
     35 
     36int RV::countsize() const{ int tmp=0; for(int i=0;i<len;i++){tmp+=RV_SIZES(ids(i));} return tmp;} 
     37 
     38void RV::init ( Array<std::string> in_names, ivec in_sizes,ivec in_times ) { 
     39        len = in_names.length(); 
     40        it_assert_debug ( in_names.length() ==in_times.length(), "check \"times\" " ); 
     41        it_assert_debug ( in_names.length() ==in_sizes.length(), "check \"sizes\" " ); 
     42         
     43        times.set_length ( len ); 
     44        ids.set_length ( len ); 
     45        int id; 
     46        for ( int i=0; i<len; i++ ) { 
     47                id = init ( in_names ( i ), in_sizes ( i ) ); 
     48                ids ( i ) = id; 
     49        } 
    2950        times = in_times; 
    30         tsize = 0; 
    31         for ( i = 0;i < len;i++ ) {tsize += sizes ( i );} 
    32 }; 
    33  
    34 RV::RV ( Array<std::string> in_names, ivec in_sizes, ivec in_times ) { 
    35         int len = in_names.length(); 
    36         init ( linspace ( RVcounter+1, RVcounter+len ), in_names, in_sizes, in_times ); 
    37         RVcounter+=len; 
    38 } 
    39  
    40 RV::RV ( Array<std::string> in_names, ivec in_sizes ) { 
    41         int len = in_names.length(); 
    42         init ( linspace ( RVcounter+1, RVcounter+len ), in_names, in_sizes, zeros_i ( in_names.length() ) ); 
    43         RVcounter+=len; 
    44 } 
    45  
    46 RV::RV ( Array<std::string> in_names ) { 
    47         int len = in_names.length(); 
    48         init ( linspace ( RVcounter+1, RVcounter+len ), in_names, ones_i ( in_names.length() ), zeros_i ( in_names.length() ) ); 
    49         RVcounter+=len; 
    50 } 
    51  
    52 RV::RV() : tsize ( 0 ), len ( 0 ), ids ( 0 ),  sizes ( 0 ), times ( 0 ),names ( 0 ) {}; 
    53  
    54 RV::RV(string name, int id, int sz, int tm){ 
    55         if (id>RVcounter) {RVcounter=id;}; 
    56         Array<string> A(1); A(0)=name; 
    57         init(vec_1(id),A,vec_1(sz),vec_1(tm)); 
     51        dsize = countsize(); 
     52} 
     53 
     54RV::RV ( string name, int sz, int tm ) { 
     55        Array<string> A ( 1 ); A ( 0 ) =name; 
     56        init (A,vec_1 ( sz ),vec_1 ( tm ) ); 
    5857} 
    5958 
     
    6463                ivec index = itpp::find ( ind==-1 ); 
    6564 
    66  
    6765                if ( index.length() < rv2.len ) { //conflict 
    6866                        ids = concat ( ids, rv2.ids ( index ) ); 
    69                         sizes = concat ( sizes, rv2.sizes ( index ) ); 
    7067                        times = concat ( times, rv2.times ( index ) ); 
    71                         names = concat ( names, rv2.names ( to_Arr ( index ) ) ); 
    7268                } 
    7369                else { 
    7470                        ids = concat ( ids, rv2.ids ); 
    75                         sizes = concat ( sizes, rv2.sizes ); 
    7671                        times = concat ( times, rv2.times ); 
    77                         names = concat ( names, rv2.names ); 
    78                 } 
    79                 tsize = sum ( sizes ); 
     72                } 
    8073                len = ids.length(); 
    81                 return ( index.length() ==rv2.len ); 
     74                dsize = countsize(); 
     75                return ( index.length() ==rv2.len ); //conflict or not 
    8276        } 
    8377        else { //rv2 is empty 
    84                 return true; 
    85         } 
    86 //      return *this; 
     78                return true; // no conflict 
     79        } 
    8780}; 
    8881 
    89 // RV::RV ( ivec in_ids ) { 
    90 // 
    91 //      len = in_ids.length(); 
    92 //      Array<std::string> A ( len ); 
    93 //      std::string rvstr = "rv"; 
    94 // 
    95 //      for ( int i = 0; i < len;i++ ) { 
    96 //              A ( i ) = rvstr + to_str ( i ); 
    97 //      } 
    98 // 
    99 //      init ( in_ids, A, ones_i ( len ), zeros_i ( len ) ); 
    100 // } 
    101  
    102 RV RV::subselect (const ivec &ind ) const { 
     82RV RV::subselect ( const ivec &ind ) const { 
    10383        RV ret; 
    104         ret.init ( ids ( ind ), names ( to_Arr ( ind ) ), sizes ( ind ), times ( ind ) ); 
     84        ret.ids = ids(ind); 
     85        ret.times= times(ind); 
     86        ret.len = ind.length(); 
     87        ret.dsize=ret.countsize(); 
    10588        return ret; 
    10689} 
     
    10891void RV::t ( int delta ) { times += delta;} 
    10992 
    110 RV RV::operator() (const ivec &ind ) const { 
    111         RV ret; 
    112         if ( ind.length() >0 ) { 
    113                 ret.init ( ids ( ind ), names ( to_Arr ( ind ) ), sizes ( ind ), times ( ind ) ); 
    114         } 
    115         return ret; 
    116 } 
    117  
    11893bool RV::equal ( const RV &rv2 ) const { 
    119         return ( ids == rv2.ids ) && ( times == rv2.times ) && ( sizes == rv2.sizes ); 
     94        return ( ids == rv2.ids ) && ( times == rv2.times ); 
    12095} 
    12196 
    12297mat epdf::sample_m ( int N ) const { 
    123         mat X = zeros ( rv.count(), N ); 
     98        mat X = zeros ( dim, N ); 
    12499        for ( int i = 0;i < N;i++ ) X.set_col ( i, this->sample() ); 
    125100        return X; 
     
    128103 
    129104std::ostream &operator<< ( std::ostream &os, const RV &rv ) { 
    130  
     105        int id; 
    131106        for ( int i = 0; i < rv.len ;i++ ) { 
    132                 os << rv.ids ( i ) << "(" << rv.sizes ( i ) << ")" <<  // id(size)= 
    133                 "=" << rv.names ( i )  << "_{"  << rv.times ( i ) << "}; "; //name_{time} 
     107                id=rv.ids ( i ); 
     108                os << id << "(" << RV_SIZES ( id ) << ")" <<  // id(size)= 
     109                "=" << RV_NAMES ( id )  << "_{"  << rv.times ( i ) << "}; "; //name_{time} 
    134110        } 
    135111        return os; 
     
    137113 
    138114str RV::tostr() const { 
    139         ivec idlist ( tsize ); 
    140         ivec tmlist ( tsize ); 
     115        ivec idlist ( dsize ); 
     116        ivec tmlist ( dsize ); 
    141117        int i; 
    142118        int pos = 0; 
    143119        for ( i = 0;i < len;i++ ) { 
    144                 idlist.set_subvector ( pos, pos + sizes ( i ) - 1, ids ( i ) ); 
    145                 tmlist.set_subvector ( pos, pos + sizes ( i ) - 1, times ( i ) ); 
    146                 pos += sizes ( i ); 
     120                idlist.set_subvector ( pos, pos + size ( ids(i) ) - 1, ids ( i ) ); 
     121                tmlist.set_subvector ( pos, pos + size ( ids(i) ) - 1, times ( i ) ); 
     122                pos += size ( ids(i) ); 
    147123        } 
    148124        return str ( idlist, tmlist ); 
    149125} 
    150126 
    151 ivec RV::dataind (const RV &rv2 ) const { 
     127ivec RV::dataind ( const RV &rv2 ) const { 
    152128        ivec res ( 0 ); 
    153         if ( rv2.count()>0 ) { 
     129        if ( rv2._dsize() >0 ) { 
    154130                str str2 = rv2.tostr(); 
    155131                ivec part; 
     
    160136                } 
    161137        } 
    162         it_assert_debug(res.length()==tsize,"this rv is not fully present in crv!"); 
     138        it_assert_debug ( res.length() ==dsize,"this rv is not fully present in crv!" ); 
    163139        return res; 
    164140 
    165141} 
    166142 
    167 void RV::dataind (const RV &rv2, ivec &selfi, ivec &rv2i) const { 
     143void RV::dataind ( const RV &rv2, ivec &selfi, ivec &rv2i ) const { 
    168144        //clean results 
    169         selfi.set_size(0); 
    170         rv2i.set_size(0); 
    171          
     145        selfi.set_size ( 0 ); 
     146        rv2i.set_size ( 0 ); 
     147 
    172148        // just in case any rv is empty 
    173         if ((len==0)||(rv2.length()==0)){return;}  
    174          
     149        if ( ( len==0 ) || ( rv2.length() ==0 ) ) {return;} 
     150 
    175151        //find comon rv 
    176         ivec cids=itpp::find(this->findself(rv2)>=0); 
    177          
    178         // index of  
    179         if ( cids.length()>0 ) { 
     152        ivec cids=itpp::find ( this->findself ( rv2 ) >=0 ); 
     153 
     154        // index of 
     155        if ( cids.length() >0 ) { 
    180156                str str1 = tostr(); 
    181                 str str2 = rv2.tostr();  
    182                  
     157                str str2 = rv2.tostr(); 
     158 
    183159                ivec part1; 
    184160                ivec part2; 
     
    186162                // find common rv in strs 
    187163                for ( j=0; j < cids.length();j++ ) { 
    188                         i = cids(j); 
     164                        i = cids ( j ); 
    189165                        part1 = itpp::find ( ( str1.ids == ids ( i ) ) & ( str1.times == times ( i ) ) ); 
    190166                        part2 = itpp::find ( ( str2.ids == ids ( i ) ) & ( str2.times == times ( i ) ) ); 
     
    193169                } 
    194170        } 
    195         it_assert_debug(selfi.length() == rv2i.length(),"this should not happen!"); 
     171        it_assert_debug ( selfi.length() == rv2i.length(),"this should not happen!" ); 
    196172} 
    197173 
     
    199175        ivec res = this->findself ( rv2 ); // nonzeros 
    200176        ivec valid; 
    201         if (tsize>0) {valid= itpp::find ( res == -1 );} //-1 => value not found => it remains 
     177        if ( dsize>0 ) {valid= itpp::find ( res == -1 );} //-1 => value not found => it remains 
    202178        return ( *this ) ( valid ); //keep those that were not found in rv2 
    203179} 
     
    223199} 
    224200 
    225 void RV::newids(){ids=linspace ( RVcounter+1, RVcounter+len ),RVcounter+=len;} 
    226  
    227 RV compositepdf::getrv(bool checkoverlap){ 
     201RV compositepdf::getrv ( bool checkoverlap ) { 
    228202        RV rv; //empty rv 
    229203        bool rvaddok; 
    230         for (int i = 0;i < n;i++ ) { 
     204        for ( int i = 0;i < n;i++ ) { 
    231205                rvaddok=rv.add ( mpdfs ( i )->_rv() ); //add rv to common rvs. 
    232                         // If rvaddok==false, mpdfs overlap => assert error. 
    233                 it_assert_debug(rvaddok||(!checkoverlap),"mprod::mprod() input mpdfs overlap in rv!"); 
     206                // If rvaddok==false, mpdfs overlap => assert error. 
     207                it_assert_debug ( rvaddok|| ( !checkoverlap ),"mprod::mprod() input mpdfs overlap in rv!" ); 
    234208        }; 
    235209        return rv; 
    236210} 
    237211 
    238 void compositepdf::setrvc(const RV &rv, RV &rvc){ 
    239         for (int i = 0;i < n;i++ ) { 
     212void compositepdf::setrvc ( const RV &rv, RV &rvc ) { 
     213        for ( int i = 0;i < n;i++ ) { 
    240214                RV rvx = mpdfs ( i )->_rvc().subt ( rv ); 
    241215                rvc.add ( rvx ); //add rv to common rvc 
     
    243217} 
    244218 
    245 void BM::bayesB(const mat &Data){ 
    246         for(int t=0;t<Data.cols();t++){bayes(Data.get_col(t));} 
    247 } 
    248 } 
     219void BM::bayesB ( const mat &Data ) { 
     220        for ( int t=0;t<Data.cols();t++ ) {bayes ( Data.get_col ( t ) );} 
     221} 
     222} 
  • bdm/stat/libBM.h

    r267 r270  
    1414\defgroup core Core BDM classes 
    1515@{ 
     16\defgroup const Constructors 
     17\defgroup math Mathematical operations 
    1618*/ 
    1719#ifndef BM_H 
     
    2022 
    2123#include "../itpp_ext.h" 
    22 //#include <std> 
     24#include <map> 
    2325 
    2426namespace bdm { 
    25         using namespace itpp; 
    26         using std::string; 
     27using namespace itpp; 
     28using namespace std; 
    2729 
    2830//! Root class of BDM objects 
    29         class bdmroot { 
    30                 virtual void print() {} 
     31class bdmroot { 
     32public: 
     33        //! make sure this is a virtual object 
     34        virtual ~bdmroot() {} 
     35}; 
     36 
     37typedef std::map<string, int> RVmap; 
     38extern ivec RV_SIZES; 
     39extern Array<string> RV_NAMES; 
     40 
     41//! Structure of RV (used internally), i.e. expanded RVs 
     42class str { 
     43public: 
     44        //! vector id ids (non-unique!) 
     45        ivec ids; 
     46        //! vector of times 
     47        ivec times; 
     48        //!Default constructor 
     49        str ( ivec ids0, ivec times0 ) :ids ( ids0 ),times ( times0 ) { 
     50                it_assert_debug ( times0.length() ==ids0.length(),"Incompatible input" ); 
    3151        }; 
    32  
    33 //! Structure of RV (used internally), i.e. expanded RVs 
    34         class str { 
    35         public: 
    36                 //! vector id ids (non-unique!) 
    37                 ivec ids; 
    38                 //! vector of times 
    39                 ivec times; 
    40                 //!Default constructor 
    41                 str ( ivec ids0, ivec times0 ) :ids ( ids0 ),times ( times0 ) { 
    42                         it_assert_debug ( times0.length() ==ids0.length(),"Incompatible input" ); 
    43                 }; 
     52}; 
     53 
     54/*! 
     55* \brief Class representing variables, most often random variables 
     56 
     57The purpose of this class is to decribe a vector of data. Such description is used for connecting various vectors between each other, see class datalink. 
     58 
     59The class is implemented using global variables to assure uniqueness of description: 
     60 
     61 In is a vector 
     62\dot 
     63digraph datalink { 
     64rankdir=LR; 
     65subgraph cluster0 { 
     66node [shape=record]; 
     67label = "RV_MAP \n std::map<string,int>"; 
     68map [label="{{\"a\"| \"b\" | \"c\"} | {<3> 3 |<1> 1|<2> 2}}"]; 
     69color = "white" 
     70} 
     71subgraph cluster1{ 
     72node [shape=record]; 
     73label = "RV_NAMES"; 
     74names [label="{<1> \"b\" | <2> \"c\" | <3>\"a\" }"]; 
     75color = "white" 
     76} 
     77subgraph cluster2{ 
     78node [shape=record]; 
     79label = "RV_SIZES"; 
     80labelloc = b; 
     81sizes [label="{<1>1 |<2> 4 |<3> 1}"]; 
     82color = "white" 
     83} 
     84map:1 -> names:1; 
     85map:1 -> sizes:1; 
     86map:3 -> names:3; 
     87map:3 -> sizes:3; 
     88} 
     89\enddot 
     90*/ 
     91 
     92class RV :public bdmroot { 
     93protected: 
     94        //! size of the data vector 
     95        int dsize; 
     96        //! number of individual rvs 
     97        int len; 
     98        //! Vector of unique IDs 
     99        ivec ids; 
     100        //! Vector of shifts from current time 
     101        ivec times; 
     102 
     103private: 
     104        //! auxiliary function used in constructor 
     105        void init ( Array<std::string> in_names, ivec in_sizes, ivec in_times ); 
     106        int init ( const  string &name, int size ); 
     107public: 
     108        //! \name Constructors  
     109        //!@{ 
     110         
     111        //! Full constructor  
     112        RV ( Array<std::string> in_names, ivec in_sizes, ivec in_times ) {init ( in_names,in_sizes,in_times );}; 
     113        //! Constructor with times=0  
     114        RV ( Array<std::string> in_names, ivec in_sizes ) {init ( in_names,in_sizes,zeros_i ( in_names.length() ) );}; 
     115        //! Constructor with sizes=1, times=0  
     116        RV ( Array<std::string> in_names ) {init ( in_names,ones_i ( in_names.length() ),zeros_i ( in_names.length() ) );} 
     117        //! Constructor of empty RV  
     118        RV () :dsize ( 0 ),len ( 0 ),ids ( 0 ),times ( 0 ) {}; 
     119        //! Constructor of a single RV with given id 
     120        RV ( string name, int sz, int tm=0 ); 
     121        //!@} 
     122         
     123        //! \name Access functions 
     124        //!@{ 
     125         
     126        //! Printing output e.g. for debugging. 
     127        friend std::ostream &operator<< ( std::ostream &os, const RV &rv ); 
     128        int _dsize() const {return dsize;} ; 
     129        //! Recount size of the corresponding data vector 
     130        int countsize() const; 
     131        int length() const {return len;} ; 
     132        int id ( int at ) const{return ids ( at );}; 
     133        int size ( int at ) const {return RV_SIZES ( at );}; 
     134        int time ( int at ) const{return times ( at );}; 
     135        std::string name ( int at ) const {return RV_NAMES ( at );}; 
     136        void set_time ( int at, int time0 ) {times ( at ) =time0;}; 
     137        //!@} 
     138         
     139        //TODO why not inline and later?? 
     140 
     141        //! \name Algebra on Random Variables 
     142        //!@{ 
     143         
     144        //! Find indices of self in another rv, \return ivec of the same size as self. 
     145        ivec findself ( const RV &rv2 ) const; 
     146        //! Compare if \c rv2 is identical to this \c RV 
     147        bool equal ( const RV &rv2 ) const; 
     148        //! Add (concat) another variable to the current one, \return true if all rv2 were added, false if rv2 is in conflict 
     149        bool add ( const RV &rv2 ); 
     150        //! Subtract  another variable from the current one 
     151        RV subt ( const RV &rv2 ) const; 
     152        //! Select only variables at indeces ind 
     153        RV subselect ( const ivec &ind ) const; 
     154        //! Select only variables at indeces ind 
     155        RV operator() ( const ivec &ind ) const {return subselect ( ind );}; 
     156        //! Shift \c time shifted by delta. 
     157        void t ( int delta ); 
     158        //!@} 
     159         
     160        //!\name Relation to vectors  
     161        //!@{ 
     162         
     163        //! generate \c str from rv, by expanding sizes 
     164        str tostr() const; 
     165        //! when this rv is a part of bigger rv, this function returns indeces of self in the data vector of the bigger crv. 
     166        //! Then, data can be copied via: data_of_this = cdata(ind); 
     167        ivec dataind ( const RV &crv ) const; 
     168        //! generate mutual indeces when copying data betwenn self and crv. 
     169        //! Data are copied via: data_of_this(selfi) = data_of_rv2(rv2i) 
     170        void dataind ( const RV &rv2, ivec &selfi, ivec &rv2i ) const; 
     171        //! Minimum time-offset 
     172        int mint () const {return min ( times );}; 
     173        //!@} 
     174         
     175}; 
     176 
     177 
     178//! Concat two random variables 
     179RV concat ( const RV &rv1, const RV &rv2 ); 
     180 
     181//!Default empty RV that can be used as default argument 
     182extern RV RV0; 
     183 
     184//! Class representing function \f$f(x)\f$ of variable \f$x\f$ represented by \c rv 
     185 
     186class fnc :public bdmroot { 
     187protected: 
     188        //! Length of the output vector 
     189        int dimy; 
     190public: 
     191        //!default constructor 
     192        fnc ( ) {}; 
     193        //! function evaluates numerical value of \f$f(x)\f$ at \f$x=\f$ \c cond 
     194        virtual vec eval ( const vec &cond ) { 
     195                return vec ( 0 ); 
    44196        }; 
    45197 
    46         /*! 
    47         * \brief Class representing variables, most often random variables 
    48  
    49         * More?... 
    50         */ 
    51  
    52         class RV :public bdmroot { 
    53         protected: 
    54                 //! size = sum of sizes 
    55                 int tsize; 
    56                 //! len = number of individual rvs 
    57                 int len; 
    58                 //! Vector of unique IDs 
    59                 ivec ids; 
    60                 //! Vector of sizes 
    61                 ivec sizes; 
    62                 //! Vector of shifts from current time 
    63                 ivec times; 
    64                 //! Array of names 
    65                 Array<std::string> names; 
    66  
    67         private: 
    68                 //! auxiliary function used in constructor 
    69                 void init ( ivec in_ids, Array<std::string> in_names, ivec in_sizes, ivec in_times ); 
    70         public: 
    71                 //! Full constructor 
    72                 RV ( Array<std::string> in_names, ivec in_sizes, ivec in_times ); 
    73                 //! Constructor with times=0 
    74                 RV ( Array<std::string> in_names, ivec in_sizes ); 
    75                 //! Constructor with sizes=1, times=0 
    76                 RV ( Array<std::string> in_names ); 
    77                 //! Constructor of empty RV 
    78                 RV (); 
    79                 //! Constructor of a single RV with given id 
    80                 RV (string name, int id, int sz=1, int tm=0); 
    81  
    82                 //! Printing output e.g. for debugging. 
    83                 friend std::ostream &operator<< ( std::ostream &os, const RV &rv ); 
    84  
    85                 //! Return number of scalars in the RV. 
    86                 int count() const {return tsize;} ; 
    87                 //! Return length (number of entries) of the RV. 
    88                 int length() const {return len;} ; 
    89  
    90                 //TODO why not inline and later?? 
    91  
    92                 //! Find indexes of self in another rv, \return ivec of the same size as self. 
    93                 ivec findself ( const RV &rv2 ) const; 
    94                 //! Compare if \c rv2 is identical to this \c RV 
    95                 bool equal ( const RV &rv2 ) const; 
    96                 //! Add (concat) another variable to the current one, \return true if all rv2 were added, false if rv2 is in conflict 
    97                 bool add ( const RV &rv2 ); 
    98                 //! Subtract  another variable from the current one 
    99                 RV subt ( const RV &rv2 ) const; 
    100                 //! Select only variables at indeces ind 
    101                 RV subselect ( const ivec &ind ) const; 
    102                 //! Select only variables at indeces ind 
    103                 RV operator() ( const ivec &ind ) const; 
    104                 //! Shift \c time shifted by delta. 
    105                 void t ( int delta ); 
    106                 //! generate \c str from rv, by expanding sizes 
    107                 str tostr() const; 
    108                 //! when this rv is a part of bigger rv, this function returns indeces of self in the data vector of the bigger crv. 
    109                 //! Then, data can be copied via: data_of_this = cdata(ind); 
    110                 ivec dataind ( const RV &crv ) const; 
    111                 //! generate mutual indeces when copying data betwenn self and crv. 
    112                 //! Data are copied via: data_of_this(selfi) = data_of_rv2(rv2i) 
    113                 void dataind ( const RV &rv2, ivec &selfi, ivec &rv2i ) const; 
    114                 //! Minimum time-offset 
    115                 int mint () const {return min ( times );}; 
    116  
    117                 //!access function 
    118                 Array<std::string>& _names() {return names;}; 
    119  
    120                 //!access function 
    121                 int id ( int at ) {return ids ( at );}; 
    122                 //!access function 
    123                 int size ( int at ) {return sizes ( at );}; 
    124                 //!access function 
    125                 int time ( int at ) {return times ( at );}; 
    126                 //!access function 
    127                 std::string name ( int at ) {return names ( at );}; 
    128  
    129                 //!access function 
    130                 void set_id ( int at, int id0 ) {ids ( at ) =id0;}; 
    131                 //!access function 
    132                 void set_size ( int at, int size0 ) {sizes ( at ) =size0; tsize=sum ( sizes );}; 
    133                 //!access function 
    134                 void set_time ( int at, int time0 ) {times ( at ) =time0;}; 
    135  
    136                 //!Assign unused ids to this rv 
    137                 void newids(); 
    138         }; 
    139  
    140 //! Concat two random variables 
    141         RV concat ( const RV &rv1, const RV &rv2 ); 
    142  
    143 //!Default empty RV that can be used as default argument 
    144         extern RV RV0; 
    145  
    146 //! Class representing function \f$f(x)\f$ of variable \f$x\f$ represented by \c rv 
    147  
    148         class fnc :public bdmroot { 
    149         protected: 
    150                 //! Length of the output vector 
    151                 int dimy; 
    152         public: 
    153                 //!default constructor 
    154                 fnc ( int dy ) :dimy ( dy ) {}; 
    155                 //! function evaluates numerical value of \f$f(x)\f$ at \f$x=\f$ \c cond 
    156                 virtual vec eval ( const vec &cond ) { 
    157                         return vec ( 0 ); 
    158                 }; 
    159  
    160                 //! function substitutes given value into an appropriate position 
    161                 virtual void condition ( const vec &val ) {}; 
    162  
    163                 //! access function 
    164                 int _dimy() const{return dimy;} 
    165  
    166                 //! Destructor for future use; 
    167                 virtual ~fnc() {}; 
    168         }; 
    169  
    170         class mpdf; 
     198        //! function substitutes given value into an appropriate position 
     199        virtual void condition ( const vec &val ) {}; 
     200 
     201        //! access function 
     202        int _dimy() const{return dimy;} 
     203}; 
     204 
     205class mpdf; 
    171206 
    172207//! Probability density function with numerical statistics, e.g. posterior density. 
    173208 
    174         class epdf :public bdmroot { 
    175         protected: 
    176                 //! Identified of the random variable 
    177                 RV rv; 
    178         public: 
    179                 //!default constructor 
    180                 epdf() :rv ( ) {}; 
    181  
    182                 //!default constructor 
    183                 epdf ( const RV &rv0 ) :rv ( rv0 ) {}; 
    184  
    185 //      //! Returns the required moment of the epdf 
    186 //      virtual vec moment ( const int order = 1 ); 
    187  
    188                 //! Returns a sample, \f$x\f$ from density \f$epdf(rv)\f$ 
    189                 virtual vec sample () const =0; 
    190                 //! Returns N samples from density \f$epdf(rv)\f$ 
    191                 virtual mat sample_m ( int N ) const; 
    192  
    193                 //! Compute log-probability of argument \c val 
    194                 virtual double evallog ( const vec &val ) const =0; 
    195  
    196                 //! Compute log-probability of multiple values argument \c val 
    197                 virtual vec evallog_m ( const mat &Val ) const { 
    198                         vec x ( Val.cols() ); 
    199                         for ( int i=0;i<Val.cols();i++ ) {x ( i ) =evallog ( Val.get_col ( i ) ) ;} 
    200                         return x; 
    201                 } 
    202                 //! Return conditional density on the given RV, the remaining rvs will be in conditioning 
    203                 virtual mpdf* condition ( const RV &rv ) const  {it_warning ( "Not implemented" ); return NULL;} 
    204                 //! Return marginal density on the given RV, the remainig rvs are intergrated out 
    205                 virtual epdf* marginal ( const RV &rv ) const {it_warning ( "Not implemented" ); return NULL;} 
    206  
    207                 //! return expected value 
    208                 virtual vec mean() const =0; 
    209  
    210                 //! return expected variance (not covariance!) 
    211                 virtual vec variance() const = 0; 
    212  
    213                 //! Destructor for future use; 
    214                 virtual ~epdf() {}; 
    215                 //! access function, possibly dangerous! 
    216                 const RV& _rv() const {return rv;} 
    217                 //! modifier function - useful when copying epdfs 
    218                 void _renewrv ( const RV &in_rv ) {rv=in_rv;} 
    219                 //! 
    220         }; 
     209class epdf :public bdmroot { 
     210protected: 
     211        //! dimension of the random variable 
     212        int dim; 
     213        //! Description of the random variable 
     214        RV rv; 
     215 
     216public: 
     217        /*! \name Constructors 
     218         Construction of each epdf should support two types of constructors:  
     219        \li empty constructor,  
     220        \li copy constructor, 
     221         
     222        The following constructors should be supported for convenience: 
     223        \li constructor followed by calling \c set_parameters()  
     224        \li constructor accepting random variables calling \c set_rv() 
     225         
     226         All internal data structures are constructed as empty. Their values (including sizes) will be set by method \c set_parameters(). This way references can be initialized in constructors. 
     227        @{*/ 
     228        epdf() :dim(0),rv ( ) {}; 
     229        epdf(const epdf &e) :dim(e.dim),rv (e.rv) {}; 
     230        epdf(const RV &rv0) {set_rv(rv0);}; 
     231        void set_parameters(int dim0){dim=dim0;} 
     232        //!@} 
     233         
     234        //! \name Matematical Operations 
     235        //!@{ 
     236         
     237        //! Returns a sample, \f$ x \f$ from density \f$ f_x()\f$ 
     238        virtual vec sample () const {it_error("not implemneted");return vec(0);}; 
     239        //! Returns N samples, \f$ [x_1 , x_2 , \ldots \ \f$  from density \f$ f_x(rv)\f$ 
     240        virtual mat sample_m ( int N ) const; 
     241        //! Compute log-probability of argument \c val 
     242        virtual double evallog ( const vec &val ) const {it_error("not implemneted");return 0.0;}; 
     243        //! Compute log-probability of multiple values argument \c val 
     244        virtual vec evallog_m ( const mat &Val ) const { 
     245                vec x ( Val.cols() ); 
     246                for ( int i=0;i<Val.cols();i++ ) {x ( i ) =evallog ( Val.get_col ( i ) ) ;} 
     247                return x; 
     248        } 
     249        //! Return conditional density on the given RV, the remaining rvs will be in conditioning 
     250        virtual mpdf* condition ( const RV &rv ) const  {it_warning ( "Not implemented" ); return NULL;} 
     251        //! Return marginal density on the given RV, the remainig rvs are intergrated out 
     252        virtual epdf* marginal ( const RV &rv ) const {it_warning ( "Not implemented" ); return NULL;} 
     253        //! return expected value 
     254        virtual vec mean() const {it_error("not implemneted");return vec(0);}; 
     255        //! return expected variance (not covariance!) 
     256        virtual vec variance() const {it_error("not implemneted");return vec(0);}; 
     257        //!@} 
     258         
     259        //! \name Connection to other classes 
     260        //! Description of the random quantity via attribute \c rv is optional.  
     261        //! For operations such as sampling \c rv does not need to be set. However, for \c marginalization  
     262        //! and \c conditioning \c rv has to be set. NB:  
     263        //! @{ 
     264         
     265        //!Name its rv 
     266        void set_rv ( const RV &rv0 ) {rv = rv0; }//it_assert_debug(isnamed(),""); }; 
     267        //! True if rv is assigned  
     268        bool isnamed() const {bool b=( dim==rv._dsize() );return b;} 
     269        //! Return name (fails when isnamed is false) 
     270        const RV& _rv() const {it_assert_debug ( isnamed(),"" ); return rv;} 
     271        //!@} 
     272         
     273        //! \name Access to attributes 
     274        //! @{ 
     275         
     276        //! Size of the random variable 
     277        int dimension() const {return dim;} 
     278        //!@} 
     279         
     280}; 
    221281 
    222282 
     
    224284//TODO Samplecond can be generalized 
    225285 
    226         class mpdf : public bdmroot { 
    227         protected: 
    228                 //! modeled random variable 
    229                 RV rv; 
    230                 //! random variable in condition 
    231                 RV rvc; 
    232                 //! pointer to internal epdf 
    233                 epdf* ep; 
    234         public: 
    235  
    236                 //! 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  
    237                 virtual vec samplecond ( const vec &cond) { 
    238                         this->condition ( cond ); 
    239                         vec temp= ep->sample(); 
    240                         return temp; 
    241                 }; 
    242                 //! 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. 
    243                 virtual mat samplecond_m ( const vec &cond, vec &ll, int N ) { 
    244                         this->condition ( cond ); 
    245                         mat temp ( rv.count(),N ); vec smp ( rv.count() ); 
    246                         for ( int i=0;i<N;i++ ) {smp=ep->sample() ;temp.set_col ( i, smp );ll ( i ) =ep->evallog ( smp );} 
    247                         return temp; 
    248                 }; 
    249                 //! Update \c ep so that it represents this mpdf conditioned on \c rvc = cond 
    250                 virtual void condition ( const vec &cond ) {it_error ( "Not implemented" );}; 
    251  
    252                 //! Shortcut for conditioning and evaluation of the internal epdf. In some cases,  this operation can be implemented efficiently. 
    253                 virtual double evallogcond ( const vec &dt, const vec &cond ) { 
    254                         double tmp; this->condition ( cond );tmp = ep->evallog ( dt );          it_assert_debug ( std::isfinite ( tmp ),"Infinite value" ); return tmp; 
    255                 }; 
    256  
    257                 //! Matrix version of evallogcond 
    258                 virtual vec evallogcond_m ( const mat &Dt, const vec &cond ) {this->condition ( cond );return ep->evallog_m ( Dt );}; 
    259  
    260                 //! Destructor for future use; 
    261                 virtual ~mpdf() {}; 
    262  
    263                 //! Default constructor 
    264                 mpdf ( const RV &rv0, const RV &rvc0 ) :rv ( rv0 ),rvc ( rvc0 ) {}; 
    265                 //! access function 
    266                 RV _rvc() const {return rvc;} 
    267                 //! access function 
    268                 RV _rv() const {return rv;} 
    269                 //!access function 
    270                 epdf& _epdf() {return *ep;} 
    271                 //!access function 
    272                 epdf* _e() {return ep;} 
     286class mpdf : public bdmroot { 
     287protected: 
     288        //!dimension of the condition 
     289        int dimc; 
     290        //! random variable in condition 
     291        RV rvc; 
     292        //! pointer to internal epdf 
     293        epdf* ep; 
     294public: 
     295        //! \name Constructors 
     296        //! @{ 
     297         
     298        mpdf ( ) :dimc(0),rvc ( ) {}; 
     299        //! copy constructor does not set pointer \c ep - has to be done in offsprings! 
     300        mpdf (const mpdf &m ) :dimc(m.dimc),rvc (m.rvc ) {}; 
     301        //!@} 
     302 
     303        //! \name Matematical operations 
     304        //!@{ 
     305         
     306        //! 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 
     307        virtual vec samplecond ( const vec &cond ) { 
     308                this->condition ( cond ); 
     309                vec temp= ep->sample(); 
     310                return temp; 
    273311        }; 
    274  
    275         /*! \brief DataLink is a connection between two data vectors Up and Down 
    276  
    277         Up can be longer than Down. Down must be fully present in Up (TODO optional) 
    278         See chart: 
    279         \dot 
    280         digraph datalink { 
    281                 node [shape=record]; 
    282                 subgraph cluster0 { 
    283                         label = "Up"; 
    284                 up [label="<1>|<2>|<3>|<4>|<5>"]; 
    285                         color = "white" 
    286         } 
    287                 subgraph cluster1{ 
    288                         label = "Down"; 
    289                         labelloc = b; 
    290                 down [label="<1>|<2>|<3>"]; 
    291                         color = "white" 
    292         } 
    293             up:1 -> down:1; 
    294             up:3 -> down:2; 
    295             up:5 -> down:3; 
    296         } 
    297         \enddot 
    298  
    299         */ 
    300         class datalink_e2e { 
    301         protected: 
    302                 //! Remember how long val should be 
    303                 int valsize; 
    304                 //! Remember how long val of "Up" should be 
    305                 int valupsize; 
    306                 //! val-to-val link, indeces of the upper val 
    307                 ivec v2v_up; 
    308         public: 
    309                 //! Constructor 
    310                 datalink_e2e ( const RV &rv, const RV &rv_up ) : 
    311                                 valsize ( rv.count() ), valupsize ( rv_up.count() ), v2v_up ( rv.dataind ( rv_up ) )  { 
    312                         it_assert_debug ( v2v_up.length() ==valsize,"rv is not fully in rv_up" ); 
    313                 } 
    314                 //! Get val for myself from val of "Up" 
    315                 vec get_val ( const vec &val_up ) {it_assert_debug ( valupsize==val_up.length(),"Wrong val_up" ); return get_vec ( val_up,v2v_up );} 
    316                 //! Fill val of "Up" by my pieces 
    317                 void fill_val ( vec &val_up, const vec &val ) { 
    318                         it_assert_debug ( valsize==val.length(),"Wrong val" ); 
    319                         it_assert_debug ( valupsize==val_up.length(),"Wrong val_up" ); 
    320                         set_subvector ( val_up, v2v_up, val ); 
    321                 } 
     312        //! 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. 
     313        virtual mat samplecond_m ( const vec &cond, int N ) { 
     314                this->condition ( cond ); 
     315                mat temp ( ep->dimension(),N ); vec smp ( ep->dimension() ); 
     316                for ( int i=0;i<N;i++ ) {smp=ep->sample() ;temp.set_col ( i, smp );} 
     317                return temp; 
    322318        }; 
     319        //! Update \c ep so that it represents this mpdf conditioned on \c rvc = cond 
     320        virtual void condition ( const vec &cond ) {it_error ( "Not implemented" );}; 
     321 
     322        //! Shortcut for conditioning and evaluation of the internal epdf. In some cases,  this operation can be implemented efficiently. 
     323        virtual double evallogcond ( const vec &dt, const vec &cond ) { 
     324                double tmp; this->condition ( cond );tmp = ep->evallog ( dt );          it_assert_debug ( std::isfinite ( tmp ),"Infinite value" ); return tmp; 
     325        }; 
     326 
     327        //! Matrix version of evallogcond 
     328        virtual vec evallogcond_m ( const mat &Dt, const vec &cond ) {this->condition ( cond );return ep->evallog_m ( Dt );}; 
     329 
     330        //! \name Access to attributes 
     331        //! @{ 
     332         
     333        RV _rv() {return ep->_rv();} 
     334        RV _rvc() {it_assert_debug ( isnamed(),"" ); return rvc;} 
     335        int dimension() {return ep->dimension();} 
     336        int dimensionc() {return dimc;} 
     337        epdf& _epdf() {return *ep;} 
     338        epdf* _e() {return ep;} 
     339        //!@} 
     340         
     341        //! \name Connection to other objects 
     342        //!@{ 
     343        void set_rvc ( const RV &rvc0 ) {rvc=rvc0;} 
     344        void set_rv ( const RV &rv0 ) {ep->set_rv(rv0);} 
     345        bool isnamed() {return (ep->isnamed())&&(dimc==rvc._dsize());} 
     346        //!@} 
     347}; 
     348 
     349/*! \brief DataLink is a connection between two data vectors Up and Down 
     350 
     351Up can be longer than Down. Down must be fully present in Up (TODO optional) 
     352See chart: 
     353\dot 
     354digraph datalink { 
     355        node [shape=record]; 
     356        subgraph cluster0 { 
     357                label = "Up"; 
     358        up [label="<1>|<2>|<3>|<4>|<5>"]; 
     359                color = "white" 
     360} 
     361        subgraph cluster1{ 
     362                label = "Down"; 
     363                labelloc = b; 
     364        down [label="<1>|<2>|<3>"]; 
     365                color = "white" 
     366} 
     367    up:1 -> down:1; 
     368    up:3 -> down:2; 
     369    up:5 -> down:3; 
     370} 
     371\enddot 
     372 
     373*/ 
     374class datalink { 
     375protected: 
     376        //! Remember how long val should be 
     377        int downsize; 
     378        //! Remember how long val of "Up" should be 
     379        int upsize; 
     380        //! val-to-val link, indeces of the upper val 
     381        ivec v2v_up; 
     382public: 
     383        //! Constructor 
     384        datalink ( const RV &rv, const RV &rv_up ) : 
     385                        downsize ( rv._dsize() ), upsize ( rv_up._dsize() ), v2v_up ( rv.dataind ( rv_up ) )  { 
     386                it_assert_debug ( v2v_up.length() ==downsize,"rv is not fully in rv_up" ); 
     387        } 
     388        //! Get val for myself from val of "Up" 
     389        vec pushdown ( const vec &val_up ) { 
     390                it_assert_debug ( upsize==val_up.length(),"Wrong val_up" ); 
     391                return get_vec ( val_up,v2v_up ); 
     392        } 
     393        //! Fill val of "Up" by my pieces 
     394        void pushup ( vec &val_up, const vec &val ) { 
     395                it_assert_debug ( downsize==val.length(),"Wrong val" ); 
     396                it_assert_debug ( upsize==val_up.length(),"Wrong val_up" ); 
     397                set_subvector ( val_up, v2v_up, val ); 
     398        } 
     399}; 
    323400 
    324401//! data link between 
    325         class datalink_m2e: public datalink_e2e { 
    326         protected: 
    327                 //! Remember how long cond should be 
    328                 int condsize; 
    329                 //!upper_val-to-local_cond link, indeces of the upper val 
    330                 ivec v2c_up; 
    331                 //!upper_val-to-local_cond link, ideces of the local cond 
    332                 ivec v2c_lo; 
    333  
    334         public: 
    335                 //! Constructor 
    336                 datalink_m2e ( const RV &rv,  const RV &rvc, const RV &rv_up ) : 
    337                                 datalink_e2e ( rv,rv_up ), condsize ( rvc.count() ) { 
    338                         //establish v2c connection 
    339                         rvc.dataind ( rv_up, v2c_lo, v2c_up ); 
    340                 } 
    341                 //!Construct condition 
    342                 vec get_cond ( const vec &val_up ) { 
    343                         vec tmp ( condsize ); 
    344                         set_subvector ( tmp,v2c_lo,val_up ( v2c_up ) ); 
    345                         return tmp; 
    346                 } 
    347                 void fill_val_cond ( vec &val_up, const vec &val, const vec &cond ) { 
    348                         it_assert_debug ( valsize==val.length(),"Wrong val" ); 
    349                         it_assert_debug ( valupsize==val_up.length(),"Wrong val_up" ); 
    350                         set_subvector ( val_up, v2v_up, val ); 
    351                         set_subvector ( val_up, v2c_up, cond ); 
    352                 } 
    353         }; 
     402class datalink_m2e: public datalink { 
     403protected: 
     404        //! Remember how long cond should be 
     405        int condsize; 
     406        //!upper_val-to-local_cond link, indeces of the upper val 
     407        ivec v2c_up; 
     408        //!upper_val-to-local_cond link, ideces of the local cond 
     409        ivec v2c_lo; 
     410 
     411public: 
     412        //! Constructor 
     413        datalink_m2e ( const RV &rv,  const RV &rvc, const RV &rv_up ) : 
     414                        datalink ( rv,rv_up ), condsize ( rvc._dsize() ) { 
     415                //establish v2c connection 
     416                rvc.dataind ( rv_up, v2c_lo, v2c_up ); 
     417        } 
     418        //!Construct condition 
     419        vec get_cond ( const vec &val_up ) { 
     420                vec tmp ( condsize ); 
     421                set_subvector ( tmp,v2c_lo,val_up ( v2c_up ) ); 
     422                return tmp; 
     423        } 
     424        void pushup_cond ( vec &val_up, const vec &val, const vec &cond ) { 
     425                it_assert_debug ( downsize==val.length(),"Wrong val" ); 
     426                it_assert_debug ( upsize==val_up.length(),"Wrong val_up" ); 
     427                set_subvector ( val_up, v2v_up, val ); 
     428                set_subvector ( val_up, v2c_up, cond ); 
     429        } 
     430}; 
    354431//!DataLink is a connection between mpdf and its superordinate (Up) 
    355432//! This class links 
    356         class datalink_m2m: public datalink_m2e { 
    357         protected: 
    358                 //!cond-to-cond link, indeces of the upper cond 
    359                 ivec c2c_up; 
    360                 //!cond-to-cond link, indeces of the local cond 
    361                 ivec c2c_lo; 
    362         public: 
    363                 //! Constructor 
    364                 datalink_m2m ( const RV &rv, const RV &rvc, const RV &rv_up, const RV &rvc_up ) : 
    365                                 datalink_m2e ( rv, rvc, rv_up ) { 
    366                         //establish c2c connection 
    367                         rvc.dataind ( rvc_up, c2c_lo, c2c_up ); 
    368                         it_assert_debug ( c2c_lo.length() +v2c_lo.length() ==condsize, "cond is not fully given" ); 
    369                 } 
    370                 //! Get cond for myself from val and cond of "Up" 
    371                 vec get_cond ( const vec &val_up, const vec &cond_up ) { 
    372                         vec tmp ( condsize ); 
    373                         set_subvector ( tmp,v2c_lo,val_up ( v2c_up ) ); 
    374                         set_subvector ( tmp,c2c_lo,cond_up ( c2c_up ) ); 
    375                         return tmp; 
    376                 } 
    377                 //! Fill 
    378  
    379         }; 
    380  
    381         /*! 
    382         @brief Class for storing results (and semi-results) of an experiment 
    383  
    384         This class abstracts logging of results from implementation. This class replaces direct logging of results (e.g. to files or to global variables) by calling methods of a logger. Specializations of this abstract class for specific storage method are designed. 
    385          */ 
    386         class logger : public bdmroot { 
    387                 protected: 
    388                 //! RVs of all logged variables. 
    389                         Array<RV> entries; 
    390                 //! Names of logged quantities, e.g. names of algorithm variants 
    391                         Array<string> names; 
    392                 public: 
    393                 //!Default constructor 
    394                         logger ( ) : entries ( 0 ),names ( 0 ) {} 
    395  
    396                 //! returns an identifier which will be later needed for calling the log() function 
    397                         virtual int add ( const RV &rv, string name="" ) { 
    398                                 int id=entries.length(); 
    399                                 names=concat ( names, name ); // diff 
    400                                 entries.set_length ( id+1,true ); 
    401                                 entries ( id ) = rv; 
    402                                 return id; // identifier of the last entry 
    403                         } 
    404  
    405                 //! log this vector 
    406                         virtual void logit ( int id, const vec &v ) =0; 
    407  
    408                 //! Shifts storage position for another time step. 
    409                         virtual void step() =0; 
    410  
    411                 //! Finalize storing information 
    412                         virtual void finalize() {}; 
    413  
    414                 //! Initialize the storage 
    415                         virtual void init() {}; 
    416  
    417                 //! for future use 
    418                         virtual ~logger() {}; 
    419         }; 
    420  
    421         /*! \brief Unconditional mpdf, allows using epdf in the role of mpdf. 
    422  
    423         */ 
    424         class mepdf : public mpdf { 
    425         public: 
    426                 //!Default constructor 
    427                 mepdf ( const epdf* em ) :mpdf ( em->_rv(),RV() ) {ep=const_cast<epdf*> ( em );}; 
    428                 void condition ( const vec &cond ) {} 
    429         }; 
     433class datalink_m2m: public datalink_m2e { 
     434protected: 
     435        //!cond-to-cond link, indeces of the upper cond 
     436        ivec c2c_up; 
     437        //!cond-to-cond link, indeces of the local cond 
     438        ivec c2c_lo; 
     439public: 
     440        //! Constructor 
     441        datalink_m2m ( const RV &rv, const RV &rvc, const RV &rv_up, const RV &rvc_up ) : 
     442                        datalink_m2e ( rv, rvc, rv_up ) { 
     443                //establish c2c connection 
     444                rvc.dataind ( rvc_up, c2c_lo, c2c_up ); 
     445                it_assert_debug ( c2c_lo.length() +v2c_lo.length() ==condsize, "cond is not fully given" ); 
     446        } 
     447        //! Get cond for myself from val and cond of "Up" 
     448        vec get_cond ( const vec &val_up, const vec &cond_up ) { 
     449                vec tmp ( condsize ); 
     450                set_subvector ( tmp,v2c_lo,val_up ( v2c_up ) ); 
     451                set_subvector ( tmp,c2c_lo,cond_up ( c2c_up ) ); 
     452                return tmp; 
     453        } 
     454        //! Fill 
     455 
     456}; 
     457 
     458/*! 
     459@brief Class for storing results (and semi-results) of an experiment 
     460 
     461This class abstracts logging of results from implementation. This class replaces direct logging of results (e.g. to files or to global variables) by calling methods of a logger. Specializations of this abstract class for specific storage method are designed. 
     462 */ 
     463class logger : public bdmroot { 
     464protected: 
     465        //! RVs of all logged variables. 
     466        Array<RV> entries; 
     467        //! Names of logged quantities, e.g. names of algorithm variants 
     468        Array<string> names; 
     469public: 
     470        //!Default constructor 
     471        logger ( ) : entries ( 0 ),names ( 0 ) {} 
     472 
     473        //! returns an identifier which will be later needed for calling the log() function 
     474        virtual int add ( const RV &rv, string name="" ) { 
     475                int id=entries.length(); 
     476                names=concat ( names, name ); // diff 
     477                entries.set_length ( id+1,true ); 
     478                entries ( id ) = rv; 
     479                return id; // identifier of the last entry 
     480        } 
     481 
     482        //! log this vector 
     483        virtual void logit ( int id, const vec &v ) =0; 
     484 
     485        //! Shifts storage position for another time step. 
     486        virtual void step() =0; 
     487 
     488        //! Finalize storing information 
     489        virtual void finalize() {}; 
     490 
     491        //! Initialize the storage 
     492        virtual void init() {}; 
     493 
     494}; 
     495 
     496/*! \brief Unconditional mpdf, allows using epdf in the role of mpdf. 
     497 
     498*/ 
     499class mepdf : public mpdf { 
     500public: 
     501        //!Default constructor 
     502        mepdf ( const epdf* em ) :mpdf ( ) {ep=const_cast<epdf*> ( em );}; 
     503        void condition ( const vec &cond ) {} 
     504}; 
    430505 
    431506//!\brief Abstract composition of pdfs, will be used for specific classes 
    432507//!this abstract class is common to epdf and mpdf 
    433         class compositepdf { 
    434         protected: 
    435                 //!Number of mpdfs in the composite 
    436                 int n; 
    437                 //! Elements of composition 
    438                 Array<mpdf*> mpdfs; 
    439         public: 
    440                 compositepdf ( Array<mpdf*> A0 ) : n ( A0.length() ), mpdfs ( A0 ) {}; 
    441                 //! find common rv, flag \param checkoverlap modifies whether overlaps are acceptable 
    442                 RV getrv ( bool checkoverlap=false ); 
    443                 //! common rvc of all mpdfs is written to rvc 
    444                 void setrvc ( const RV &rv, RV &rvc ); 
    445         }; 
    446  
    447         /*! \brief Abstract class for discrete-time sources of data. 
    448  
    449         The class abstracts operations of: (i) data aquisition, (ii) data-preprocessing, (iii) scaling of data, and (iv) data resampling from the task of estimation and control. 
    450         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). 
    451  
     508class compositepdf { 
     509protected: 
     510        //!Number of mpdfs in the composite 
     511        int n; 
     512        //! Elements of composition 
     513        Array<mpdf*> mpdfs; 
     514public: 
     515        compositepdf ( Array<mpdf*> A0 ) : n ( A0.length() ), mpdfs ( A0 ) {}; 
     516        //! find common rv, flag \param checkoverlap modifies whether overlaps are acceptable 
     517        RV getrv ( bool checkoverlap=false ); 
     518        //! common rvc of all mpdfs is written to rvc 
     519        void setrvc ( const RV &rv, RV &rvc ); 
     520}; 
     521 
     522/*! \brief Abstract class for discrete-time sources of data. 
     523 
     524The class abstracts operations of: (i) data aquisition, (ii) data-preprocessing, (iii) scaling of data, and (iv) data resampling from the task of estimation and control. 
     525Moreover, for controlled systems, it is able to receive the desired control action and perform it in the next step. (Or as soon as possible). 
     526 
     527*/ 
     528 
     529class DS : public bdmroot { 
     530protected: 
     531        int dtsize; 
     532        int utsize; 
     533        //!Description of data returned by \c getdata(). 
     534        RV Drv; 
     535        //!Description of data witten by by \c write(). 
     536        RV Urv; // 
     537        //! Remember its own index in Logger L 
     538        int L_dt, L_ut; 
     539public: 
     540        //! default constructors 
     541        DS() :Drv (  ),Urv ( ) {}; 
     542        //! Returns full vector of observed data=[output, input] 
     543        virtual void getdata ( vec &dt ) {it_error ( "abstract class" );}; 
     544        //! Returns data records at indeces. 
     545        virtual void getdata ( vec &dt, const ivec &indeces ) {it_error ( "abstract class" );}; 
     546        //! Accepts action variable and schedule it for application. 
     547        virtual void write ( vec &ut ) {it_error ( "abstract class" );}; 
     548        //! Accepts action variables at specific indeces 
     549        virtual void write ( vec &ut, const ivec &indeces ) {it_error ( "abstract class" );}; 
     550 
     551        //! Moves from \f$ t \f$ to \f$ t+1 \f$, i.e. perfroms the actions and reads response of the system. 
     552        virtual void step() =0; 
     553 
     554        //! Register DS for logging into logger L 
     555        virtual void log_add ( logger &L ) { 
     556                it_assert_debug ( dtsize==Drv._dsize(),"" ); 
     557                it_assert_debug ( utsize==Urv._dsize(),"" ); 
     558 
     559                L_dt=L.add ( Drv,"" ); 
     560                L_ut=L.add ( Urv,"" ); 
     561        } 
     562        //! Register DS for logging into logger L 
     563        virtual void logit ( logger &L ) { 
     564                vec tmp ( Drv._dsize() +Urv._dsize() ); 
     565                getdata ( tmp ); 
     566                // d is first in getdata 
     567                L.logit ( L_dt,tmp.left ( Drv._dsize() ) ); 
     568                // u follows after d in getdata 
     569                L.logit ( L_ut,tmp.mid ( Drv._dsize(), Urv._dsize() ) ); 
     570        } 
     571        //!access function 
     572        virtual RV _drv() const {return concat ( Drv,Urv );} 
     573        //!access function 
     574        const RV& _urv() const {return Urv;} 
     575}; 
     576 
     577/*! \brief Bayesian Model of a system, i.e. all uncertainty is modeled by probabilities. 
     578 
     579*/ 
     580 
     581class BM :public bdmroot { 
     582protected: 
     583        //! Random variable of the data (optional) 
     584        RV drv; 
     585        //!Logarithm of marginalized data likelihood. 
     586        double ll; 
     587        //!  If true, the filter will compute likelihood of the data record and store it in \c ll . Set to false if you want to save computational time. 
     588        bool evalll; 
     589public: 
     590        //! \name Constructors 
     591        //! @{ 
     592         
     593        BM () :ll (0),evalll ( false) {}; 
     594        BM ( const BM &B ) :  drv(B.drv), ll ( B.ll ), evalll ( B.evalll ) {} 
     595        //! Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually! 
     596        //! Prototype: \code BM* _copy_(){return new BM(*this);} \endcode 
     597        virtual BM* _copy_ () {return NULL;}; 
     598        //!@} 
     599 
     600        //! \name Mathematical operations 
     601        //!@{ 
     602         
     603        /*! \brief Incremental Bayes rule 
     604        @param dt vector of input data 
    452605        */ 
    453  
    454         class DS : public bdmroot { 
    455         protected: 
    456                 //!Observed variables, returned by \c getdata(). 
    457                 RV Drv; 
    458                 //!Action variables, accepted by \c write(). 
    459                 RV Urv; // 
    460                 //! Remember its own index in Logger L 
    461                 int L_dt, L_ut; 
    462         public: 
    463                 DS() :Drv ( RV0 ),Urv ( RV0 ) {}; 
    464                 DS ( const RV &Drv0, const RV &Urv0 ) :Drv ( Drv0 ),Urv ( Urv0 ) {}; 
    465                 //! Returns full vector of observed data=[output, input] 
    466                 virtual void getdata ( vec &dt ) {it_error ( "abstract class" );}; 
    467                 //! Returns data records at indeces. 
    468                 virtual void getdata ( vec &dt, const ivec &indeces ) {it_error ( "abstract class" );}; 
    469                 //! Accepts action variable and schedule it for application. 
    470                 virtual void write ( vec &ut ) {it_error ( "abstract class" );}; 
    471                 //! Accepts action variables at specific indeces 
    472                 virtual void write ( vec &ut, const ivec &indeces ) {it_error ( "abstract class" );}; 
    473  
    474                 //! Moves from \f$t\f$ to \f$t+1\f$, i.e. perfroms the actions and reads response of the system. 
    475                 virtual void step() =0; 
    476  
    477                 //! Register DS for logging into logger L 
    478                 virtual void log_add ( logger &L ) { 
    479                         L_dt=L.add ( Drv,"" ); 
    480                         L_ut=L.add ( Urv,"" ); 
    481                 } 
    482                 //! Register DS for logging into logger L 
    483                 virtual void logit ( logger &L ) { 
    484                         vec tmp(Drv.count()+Urv.count()); 
    485                         getdata(tmp); 
    486                         // d is first in getdata 
    487                         L.logit ( L_dt,tmp.left ( Drv.count() ) ); 
    488                         // u follows after d in getdata 
    489                         L.logit ( L_ut,tmp.mid ( Drv.count(), Urv.count() ) ); 
    490                 } 
    491                 //!access function  
    492                 virtual RV _drv() const {return concat(Drv,Urv);} 
    493                 //!access function  
    494                 const RV& _urv() const {return Urv;} 
    495         }; 
    496  
    497         /*! \brief Bayesian Model of a system, i.e. all uncertainty is modeled by probabilities. 
    498  
    499         */ 
    500  
    501         class BM :public bdmroot { 
    502         protected: 
    503                 //!Random variable of the posterior 
    504                 RV rv; 
    505                 //! Random variable of the data (optional) 
    506                 RV drv; 
    507                 //!Logarithm of marginalized data likelihood. 
    508                 double ll; 
    509                 //!  If true, the filter will compute likelihood of the data record and store it in \c ll . Set to false if you want to save computational time. 
    510                 bool evalll; 
    511         public: 
    512  
    513                 //!Default constructor 
    514                 BM ( const RV &rv0, double ll0=0,bool evalll0=true ) :rv ( rv0 ), ll ( ll0 ),evalll ( evalll0 ) {//Fixme: test rv 
    515                 }; 
    516                 //!Copy constructor 
    517                 BM ( const BM &B ) : rv ( B.rv ), ll ( B.ll ), evalll ( B.evalll ) {} 
    518  
    519                 /*! \brief Incremental Bayes rule 
    520                 @param dt vector of input data 
    521                 */ 
    522                 virtual void bayes ( const vec &dt ) = 0; 
    523                 //! Batch Bayes rule (columns of Dt are observations) 
    524                 virtual void bayesB ( const mat &Dt ); 
    525                 //! Returns a reference to the epdf representing posterior density on parameters. 
    526                 virtual const epdf& _epdf() const =0; 
    527  
    528                 //! Returns a pointer to the epdf representing posterior density on parameters. Use with care! 
    529                 virtual const epdf* _e() const =0; 
    530  
    531                 //! Evaluates predictive log-likelihood of the given data record 
    532                 //! I.e. marginal likelihood of the data with the posterior integrated out. 
    533                 virtual double logpred ( const vec &dt ) const{it_error ( "Not implemented" );return 0.0;} 
    534                 //! Matrix version of logpred 
    535                 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;} 
    536  
    537                 //!Constructs a predictive density (marginal density on data) 
    538                 virtual epdf* predictor ( const RV &rv ) const {it_error ( "Not implemented" );return NULL;}; 
    539  
    540                 //! Destructor for future use; 
    541                 virtual ~BM() {}; 
    542                 //!access function 
    543                 const RV& _rv() const {return rv;} 
    544                 //!access function  
    545                 const RV& _drv() const {return drv;} 
    546                 //!set drv 
    547                 void set_drv(const RV &rv){drv=rv;} 
    548                 //!access function 
    549                 double _ll() const {return ll;} 
    550                 //!access function 
    551                 void set_evalll ( bool evl0 ) {evalll=evl0;} 
    552  
    553                 //! Copy function required in vectors, Arrays of BM etc. Have to be DELETED manually! 
    554                 //! Prototype: BM* _copy_(){BM Tmp*=new Tmp(this*);  return Tmp; } 
    555                 virtual BM* _copy_ ( bool changerv=false ) {it_error ( "function _copy_ not implemented for this BM" ); return NULL;}; 
    556         }; 
    557  
    558         /*! 
    559         \brief Conditional Bayesian Filter 
    560  
    561         Evaluates conditional filtering density \f$f(rv|rvc,data)\f$ for a given \c rvc which is specified in each step by calling function \c condition. 
    562  
    563         This is an interface class used to assure that certain BM has operation \c condition . 
    564  
    565         */ 
    566  
    567         class BMcond :public bdmroot { 
    568         protected: 
    569                 //! Identificator of the conditioning variable 
    570                 RV rvc; 
    571         public: 
    572                 //! Substitute \c val for \c rvc. 
    573                 virtual void condition ( const vec &val ) =0; 
    574                 //! Default constructor 
    575                 BMcond ( RV &rv0 ) :rvc ( rv0 ) {}; 
    576                 //! Destructor for future use 
    577                 virtual ~BMcond() {}; 
    578                 //! access function 
    579                 const RV& _rvc() const {return rvc;} 
    580         }; 
     606        virtual void bayes ( const vec &dt ) = 0; 
     607        //! Batch Bayes rule (columns of Dt are observations) 
     608        virtual void bayesB ( const mat &Dt ); 
     609        //! Evaluates predictive log-likelihood of the given data record 
     610        //! I.e. marginal likelihood of the data with the posterior integrated out. 
     611        virtual double logpred ( const vec &dt ) const{it_error ( "Not implemented" );return 0.0;} 
     612        //! Matrix version of logpred 
     613        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;} 
     614 
     615        //!Constructs a predictive density \f$ f(d_{t+1} |d_{t}, \ldots d_{0}) \f$ 
     616        virtual epdf* epredictor (  ) const {it_error ( "Not implemented" );return NULL;}; 
     617        //!Constructs a conditional density 1-step ahead predictor \f$ f(d_{t+1} |d_{t+h-1}, \ldots d_{t}) 
     618        virtual mpdf* predictor ( ) const {it_error ( "Not implemented" );return NULL;}; 
     619        //!@} 
     620         
     621        //! \name Access to attributes 
     622        //!@{ 
     623         
     624        const RV& _drv() const {return drv;} 
     625        void set_drv ( const RV &rv ) {drv=rv;} 
     626        double _ll() const {return ll;} 
     627        void set_evalll ( bool evl0 ) {evalll=evl0;} 
     628        virtual const epdf& _epdf() const =0; 
     629        virtual const epdf* _e() const =0; 
     630        //!@} 
     631 
     632}; 
     633 
     634/*! 
     635\brief Conditional Bayesian Filter 
     636 
     637Evaluates conditional filtering density \f$f(rv|rvc,data)\f$ for a given \c rvc which is specified in each step by calling function \c condition. 
     638 
     639This is an interface class used to assure that certain BM has operation \c condition . 
     640 
     641*/ 
     642 
     643class BMcond :public bdmroot { 
     644protected: 
     645        //! Identificator of the conditioning variable 
     646        RV rvc; 
     647public: 
     648        //! Substitute \c val for \c rvc. 
     649        virtual void condition ( const vec &val ) =0; 
     650        //! Default constructor 
     651        BMcond ( ) :rvc ( ) {}; 
     652        //! Destructor for future use 
     653        virtual ~BMcond() {}; 
     654        //! access function 
     655        const RV& _rvc() const {return rvc;} 
     656}; 
    581657 
    582658}; //namespace 
  • bdm/stat/libDS.cpp

    r267 r270  
    2626} 
    2727 
    28 void MemDS::linkrvs ( RV &drv, RV &urv ) { 
    29         it_assert_debug ( drv.count() ==rowid.length(),"MemDS::linkrvs incompatible drv" ); 
    30         it_assert_debug ( urv.count() ==0,"MemDS does not support urv." ); 
     28void MemDS::set_rvs ( RV &drv, RV &urv ) { 
     29        it_assert_debug ( drv._dsize() ==rowid.length(),"MemDS::set_rvs incompatible drv" ); 
     30        it_assert_debug ( urv._dsize() ==0,"MemDS does not support urv." ); 
    3131 
    3232        Drv = drv; 
    33         Urv = urv; 
    3433} 
    3534 
     
    4443void ArxDS::step() { 
    4544        //shift history 
    46         H.shift_right ( 0, Drv.count() +Urv.count() ); 
     45        H.shift_right ( 0, Drv._dsize() +Urv._dsize() ); 
    4746 
    48         H.set_subvector ( Drv.count(), U ); // write U after Drv 
     47        H.set_subvector ( Drv._dsize(), U ); // write U after Drv 
    4948 
    5049        //get regressor 
    51         rgr = rgrlnk.get_val ( H ); 
     50        rgr = rgrlnk->pushdown ( H ); 
    5251        // Eval Y 
    5352        H.set_subvector ( 0, model.samplecond ( rgr ) ); 
     
    6665        return T; 
    6766} 
    68  
    69 ArxDS::ArxDS ( RV &drv, RV &urv, RV &rrv ) : 
    70                 DS ( drv,urv ), Rrv ( rrv ), Hrv ( concat(drv,fullrgr ( drv,urv,rrv )) ), //RVs 
    71                 H ( Hrv.count() ) ,U ( urv.count() ),rgr ( rrv.count() ),  //tmp variables 
    72                 rgrlnk ( rrv, Hrv ) ,model ( drv,rrv ) { 
    73 } 
  • bdm/stat/libDS.h

    r267 r270  
    2323        * \brief Memory storage of off-line data column-wise 
    2424 
    25         The data are stored in an internal matrix \c Data . Each column of Data corresponds to one discrete time observation \f$t\f$. Access to this matrix is via indexes \c rowid and \c delays. 
     25        The data are stored in an internal matrix \c Data . Each column of Data corresponds to one discrete time observation \f$t\f$. Access to this matrix is via indices \c rowid and \c delays. 
    2626 
    2727        The data can be loaded from a file. 
     
    4040                void getdata ( vec &dt ); 
    4141                void getdata ( vec &dt, const ivec &indeces ); 
    42                 void linkrvs ( RV &drv, RV &urv ); 
     42                void set_rvs ( RV &drv, RV &urv ); 
    4343                void write ( vec &ut ) {it_error ( "MemDS::write is not supported" );} 
    44                 void write ( vec &ut,ivec &indexes ) {it_error ( "MemDS::write is not supported" );} 
     44                void write ( vec &ut,ivec &indices ) {it_error ( "MemDS::write is not supported" );} 
    4545                void step(); 
    4646                //!Default constructor 
     
    6565                vec rgr; 
    6666                //! data link: H -> rgr 
    67                 datalink_e2e rgrlnk; 
     67                datalink *rgrlnk; 
    6868                //! model of Y - linear Gaussian 
    6969                mlnorm<chmat> model; 
     
    7575        public: 
    7676                void getdata ( vec &dt ) { 
    77                         it_assert_debug ( dt.length() ==Drv.count(),"ArxDS" ); 
    78                         dt=H.left ( Urv.count() +Drv.count() ); 
     77                        //it_assert_debug ( dt.length() ==Drv.count(),"ArxDS" ); 
     78                        dt=H.left ( Urv._dsize() +Drv._dsize() ); 
    7979                }; 
    80                 void getdata ( vec &dt, const ivec &indexes ) { 
    81                         it_assert_debug ( dt.length() ==indeces.length(),"ArxDS" ); 
    82                         dt=H ( indexes ); 
     80                void getdata ( vec &dt, const ivec &indices ) { 
     81                        it_assert_debug ( dt.length() ==indices.length(),"ArxDS" ); 
     82                        dt=H ( indices ); 
    8383                }; 
    8484                void write ( vec &ut ) { 
    85                         it_assert_debug ( ut.length() ==Urv.count(),"ArxDS" ); 
     85                        //it_assert_debug ( ut.length() ==Urv.count(),"ArxDS" ); 
    8686                        U=ut; 
    8787                }; 
    88                 void write ( vec &ut, const ivec &indexes ) { 
    89                         it_assert_debug ( ut.length() ==indeces.length(),"ArxDS" ); 
    90                         set_subvector ( U, indexes,ut ); 
     88                void write ( vec &ut, const ivec &indices ) { 
     89                        it_assert_debug ( ut.length() ==indices.length(),"ArxDS" ); 
     90                        set_subvector ( U, indices,ut ); 
    9191                }; 
    9292                void step(); 
    9393                //!Default constructor 
    94                 ArxDS ( RV &drv, RV &urv, RV &rrv ); 
     94                ArxDS ( ){}; 
    9595                //! Set parameters of the internal model 
    9696                void set_parameters ( const mat &Th0, const vec mu0, const chmat &sqR0 ) 
     
    119119        class ARXDS : public ArxDS { 
    120120        public: 
    121                 ARXDS ( RV &drv, RV &urv, RV &rrv ) : ArxDS ( drv,urv,rrv ) {} 
     121                ARXDS ( ) : ArxDS ( ) {} 
    122122 
    123123                void getdata ( vec &dt ) {dt=H;} 
     
    145145                void getdata ( vec &dt0, const ivec &indeces ) {dt0=dt ( indeces );} 
    146146 
    147                 stateDS ( mpdf* IM0, mpdf* OM0, RV &Urv0 ) :DS ( OM0->_rv(),Urv0 ),IM ( IM0 ),OM ( OM0 ), 
    148                                 dt ( OM0->_rv().count() ), xt ( IM0->_rv().count() ), ut ( Urv0.count() ) {} 
     147                stateDS ( mpdf* IM0, mpdf* OM0, int usize ) :DS ( ),IM ( IM0 ),OM ( OM0 ), 
     148                                dt ( OM0->dimension() ), xt ( IM0->dimension() ), ut ( usize) {} 
    149149                ~stateDS() {delete IM; delete OM;} 
    150150                virtual void step() { 
    151                         double tmp; 
    152151                        xt=IM->samplecond(concat ( xt,ut )); 
    153152                        dt=OM->samplecond(concat ( xt,ut )); 
  • bdm/stat/libEF.cpp

    r262 r270  
    2222        int vend = val.length()-1; 
    2323 
    24         if ( xdim==1 ) { //same as the following, just quicker. 
     24        if ( dimx==1 ) { //same as the following, just quicker. 
    2525                double r = val ( vend ); //last entry! 
    26                 vec Psi ( nPsi+xdim ); 
     26                vec Psi ( nPsi+dimx ); 
    2727                Psi ( 0 ) = -1.0; 
    2828                Psi.set_subvector ( 1,val ( 0,vend-1 ) ); // fill the rest 
     
    3232        } 
    3333        else { 
    34                 mat Th= reshape ( val ( 0,nPsi*xdim-1 ),nPsi,xdim ); 
    35                 fsqmat R ( reshape ( val ( nPsi*xdim,vend ),xdim,xdim ) ); 
    36                 mat Tmp=concat_vertical ( -eye ( xdim ),Th ); 
    37                 fsqmat iR ( xdim ); 
     34                mat Th= reshape ( val ( 0,nPsi*dimx-1 ),nPsi,dimx ); 
     35                fsqmat R ( reshape ( val ( nPsi*dimx,vend ),dimx,dimx ) ); 
     36                mat Tmp=concat_vertical ( -eye ( dimx ),Th ); 
     37                fsqmat iR ( dimx ); 
    3838                R.inv ( iR ); 
    3939 
     
    4545        const vec& D = V._D(); 
    4646 
    47         double m = nu - nPsi -xdim-1; 
     47        double m = nu - nPsi -dimx-1; 
    4848#define log2  0.693147180559945286226763983 
    4949#define logpi 1.144729885849400163877476189 
     
    5151#define Inf std::numeric_limits<double>::infinity() 
    5252 
    53         double nkG = 0.5* xdim* ( -nPsi *log2pi + sum ( log ( D ( xdim,D.length()-1 ) ) ) ); 
     53        double nkG = 0.5* dimx* ( -nPsi *log2pi + sum ( log ( D ( dimx,D.length()-1 ) ) ) ); 
    5454        // temporary for lgamma in Wishart 
    5555        double lg=0; 
    56         for ( int i =0; i<xdim;i++ ) {lg+=lgamma ( 0.5* ( m-i ) );} 
    57  
    58         double nkW = 0.5* ( m*sum ( log ( D ( 0,xdim-1 ) ) ) ) \ 
    59                      - 0.5*xdim* ( m*log2 + 0.5* ( xdim-1 ) *log2pi )  - lg; 
     56        for ( int i =0; i<dimx;i++ ) {lg+=lgamma ( 0.5* ( m-i ) );} 
     57 
     58        double nkW = 0.5* ( m*sum ( log ( D ( 0,dimx-1 ) ) ) ) \ 
     59                     - 0.5*dimx* ( m*log2 + 0.5* ( dimx-1 ) *log2pi )  - lg; 
    6060 
    6161        it_assert_debug ( ( ( -nkG-nkW ) >-Inf ) && ( ( -nkG-nkW ) <Inf ), "ARX improper" ); 
     
    6565vec egiw::mean() const { 
    6666 
    67         if ( xdim==1 ) { 
     67        if ( dimx==1 ) { 
    6868                const mat &L= V._L(); 
    6969                const vec &D= V._D(); 
    7070                int end = L.rows()-1; 
    7171 
    72                 vec m ( rv.count() ); 
    73                 mat iLsub = ltuinv ( L ( xdim,end,xdim,end ) ); 
     72                vec m ( dim ); 
     73                mat iLsub = ltuinv ( L ( dimx,end,dimx,end ) ); 
    7474 
    7575                vec L0 = L.get_col ( 0 ); 
    7676 
    7777                m.set_subvector ( 0,iLsub*L0 ( 1,end ) ); 
    78                 m ( end ) = D ( 0 ) / ( nu -nPsi -2*xdim -2 ); 
     78                m ( end ) = D ( 0 ) / ( nu -nPsi -2*dimx -2 ); 
    7979                return m; 
    8080        } 
     
    9090vec egiw::variance() const { 
    9191 
    92         if ( xdim==1 ) { 
     92        if ( dimx==1 ) { 
    9393                int l=V.rows(); 
    9494                const ldmat tmp(V,linspace(1,l-1)); 
    9595                ldmat itmp(l); 
    9696                tmp.inv(itmp); 
    97                 double cove = V._D() ( 0 ) / ( nu -nPsi -2*xdim -2 ); 
     97                double cove = V._D() ( 0 ) / ( nu -nPsi -2*dimx -2 ); 
    9898                 
    9999                vec var(l); 
    100100                var.set_subvector(0,diag(itmp.to_mat())*cove); 
    101                 var(l-1)=cove*cove/( nu -nPsi -2*xdim -2 ); 
     101                var(l-1)=cove*cove/( nu -nPsi -2*dimx -2 ); 
    102102                return var; 
    103103        } 
     
    110110        int end = L.rows()-1; 
    111111 
    112         ldmat ldR ( L ( 0,xdim-1,0,xdim-1 ), D ( 0,xdim-1 ) / ( nu -nPsi -2*xdim -2 ) ); //exp val of R 
    113         mat iLsub=ltuinv ( L ( xdim,end,xdim,end ) ); 
     112        ldmat ldR ( L ( 0,dimx-1,0,dimx-1 ), D ( 0,dimx-1 ) / ( nu -nPsi -2*dimx -2 ) ); //exp val of R 
     113        mat iLsub=ltuinv ( L ( dimx,end,dimx,end ) ); 
    114114 
    115115        // set mean value 
    116         mat Lpsi = L ( xdim,end,0,xdim-1 ); 
     116        mat Lpsi = L ( dimx,end,0,dimx-1 ); 
    117117        M= iLsub*Lpsi; 
    118118        R= ldR.to_mat()  ; 
     
    120120 
    121121vec egamma::sample() const { 
    122         vec smp ( rv.count() ); 
     122        vec smp ( dim); 
    123123        int i; 
    124124 
    125         for ( i=0; i<rv.count(); i++ ) { 
     125        for ( i=0; i<dim; i++ ) { 
    126126                if ( beta ( i ) >std::numeric_limits<double>::epsilon() ) { 
    127127                        GamRNG.setup ( alpha ( i ),beta ( i ) ); 
     
    156156        int i; 
    157157 
    158         for ( i=0; i<rv.count(); i++ ) { 
     158        for ( i=0; i<dim; i++ ) { 
    159159                res += ( alpha ( i ) - 1 ) *std::log ( val ( i ) ) - beta ( i ) *val ( i ); 
    160160        } 
     
    168168        int i; 
    169169 
    170         for ( i=0; i<rv.count(); i++ ) { 
     170        for ( i=0; i<dim; i++ ) { 
    171171                res += lgamma ( alpha ( i ) ) - alpha ( i ) *std::log ( beta ( i ) ) ; 
    172172        } 
     
    176176 
    177177//MGamma 
    178 void mgamma::set_parameters ( double k0 ) { 
     178void mgamma::set_parameters ( double k0, const vec &beta0 ) { 
    179179        k=k0; 
    180180        ep = &epdf; 
    181         epdf.set_parameters ( k*ones ( rv.count() ),*_beta ); 
     181        epdf.set_parameters ( k*ones ( beta0.length()),beta0 ); 
     182        dimc = ep->dimension(); 
    182183}; 
    183184 
     
    273274        n=w.length(); 
    274275        samples.set_size ( n ); 
     276        dim = epdf0->dimension(); 
    275277 
    276278        for ( int i=0;i<n;i++ ) {samples ( i ) =epdf0->sample();} 
  • bdm/stat/libEF.h

    r262 r270  
    1919//#include <std> 
    2020 
    21 namespace bdm{ 
     21namespace bdm { 
    2222 
    2323 
     
    3939//      eEF() :epdf() {}; 
    4040        //! default constructor 
    41         eEF ( const RV &rv ) :epdf ( rv ) {}; 
     41        eEF ( ) :epdf ( ) {}; 
    4242        //! logarithm of the normalizing constant, \f$\mathcal{I}\f$ 
    4343        virtual double lognc() const =0; 
     
    4747        virtual double evallog_nn ( const vec &val ) const{it_error ( "Not implemented" );return 0.0;}; 
    4848        //!Evaluate normalized log-probability 
    49         virtual double evallog ( const vec &val ) const {double tmp;tmp= evallog_nn ( val )-lognc();it_assert_debug(std::isfinite(tmp),"Infinite value"); return tmp;} 
     49        virtual double evallog ( const vec &val ) const {double tmp;tmp= evallog_nn ( val )-lognc();it_assert_debug ( std::isfinite ( tmp ),"Infinite value" ); return tmp;} 
    5050        //!Evaluate normalized log-probability for many samples 
    5151        virtual vec evallog ( const mat &Val ) const { 
     
    6868public: 
    6969        //! Default constructor 
    70         mEF ( const RV &rv0, const RV &rvc0 ) :mpdf ( rv0,rvc0 ) {}; 
     70        mEF ( ) :mpdf ( ) {}; 
    7171}; 
    7272 
     
    7979        double last_lognc; 
    8080public: 
    81         //! Default constructor 
    82         BMEF ( const RV &rv, double frg0=1.0 ) :BM ( rv ), frg ( frg0 ) {} 
     81        //! Default constructor (=empty constructor) 
     82        BMEF ( double frg0=1.0 ) :BM ( ), frg ( frg0 ) {} 
    8383        //! Copy constructor 
    8484        BMEF ( const BMEF &B ) :BM ( B ), frg ( B.frg ), last_lognc ( B.last_lognc ) {} 
     
    112112        //! Covariance matrix in decomposed form 
    113113        sq_T R; 
    114         //! dimension (redundant from rv.count() for easier coding ) 
    115         int dim; 
    116 public: 
    117         //!Default constructor 
    118         enorm ( const RV &rv ); 
    119         //! Set mean value \c mu and covariance \c R 
     114public: 
     115        //!\name Constructors 
     116        //!@{ 
     117 
     118        enorm ( ):eEF ( ), mu ( ),R ( ) {}; 
     119        enorm ( const vec &mu,const sq_T &R ) {set_parameters ( mu,R );} 
    120120        void set_parameters ( const vec &mu,const sq_T &R ); 
    121         ////! tupdate in exponential form (not really handy) 
    122         //void tupdate ( double phi, mat &vbar, double nubar ); 
     121        //!@} 
     122 
     123        //! \name Mathematical operations 
     124        //!@{ 
     125 
    123126        //! dupdate in exponential form (not really handy) 
    124127        void dupdate ( mat &v,double nu=1.0 ); 
    125128 
    126129        vec sample() const; 
    127         //! TODO is it used? 
    128130        mat sample ( int N ) const; 
    129 //      double eval ( const vec &val ) const ; 
    130131        double evallog_nn ( const vec &val ) const; 
    131132        double lognc () const; 
    132133        vec mean() const {return mu;} 
    133         vec variance() const {return diag(R.to_mat());} 
     134        vec variance() const {return diag ( R.to_mat() );} 
    134135//      mlnorm<sq_T>* condition ( const RV &rvn ) const ; 
    135136        mpdf* condition ( const RV &rvn ) const ; 
    136137//      enorm<sq_T>* marginal ( const RV &rv ) const; 
    137138        epdf* marginal ( const RV &rv ) const; 
    138 //Access methods 
    139         //! returns a pointer to the internal mean value. Use with Care! 
     139        //!@} 
     140 
     141        //! \name Access to attributes 
     142        //!@{ 
     143 
    140144        vec& _mu() {return mu;} 
    141  
    142         //! access function 
    143145        void set_mu ( const vec mu0 ) { mu=mu0;} 
    144  
    145         //! returns pointers to the internal variance and its inverse. Use with Care! 
    146146        sq_T& _R() {return R;} 
    147147        const sq_T& _R() const {return R;} 
    148  
    149         //! access method 
    150 //      mat getR () {return R.to_mat();} 
     148        //!@} 
     149 
    151150}; 
    152151 
     
    164163        double nu; 
    165164        //! Dimension of the output 
    166         int xdim; 
     165        int dimx; 
    167166        //! Dimension of the regressor 
    168167        int nPsi; 
    169168public: 
    170         //!Default constructor, if nu0<0 a minimal nu0 will be computed 
    171         egiw ( RV rv, mat V0, double nu0=-1.0 ) : eEF ( rv ), V ( V0 ), nu ( nu0 ) { 
    172                 xdim = rv.count() /V.rows(); 
    173                 it_assert_debug ( rv.count() ==xdim*V.rows(),"Incompatible V0." ); 
    174                 nPsi = V.rows()-xdim; 
    175                 //set mu to have proper normalization and  
    176                 if (nu0<0){ 
    177                         nu = 0.1 +nPsi +2*xdim +2; // +2 assures finite expected value of R 
     169        //!\name Constructors 
     170        //!@{ 
     171        egiw() :eEF() {}; 
     172        egiw ( int dimx0, ldmat V0, double nu0=-1.0 ) :eEF() {set_parameters ( dimx0,V0, nu0 );}; 
     173 
     174        void set_parameters ( int dimx0, ldmat V0, double nu0=-1.0 ) { 
     175                dimx=dimx0; 
     176                nPsi = V0.rows()-dimx; 
     177                dim = dimx* ( dimx+nPsi ); // size(R) + size(Theta) 
     178 
     179                V=V0; 
     180                if ( nu0<0 ) { 
     181                        nu = 0.1 +nPsi +2*dimx +2; // +2 assures finite expected value of R 
    178182                        // terms before that are sufficient for finite normalization 
    179183                } 
    180         } 
    181         //!Full constructor for V in ldmat form 
    182         egiw ( RV rv, ldmat V0, double nu0=-1.0 ) : eEF ( rv ), V ( V0 ), nu ( nu0 ) { 
    183                 xdim = rv.count() /V.rows(); 
    184                 it_assert_debug ( rv.count() ==xdim*V.rows(),"Incompatible V0." ); 
    185                 nPsi = V.rows()-xdim; 
    186                 if (nu0<0){ 
    187                         nu = 0.1 +nPsi +2*xdim +2; // +2 assures finite expected value of R 
    188                         // terms before that are sufficient for finite normalization 
     184                else { 
     185                        nu=nu0; 
    189186                } 
    190187        } 
     188        //!@} 
    191189 
    192190        vec sample() const; 
     
    197195        double evallog_nn ( const vec &val ) const; 
    198196        double lognc () const; 
    199  
    200         //Access 
    201         //! returns a pointer to the internal statistics. Use with Care! 
     197        void pow ( double p ) {V*=p;nu*=p;}; 
     198 
     199        //! \name Access attributes 
     200        //!@{ 
     201 
    202202        ldmat& _V() {return V;} 
    203         //! returns a pointer to the internal statistics. Use with Care! 
    204203        const ldmat& _V() const {return V;} 
    205         //! returns a pointer to the internal statistics. Use with Care! 
    206204        double& _nu()  {return nu;} 
    207205        const double& _nu() const {return nu;} 
    208         void pow ( double p ) {V*=p;nu*=p;}; 
     206        //!@} 
    209207}; 
    210208 
     
    224222        double gamma; 
    225223public: 
    226         //!Default constructor 
    227         eDirich ( const RV &rv, const vec &beta0 ) : eEF ( rv ),beta ( beta0 ) {it_assert_debug ( rv.count() ==beta.length(),"Incompatible statistics" ); }; 
    228         //! Copy constructor 
    229         eDirich ( const eDirich &D0 ) : eEF ( D0.rv ),beta ( D0.beta ) {}; 
     224        //!\name Constructors 
     225        //!@{ 
     226 
     227        eDirich () : eEF ( ) {}; 
     228        eDirich ( const eDirich &D0 ) : eEF () {set_parameters ( D0.beta );}; 
     229        eDirich ( const vec &beta0 ) {set_parameters ( beta0 );}; 
     230        void set_parameters ( const vec &beta0 ) { 
     231                beta= beta0; 
     232                dim = beta.length(); 
     233                gamma = sum ( beta ); 
     234        } 
     235        //!@} 
     236 
    230237        vec sample() const {it_error ( "Not implemented" );return vec_1 ( 0.0 );}; 
    231238        vec mean() const {return beta/gamma;}; 
    232         vec variance() const {return elem_mult(beta,(beta+1))/ (gamma*(gamma+1));} 
     239        vec variance() const {return elem_mult ( beta, ( beta+1 ) ) / ( gamma* ( gamma+1 ) );} 
    233240        //! In this instance, val is ... 
    234         double evallog_nn ( const vec &val ) const {double tmp; tmp=( beta-1 ) *log ( val );            it_assert_debug(std::isfinite(tmp),"Infinite value"); 
    235         return tmp;}; 
     241        double evallog_nn ( const vec &val ) const { 
     242                double tmp; tmp= ( beta-1 ) *log ( val );               it_assert_debug ( std::isfinite ( tmp ),"Infinite value" ); 
     243                return tmp; 
     244        }; 
    236245        double lognc () const { 
    237246                double tmp; 
     
    240249                for ( int i=0;i<beta.length();i++ ) {lgb+=lgamma ( beta ( i ) );} 
    241250                tmp= lgb-lgamma ( gam ); 
    242                 it_assert_debug(std::isfinite(tmp),"Infinite value"); 
     251                it_assert_debug ( std::isfinite ( tmp ),"Infinite value" ); 
    243252                return tmp; 
    244253        }; 
     
    246255        vec& _beta()  {return beta;} 
    247256        //!Set internal parameters 
    248         void set_parameters ( const vec &beta0 ) { 
    249                 if ( beta0.length() !=beta.length() ) { 
    250                         it_assert_debug ( rv.length() ==1,"Undefined" ); 
    251                         rv.set_size ( 0,beta0.length() ); 
    252                 } 
    253                 beta= beta0; 
    254                 gamma = sum(beta); 
    255         } 
    256257}; 
    257258 
     
    265266public: 
    266267        //!Default constructor 
    267         multiBM ( const RV &rv, const vec beta0 ) : BMEF ( rv ),est ( rv,beta0 ),beta ( est._beta() ) {if(beta.length()>0){last_lognc=est.lognc();}else{last_lognc=0.0;}} 
     268        multiBM ( ) : BMEF ( ),est ( ),beta ( est._beta() ) {if ( beta.length() >0 ) {last_lognc=est.lognc();}else{last_lognc=0.0;}} 
    268269        //!Copy constructor 
    269         multiBM ( const multiBM &B ) : BMEF ( B ),est ( rv,B.beta ),beta ( est._beta() ) {} 
     270        multiBM ( const multiBM &B ) : BMEF ( B ),est ( B.est ),beta ( est._beta() ) {} 
    270271        //! Sets sufficient statistics to match that of givefrom mB0 
    271272        void set_statistics ( const BM* mB0 ) {const multiBM* mB=dynamic_cast<const multiBM*> ( mB0 ); beta=mB->beta;} 
     
    300301        void set_parameters ( const vec &beta0 ) { 
    301302                est.set_parameters ( beta0 ); 
    302                 rv = est._rv(); 
    303303                if ( evalll ) {last_lognc=est.lognc();} 
    304304        } 
     
    321321        vec beta; 
    322322public : 
    323         //! Default constructor 
    324         egamma ( const RV &rv ) :eEF ( rv ), alpha(rv.count()), beta(rv.count()) {}; 
    325         //! Sets parameters 
    326         void set_parameters ( const vec &a, const vec &b ) {alpha=a,beta=b;}; 
     323        //! \name Constructors 
     324        //!@{ 
     325        egamma ( ) :eEF ( ), alpha(), beta() {}; 
     326        egamma ( const vec &a, const vec &b ) {set_parameters ( a, b );}; 
     327        void set_parameters ( const vec &a, const vec &b ) {alpha=a,beta=b;dim = alpha.length();}; 
     328        //!@} 
     329 
    327330        vec sample() const; 
    328331        //! TODO: is it used anywhere? 
     
    331334        double lognc () const; 
    332335        //! Returns poiter to alpha and beta. Potentially dengerous: use with care! 
    333         void _param ( vec* &a, vec* &b ) {a=&alpha;b=&beta;}; 
    334         vec mean() const {return elem_div(alpha,beta);} 
    335         vec variance() const {return elem_div(alpha,elem_mult(beta,beta)); } 
     336        vec& _alpha() {return alpha;} 
     337        vec& _beta() {return beta;} 
     338        vec mean() const {return elem_div ( alpha,beta );} 
     339        vec variance() const {return elem_div ( alpha,elem_mult ( beta,beta ) ); } 
    336340}; 
    337341 
     
    351355 
    352356class eigamma : public eEF { 
    353         protected: 
     357protected: 
     358        //!internal egamma 
     359        egamma eg; 
    354360        //! Vector \f$\alpha\f$ 
    355                 vec* alpha; 
     361        vec &alpha; 
    356362        //! Vector \f$\beta\f$ (in fact it is 1/beta as used in definition of iG) 
    357                 vec* beta; 
    358                 //!internal egamma 
    359                 egamma eg; 
    360         public : 
    361         //! Default constructor 
    362                 eigamma ( const RV &rv ) :eEF ( rv ), eg(rv) {eg._param(alpha,beta);}; 
    363         //! Sets parameters 
    364                 void set_parameters ( const vec &a, const vec &b ) {*alpha=a,*beta=b;}; 
    365                 vec sample() const {return 1.0/eg.sample();}; 
     363        vec &beta; 
     364public : 
     365        //! \name Constructors 
     366        //!@{ 
     367        eigamma ( ) :eEF ( ), eg(),alpha ( eg._alpha() ), beta ( eg._beta() ) {}; 
     368        eigamma ( const vec &a, const vec &b ):eEF ( ), eg(),alpha ( eg._alpha() ), beta ( eg._beta() ) {eg.set_parameters ( a,b );}; 
     369        void set_parameters ( const vec &a, const vec &b ) {eg.set_parameters ( a,b );}; 
     370        //!@} 
     371 
     372        vec sample() const {return 1.0/eg.sample();}; 
    366373        //! TODO: is it used anywhere? 
    367374//      mat sample ( int N ) const; 
    368                 double evallog ( const vec &val ) const {return eg.evallog(val);}; 
    369                 double lognc () const {return eg.lognc();}; 
     375        double evallog ( const vec &val ) const {return eg.evallog ( val );}; 
     376        double lognc () const {return eg.lognc();}; 
    370377        //! Returns poiter to alpha and beta. Potentially dangerous: use with care! 
    371                 void _param ( vec* &a, vec* &b ) {a=alpha;b=beta;}; 
    372                 vec mean() const {return elem_div(*beta,*alpha-1);} 
    373                 vec variance() const {vec mea=mean(); return elem_div(elem_mult(mea,mea),*alpha-2);} 
     378        vec mean() const {return elem_div ( beta,alpha-1 );} 
     379        vec variance() const {vec mea=mean(); return elem_div ( elem_mult ( mea,mea ),alpha-2 );} 
     380        vec& _alpha() {return alpha;} 
     381        vec& _beta() {return beta;} 
    374382}; 
    375383/* 
     
    404412        double lnk; 
    405413public: 
    406         //! Defualt constructor 
    407         euni ( const RV rv ) :epdf ( rv ) {} 
    408         double eval ( const vec &val ) const  {return nk;} 
    409         double evallog ( const vec &val ) const  {return lnk;} 
    410         vec sample() const { 
    411                 vec smp ( rv.count() ); 
    412 #pragma omp critical 
    413                 UniRNG.sample_vector ( rv.count(),smp ); 
    414                 return low+elem_mult ( distance,smp ); 
    415         } 
    416         //! set values of \c low and \c high 
     414        //! \name Constructors 
     415        //!@{ 
     416        euni ( ) :epdf ( ) {} 
     417        euni ( const vec &low0, const vec &high0 ) {set_parameters ( low0,high0 );} 
    417418        void set_parameters ( const vec &low0, const vec &high0 ) { 
    418419                distance = high0-low0; 
     
    422423                nk = prod ( 1.0/distance ); 
    423424                lnk = log ( nk ); 
    424         } 
    425         vec mean() const {return (high-low)/2.0;} 
    426         vec variance() const {return (pow(high,2)+pow(low,2)+elem_mult(high,low))/3.0;} 
     425                dim = low.length(); 
     426        } 
     427        //!@} 
     428 
     429        double eval ( const vec &val ) const  {return nk;} 
     430        double evallog ( const vec &val ) const  {return lnk;} 
     431        vec sample() const { 
     432                vec smp ( dim ); 
     433#pragma omp critical 
     434                UniRNG.sample_vector ( dim ,smp ); 
     435                return low+elem_mult ( distance,smp ); 
     436        } 
     437        //! set values of \c low and \c high 
     438        vec mean() const {return ( high-low ) /2.0;} 
     439        vec variance() const {return ( pow ( high,2 ) +pow ( low,2 ) +elem_mult ( high,low ) ) /3.0;} 
    427440}; 
    428441 
     
    442455        vec& _mu; //cached epdf.mu; 
    443456public: 
    444         //! Constructor 
    445         mlnorm ( const RV &rv, const RV &rvc ); 
     457        //! \name Constructors 
     458        //!@{ 
     459        mlnorm ( ) :mEF (),epdf ( ),A ( ),_mu ( epdf._mu() ) {ep =&epdf; }; 
     460        mlnorm ( const  mat &A, const vec &mu0, const sq_T &R ) :epdf ( ),_mu ( epdf._mu() ) { 
     461                ep =&epdf; set_parameters ( A,mu0,R ); 
     462        }; 
    446463        //! Set \c A and \c R 
    447464        void set_parameters ( const  mat &A, const vec &mu0, const sq_T &R ); 
    448 //      //!Generate one sample of the posterior 
    449 //      vec samplecond (const vec &cond, double &lik ); 
    450 //      //!Generate matrix of samples of the posterior 
    451 //      mat samplecond (const vec &cond, vec &lik, int n ); 
     465        //!@} 
    452466        //! Set value of \c rvc . Result of this operation is stored in \c epdf use function \c _ep to access it. 
    453467        void condition ( const vec &cond ); 
     
    466480/*! (Approximate) Student t density with linear function of mean value 
    467481 
    468 The internal epdf of this class is of the type of a Gaussian (enorm).  
     482The internal epdf of this class is of the type of a Gaussian (enorm). 
    469483However, each conditioning is trying to assure the best possible approximation by taking into account the zeta function. See [] for reference. 
    470484 
    471 Perhaps a moment-matching technique?  
     485Perhaps a moment-matching technique? 
    472486*/ 
    473487class mlstudent : public mlnorm<ldmat> { 
     
    477491        ldmat Re; 
    478492public: 
    479         mlstudent ( const RV &rv0, const RV &rvc0 ) :mlnorm<ldmat> ( rv0,rvc0 ), 
    480                         Lambda ( rv0.count() ), 
    481                         _R ( epdf._R() ) {} 
    482         void set_parameters ( const mat &A0, const vec &mu0, const ldmat &R0, const ldmat& Lambda0) { 
    483                 epdf.set_parameters ( zeros ( rv.count() ),Lambda ); 
     493        mlstudent ( ) :mlnorm<ldmat> (), 
     494                        Lambda (),      _R ( epdf._R() ) {} 
     495        void set_parameters ( const mat &A0, const vec &mu0, const ldmat &R0, const ldmat& Lambda0 ) { 
     496                it_assert_debug ( A0.rows() ==mu0.length(),"" ); 
     497                it_assert_debug ( R0.rows() ==A0.rows(),"" ); 
     498 
     499                epdf.set_parameters ( mu0,Lambda ); // 
    484500                A = A0; 
    485501                mu_const = mu0; 
     
    491507                double zeta; 
    492508                //ugly hack! 
    493                 if ((cond.length()+1)==Lambda.rows()){ 
    494                         zeta = Lambda.invqform ( concat(cond, vec_1(1.0)) ); 
    495                 } else { 
     509                if ( ( cond.length() +1 ) ==Lambda.rows() ) { 
     510                        zeta = Lambda.invqform ( concat ( cond, vec_1 ( 1.0 ) ) ); 
     511                } 
     512                else { 
    496513                        zeta = Lambda.invqform ( cond ); 
    497514                } 
    498515                _R = Re; 
    499                 _R*=( 1+zeta );// / ( nu ); << nu is in Re!!!!!! 
     516                _R*= ( 1+zeta );// / ( nu ); << nu is in Re!!!!!! 
    500517        }; 
    501518 
     
    517534        double k; 
    518535        //! cache of epdf.beta 
    519         vec* _beta; 
     536        vec &_beta; 
    520537 
    521538public: 
    522539        //! Constructor 
    523         mgamma ( const RV &rv,const RV &rvc ): mEF ( rv,rvc ), epdf ( rv ) {vec* tmp; epdf._param ( tmp,_beta );ep=&epdf;}; 
     540        mgamma ( ) : mEF ( ), epdf (), _beta ( epdf._beta() ) {ep=&epdf;}; 
    524541        //! Set value of \c k 
    525         void set_parameters ( double k ); 
    526         void condition ( const vec &val ) {*_beta=k/val;}; 
     542        void set_parameters ( double k, const vec &beta0 ); 
     543        void condition ( const vec &val ) {_beta=k/val;}; 
    527544}; 
    528545 
     
    530547\brief  Inverse-Gamma random walk 
    531548 
    532 Mean value, \f$\mu\f$, of this density is given by \c rvc . 
    533 Standard deviation of the random walk is proportional to one \f$k\f$-th the mean. 
    534 This is achieved by setting \f$\alpha=\mu/k+2\f$ and \f$\beta=\mu(\alpha-1)\f$. 
    535  
    536 The standard deviation of the walk is then: \f$\mu/\sqrt(k)\f$. 
     549Mean value, \f$ \mu \f$, of this density is given by \c rvc . 
     550Standard deviation of the random walk is proportional to one \f$ k \f$-th the mean. 
     551This is achieved by setting \f$ \alpha=\mu/k^2+2 \f$ and \f$ \beta=\mu(\alpha-1)\f$. 
     552 
     553The standard deviation of the walk is then: \f$ \mu/\sqrt(k)\f$. 
    537554 */ 
    538555class migamma : public mEF { 
    539         protected: 
     556protected: 
    540557        //! Internal epdf that arise by conditioning on \c rvc 
    541                 eigamma epdf; 
     558        eigamma epdf; 
    542559        //! Constant \f$k\f$ 
    543                 double k; 
     560        double k; 
     561        //! cache of epdf.alpha 
     562        vec &_alpha; 
    544563        //! cache of epdf.beta 
    545                 vec* _beta; 
    546                 //! chaceh of epdf.alpha 
    547                 vec* _alpha; 
    548  
    549         public: 
    550         //! Constructor 
    551                 migamma ( const RV &rv,const RV &rvc ): mEF ( rv,rvc ), epdf ( rv ) {epdf._param ( _alpha,_beta );ep=&epdf;}; 
     564        vec &_beta; 
     565 
     566public: 
     567        //! \name Constructors 
     568        //!@{ 
     569        migamma ( ) : mEF (), epdf ( ), _alpha ( epdf._alpha() ), _beta ( epdf._beta() ) {ep=&epdf;}; 
     570        migamma ( const migamma &m ) : mEF (), epdf ( m.epdf ), _alpha ( epdf._alpha() ), _beta ( epdf._beta() ) {ep=&epdf;}; 
     571        //!@} 
     572 
    552573        //! Set value of \c k 
    553                 void set_parameters ( double k0 ){k=k0;*_alpha=1.0/(k*k)+2;}; 
    554                 void condition ( const vec &val ) { 
    555                         *_beta=elem_mult(val,(*_alpha-1)); 
    556                 }; 
     574        void set_parameters ( int len, double k0 ) { 
     575                k=k0; 
     576                epdf.set_parameters ( ( 1.0/ ( k*k ) +2.0 ) *ones ( len ) /*alpha*/, ones ( len ) /*beta*/ ); 
     577                dimc = dimension(); 
     578        }; 
     579        void condition ( const vec &val ) { 
     580                _beta=elem_mult ( val, ( _alpha-1.0 ) ); 
     581        }; 
    557582}; 
    558583 
     
    576601public: 
    577602        //! Constructor 
    578         mgamma_fix ( const RV &rv,const RV &rvc ) : mgamma ( rv,rvc ),refl ( rv.count() ) {}; 
     603        mgamma_fix ( ) : mgamma ( ),refl () {}; 
    579604        //! Set value of \c k 
    580605        void set_parameters ( double k0 , vec ref0, double l0 ) { 
    581                 mgamma::set_parameters ( k0 ); 
     606                mgamma::set_parameters ( k0, ref0 ); 
    582607                refl=pow ( ref0,1.0-l0 );l=l0; 
     608                dimc=dimension(); 
    583609        }; 
    584610 
    585         void condition ( const vec &val ) {vec mean=elem_mult ( refl,pow ( val,l ) ); *_beta=k/mean;}; 
     611        void condition ( const vec &val ) {vec mean=elem_mult ( refl,pow ( val,l ) ); _beta=k/mean;}; 
    586612}; 
    587613 
     
    600626 */ 
    601627class migamma_fix : public migamma { 
    602         protected: 
     628protected: 
    603629        //! parameter l 
    604                 double l; 
     630        double l; 
    605631        //! reference vector 
    606                 vec refl; 
    607         public: 
     632        vec refl; 
     633public: 
    608634        //! Constructor 
    609                 migamma_fix ( const RV &rv,const RV &rvc ) : migamma ( rv,rvc ),refl ( rv.count() ) {}; 
     635        migamma_fix ( ) : migamma (),refl ( ) {}; 
    610636        //! Set value of \c k 
    611                 void set_parameters ( double k0 , vec ref0, double l0 ) { 
    612                         migamma::set_parameters ( k0 ); 
    613                         refl=pow ( ref0,1.0-l0 );l=l0; 
    614                 }; 
    615  
    616                 void condition ( const vec &val ) {vec mean=elem_mult ( refl,pow ( val,l ) ); migamma::condition(mean);}; 
     637        void set_parameters ( double k0 , vec ref0, double l0 ) { 
     638                migamma::set_parameters ( ref0.length(), k0 ); 
     639                refl=pow ( ref0,1.0-l0 ); 
     640                l=l0; 
     641                dimc = dimension(); 
     642        }; 
     643 
     644        void condition ( const vec &val ) { 
     645                vec mean=elem_mult ( refl,pow ( val,l ) ); 
     646                migamma::condition ( mean ); 
     647        }; 
    617648}; 
    618649//! Switch between various resampling methods. 
     
    632663        Array<vec> samples; 
    633664public: 
    634         //! Default constructor 
    635         eEmp ( const RV &rv0 ,int n0 ) :epdf ( rv0 ),n ( n0 ),w ( n ),samples ( n ) {}; 
     665        //! \name Constructors  
     666        //!@{ 
     667        eEmp ( ) :epdf ( ),w (  ),samples ( ) {}; 
     668        eEmp (const eEmp &e ): epdf(e), w(e.w), samples(e.samples) {}; 
     669        //!@} 
     670         
    636671        //! Set samples and weights 
    637672        void set_parameters ( const vec &w0, const epdf* pdf0 ); 
     
    639674        void set_samples ( const epdf* pdf0 ); 
    640675        //! Set sample 
    641         void set_n ( int n0, bool copy=true ){w.set_size(n0,copy);samples.set_size(n0,copy);}; 
     676        void set_n ( int n0, bool copy=true ) {w.set_size ( n0,copy );samples.set_size ( n0,copy );}; 
    642677        //! Potentially dangerous, use with care. 
    643678        vec& _w()  {return w;}; 
     
    655690        double evallog ( const vec &val ) const {it_error ( "Not implemented" );return 0.0;} 
    656691        vec mean() const { 
    657                 vec pom=zeros ( rv.count() ); 
     692                vec pom=zeros ( dim ); 
    658693                for ( int i=0;i<n;i++ ) {pom+=samples ( i ) *w ( i );} 
    659694                return pom; 
    660695        } 
    661696        vec variance() const { 
    662                 vec pom=zeros ( rv.count() ); 
    663                 for ( int i=0;i<n;i++ ) {pom+=pow(samples ( i ),2) *w ( i );} 
    664                 return pom-pow(mean(),2); 
     697                vec pom=zeros ( dim ); 
     698                for ( int i=0;i<n;i++ ) {pom+=pow ( samples ( i ),2 ) *w ( i );} 
     699                return pom-pow ( mean(),2 ); 
    665700        } 
    666701}; 
     
    668703 
    669704//////////////////////// 
    670  
    671 template<class sq_T> 
    672 enorm<sq_T>::enorm ( const RV &rv ) :eEF ( rv ), mu ( rv.count() ),R ( rv.count() ),dim ( rv.count() ) {}; 
    673705 
    674706template<class sq_T> 
     
    677709        mu = mu0; 
    678710        R = R0; 
     711        dim = mu0.length(); 
    679712}; 
    680713 
     
    692725vec enorm<sq_T>::sample() const { 
    693726        vec x ( dim ); 
    694         #pragma omp critical  
     727#pragma omp critical 
    695728        NorRNG.sample_vector ( dim,x ); 
    696729        vec smp = R.sqrt_mult ( x ); 
     
    708741 
    709742        for ( i=0;i<N;i++ ) { 
    710         #pragma omp critical  
     743#pragma omp critical 
    711744                NorRNG.sample_vector ( dim,x ); 
    712745                pom = R.sqrt_mult ( x ); 
     
    741774 
    742775template<class sq_T> 
    743 mlnorm<sq_T>::mlnorm ( const RV &rv0, const RV &rvc0 ) :mEF ( rv0,rvc0 ),epdf ( rv0 ),A ( rv0.count(),rv0.count() ),_mu ( epdf._mu() ) { 
    744         ep =&epdf; 
    745 } 
    746  
    747 template<class sq_T> 
    748776void mlnorm<sq_T>::set_parameters ( const mat &A0, const vec &mu0, const sq_T &R0 ) { 
    749         epdf.set_parameters ( zeros ( rv.count() ),R0 ); 
     777        it_assert_debug ( A0.rows() ==mu0.length(),"" ); 
     778        it_assert_debug ( A0.rows() ==R0.rows(),"" ); 
     779 
     780        epdf.set_parameters ( zeros ( A0.rows() ),R0 ); 
    750781        A = A0; 
    751782        mu_const = mu0; 
     783        dimc=A0.cols(); 
    752784} 
    753785 
     
    785817template<class sq_T> 
    786818epdf* enorm<sq_T>::marginal ( const RV &rvn ) const { 
     819        it_assert_debug(isnamed(), "rv description is not assigned"); 
    787820        ivec irvn = rvn.dataind ( rv ); 
    788821 
    789         sq_T Rn ( R,irvn ); 
    790         enorm<sq_T>* tmp = new enorm<sq_T> ( rvn ); 
     822        sq_T Rn ( R,irvn ); //select rows and columns of R 
     823         
     824        enorm<sq_T>* tmp = new enorm<sq_T>; 
     825        tmp->set_rv ( rvn ); 
    791826        tmp->set_parameters ( mu ( irvn ), Rn ); 
    792827        return tmp; 
     
    796831mpdf* enorm<sq_T>::condition ( const RV &rvn ) const { 
    797832 
     833        it_assert_debug ( isnamed(),"rvs are not assigned" ); 
     834 
    798835        RV rvc = rv.subt ( rvn ); 
    799         it_assert_debug ( ( rvc.count() +rvn.count() ==rv.count() ),"wrong rvn" ); 
     836        it_assert_debug ( ( rvc._dsize() +rvn._dsize() ==rv._dsize() ),"wrong rvn" ); 
    800837        //Permutation vector of the new R 
    801838        ivec irvn = rvn.dataind ( rv ); 
     
    807844        mat S=Rn.to_mat(); 
    808845        //fixme 
    809         int n=rvn.count()-1; 
     846        int n=rvn._dsize()-1; 
    810847        int end=R.rows()-1; 
    811848        mat S11 = S.get ( 0,n, 0, n ); 
    812         mat S12 = S.get ( 0, n , rvn.count(), end ); 
    813         mat S22 = S.get ( rvn.count(), end, rvn.count(), end ); 
     849        mat S12 = S.get ( 0, n , rvn._dsize(), end ); 
     850        mat S22 = S.get ( rvn._dsize(), end, rvn._dsize(), end ); 
    814851 
    815852        vec mu1 = mu ( irvn ); 
     
    818855        sq_T R_n ( S11 - A *S12.T() ); 
    819856 
    820         mlnorm<sq_T>* tmp=new mlnorm<sq_T> ( rvn,rvc ); 
    821  
     857        mlnorm<sq_T>* tmp=new mlnorm<sq_T> ( ); 
     858        tmp->set_rv(rvn); tmp->set_rvc(rvc); 
    822859        tmp->set_parameters ( A,mu1-A*mu2,R_n ); 
    823860        return tmp; 
  • bdm/stat/libFN.cpp

    r262 r270  
    55using namespace bdm; 
    66 
    7 bilinfn::bilinfn ( const RV &rvx0, const RV &rvu0, const mat &A0, const mat &B0 ) : diffbifn (A0.rows(), rvx0,rvu0 ) 
    8 { 
    9         //check input 
    10         it_assert_debug ( ( A0.cols() ==dimx ) & ( A0.rows() ==B0.rows() ), "linfn:: wrong A" ); 
    11         it_assert_debug ( ( B0.cols() ==dimu ), "linfn:: wrong B" ); 
    12  
    13         // set dimensions 
    14         dimy = A0.rows(); 
    15  
    16         //set internals 
    17         A = A0; 
    18         B = B0; 
    19 }; 
    207 
    218inline vec bilinfn::eval ( const  vec &x0, const vec &u0 ) 
  • bdm/stat/libFN.h

    r262 r270  
    2828                vec eval ( const vec &cond ) {return val;}; 
    2929                //!Default constructor 
    30                 constfn ( const vec &val0 ) :fnc(val0.length()), val ( val0 ) {}; 
     30                constfn ( const vec &val0 ) :fnc(), val ( val0 ) {dimy=val.length();}; 
    3131}; 
    3232 
     
    3838                //! Matrix A 
    3939                mat A; 
    40                 //! Matrix B 
     40                //! vector B 
    4141                vec B; 
    4242        public : 
    43                 vec eval (const vec &cond ) {it_assert_debug ( cond.length() ==rv.count(), "linfn::eval Wrong cond." );return A*cond+B;}; 
     43                vec eval (const vec &cond ) {it_assert_debug ( cond.length() ==A.cols(), "linfn::eval Wrong cond." );return A*cond+B;}; 
    4444 
    4545//              linfn evalsome ( ivec &rvind ); 
    4646                //!default constructor 
    47                 linfn ( const RV &rv0 ) : fnc(rv0.count()), rv ( rv0 ),A ( eye ( rv0.count() ) ),B ( zeros ( rv0.count() ) ) { }; 
     47                linfn ( ) : fnc(), A ( ),B () { }; 
    4848                //! Set values of \c A and \c B 
    49                 void set_parameters ( const mat &A0 , const vec &B0 ) {A=A0; B=B0;}; 
     49                void set_parameters ( const mat &A0 , const vec &B0 ) {A=A0; B=B0; dimy=A.rows();}; 
    5050}; 
    5151 
     
    8686                virtual void dfdu_cond ( const vec &x0, const vec &u0, mat &A, bool full=true ) {}; 
    8787                //!Default constructor (dimy is not set!) 
    88                 diffbifn (int dimy, const RV rvx0, const RV rvu0 ) : fnc(dimy), rvx ( rvx0 ),rvu ( rvu0 ) {dimx=rvx.count();dimu=rvu.count();}; 
     88                diffbifn () : fnc() {}; 
    8989                //! access function 
    9090                int _dimx() const{return dimx;} 
     
    100100                mat B; 
    101101        public : 
     102                //!\name Constructors 
     103                //!@{ 
     104                 
     105                bilinfn () : diffbifn () ,A() ,B()      {}; 
     106                bilinfn (const mat A0, const mat B0) {set_parameters(A0,B0);}; 
     107                //! Alternative constructor 
     108                void set_parameters(const mat A0, const mat B0){ 
     109                        it_assert_debug(A0.rows()==B0.rows(),""); 
     110                        A=A0;B=B0; 
     111                        dimy=A.rows(); 
     112                        dimx=A.cols(); 
     113                        dimu=B.cols(); 
     114                } 
     115                //!@} 
     116                 
     117                //!\name Mathematical operations 
     118                //!@{ 
    102119                vec eval ( const  vec &x0, const vec &u0 ); 
    103  
    104                 //! Default constructor 
    105                 bilinfn ( const RV &rvx0, const RV &rvu0 ) : diffbifn (dimx, rvx0,rvu0 ) ,A ( eye ( dimx ) ),B ( zeros ( dimx,dimu ) )  {}; 
    106                 //! Alternative constructor 
    107                 bilinfn ( const RV &rvx0, const RV &rvu0, const mat &A0, const mat &B0 ); 
    108                 //! 
    109120                void dfdx_cond ( const vec &x0, const vec &u0, mat &F, bool full ) 
    110121                { 
     
    118129                        if ( full ) F=B;        //else : nothing has changed no need to regenerate 
    119130                } 
     131                //!@} 
    120132}; 
    121133 
  • bdm/stat/loggers.cpp

    r262 r270  
    2727        int i,j,k; 
    2828        int nsc=0; 
    29         for ( i=0;i<entries.length();i++ ) {nsc+=entries ( i ).count();} 
     29        for ( i=0;i<entries.length();i++ ) {nsc+=entries ( i )._dsize();} 
    3030        ; //all entries!! 
    3131 
  • bdm/stat/loggers.h

    r263 r270  
    4242                int i; int n =entries.length(); 
    4343                vectors.set_size ( n );  
    44                 for ( i=0;i<n;i++ ) {vectors(i).set_size (maxlen,entries(i).count() );} 
     44                for ( i=0;i<n;i++ ) {vectors(i).set_size (maxlen,entries(i)._dsize() );} 
    4545                ; 
    4646        }