root/library/bdm/base/bdmbase.cpp @ 953

Revision 953, 14.7 kB (checked in by smidl, 14 years ago)

RV are now through UI::get

  • Property svn:eol-style set to native
Line 
1
2#include "bdmbase.h"
3
4//! Space of basic BDM structures
5namespace bdm {
6
7const int RV::BUFFER_STEP = 1;
8
9Array<string> RV::NAMES ( RV::BUFFER_STEP );
10
11ivec RV::SIZES ( RV::BUFFER_STEP );
12
13RV::str2int_map RV::MAP;
14
15void RV::clear_all() {
16        MAP.clear();
17        SIZES.clear();
18        NAMES = Array<string> ( BUFFER_STEP );
19}
20
21string RV::show_all() {
22        ostringstream os;
23        for ( str2int_map::const_iterator iter = MAP.begin(); iter != MAP.end(); iter++ ) {
24                os << "key: " << iter->first << " val: " << iter->second << endl;
25        }
26        return os.str();
27};
28
29int RV::assign_id( const string &name, int size ) {
30        //Refer
31        int id;
32        str2int_map::const_iterator iter = MAP.find ( name );
33        if ( iter == MAP.end() || name.length() == 0 ) { //add new RV
34                id = MAP.size() + 1;
35                //debug
36                /*              {
37                                        cout << endl;
38                                        str2int_map::const_iterator iter = MAP.begin();
39                                        for(str2int_map::const_iterator iter=MAP.begin(); iter!=MAP.end(); iter++){
40                                                cout << "key: " << iter->first << " val: " << iter->second <<endl;
41                                        }
42                                }*/
43
44                MAP.insert ( make_pair ( name, id ) ); //add new rv
45                if ( id >= NAMES.length() ) {
46                        NAMES.set_length ( id + BUFFER_STEP, true );
47                        SIZES.set_length ( id + BUFFER_STEP, true );
48                }
49                NAMES ( id ) = name;
50                SIZES ( id ) = size;
51                bdm_assert ( size > 0, "RV " + name + " does not exists. Default size (-1) can not be assigned " );
52        } else {
53                id = iter->second;
54                if ( size > 0 && name.length() > 0 ) {
55                        bdm_assert ( SIZES ( id ) == size, "RV " + name + " of size " + num2str ( SIZES ( id ) ) + " exists, requested size " + num2str ( size ) + "can not be assigned" );
56                }
57        }
58        return id;
59};
60
61int RV::countsize() const {
62        int tmp = 0;
63        for ( int i = 0; i < len; i++ ) {
64                tmp += SIZES ( ids ( i ) );
65        }
66        return tmp;
67}
68
69ivec RV::cumsizes() const {
70        ivec szs ( len );
71        int tmp = 0;
72        for ( int i = 0; i < len; i++ ) {
73                tmp += SIZES ( ids ( i ) );
74                szs ( i ) = tmp;
75        }
76        return szs;
77}
78
79void RV::init ( const Array<std::string> &in_names, const ivec &in_sizes, const ivec &in_times ) {
80        len = in_names.length();
81        bdm_assert ( in_names.length() == in_times.length(), "check \"times\" " );
82        bdm_assert ( in_names.length() == in_sizes.length(), "check \"sizes\" " );
83
84        times.set_length ( len );
85        ids.set_length ( len );
86        int id;
87        for ( int i = 0; i < len; i++ ) {
88                id = assign_id ( in_names ( i ), in_sizes ( i ) );
89                ids ( i ) = id;
90        }
91        times = in_times;
92        dsize = countsize();
93}
94
95RV::RV ( string name, int sz, int tm ) {
96        Array<string> A ( 1 );
97        A ( 0 ) = name;
98        init ( A, vec_1 ( sz ), vec_1 ( tm ) );
99}
100
101RV::RV ( int sz, int tm ) {
102        Array<string> A ( 1 );
103        A ( 0 ) = "";
104        init ( A, vec_1 ( sz ), vec_1 ( tm ) );
105}
106
107bool RV::add ( const RV &rv2 ) {
108        if ( rv2.len > 0 ) { //rv2 is nonempty
109                ivec ind = rv2.findself ( *this ); //should be -1 all the time
110                ivec index = itpp::find ( ind == -1 );
111
112                if ( index.length() < rv2.len ) { //conflict
113                        ids = concat ( ids, rv2.ids ( index ) );
114                        times = concat ( times, rv2.times ( index ) );
115                } else {
116                        ids = concat ( ids, rv2.ids );
117                        times = concat ( times, rv2.times );
118                }
119                len = ids.length();
120                dsize = countsize();
121                return ( index.length() == rv2.len ); //conflict or not
122        } else { //rv2 is empty
123                return true; // no conflict
124        }
125};
126
127RV RV::subselect ( const ivec &ind ) const {
128        RV ret;
129        ret.ids = ids ( ind );
130        ret.times = times ( ind );
131        ret.len = ind.length();
132        ret.dsize = ret.countsize();
133        return ret;
134}
135
136RV RV::operator() ( int di1, int di2 ) const {
137        ivec sz = cumsizes();
138        int i1 = 0;
139        while ( sz ( i1 ) < di1 ) i1++;
140        int i2 = i1;
141        while ( sz ( i2 ) < di2 ) i2++;
142        return subselect ( linspace ( i1, i2 ) );
143}
144
145void RV::t_plus ( int delta ) {
146        times += delta;
147}
148
149bool RV::equal ( const RV &rv2 ) const {
150        return ( ids == rv2.ids ) && ( times == rv2.times );
151}
152
153shared_ptr<pdf> epdf::condition ( const RV &rv ) const NOT_IMPLEMENTED( shared_ptr<pdf>() );
154
155
156shared_ptr<epdf> epdf::marginal ( const RV &rv ) const NOT_IMPLEMENTED( shared_ptr<epdf>() );
157
158mat epdf::sample_mat ( int N ) const {
159        mat X = zeros ( dim, N );
160        for ( int i = 0; i < N; i++ ) X.set_col ( i, this->sample() );
161        return X;
162}
163
164vec epdf::evallog_mat ( const mat &Val ) const {
165        vec x ( Val.cols() );
166        for ( int i = 0; i < Val.cols(); i++ ) {
167                x ( i ) = evallog ( Val.get_col ( i ) );
168        }
169
170        return x;
171}
172
173vec epdf::evallog_mat ( const Array<vec> &Avec ) const {
174        vec x ( Avec.size() );
175        for ( int i = 0; i < Avec.size(); i++ ) {
176                x ( i ) = evallog ( Avec ( i ) );
177        }
178
179        return x;
180}
181
182mat pdf::samplecond_mat ( const vec &cond, int N ) {
183        mat M ( dimension(), N );
184        for ( int i = 0; i < N; i++ ) {
185                M.set_col ( i, samplecond ( cond ) );
186        }
187
188        return M;
189}
190
191void pdf::from_setting ( const Setting &set ) {
192        root::from_setting( set );
193        UI::get(rv, set, "rv", UI::optional );
194        UI::get(rvc, set, "rvc", UI::optional );
195}
196
197void pdf::to_setting ( Setting &set ) const {   
198        root::to_setting( set );
199        UI::save( &rv, set, "rv" );
200        UI::save( &rvc, set, "rvc" );
201}
202
203void datalink::set_connection ( const RV &rv, const RV &rv_up ) {
204        downsize = rv._dsize();
205        upsize = rv_up._dsize();
206        v2v_up = rv.dataind ( rv_up );
207        bdm_assert_debug ( v2v_up.length() == downsize, string("rv (" + rv.to_string() + ") is not fully in rv_up(" + rv_up.to_string()) );
208}
209
210void datalink::set_connection ( int ds, int us, const ivec &upind ) {
211        downsize = ds;
212        upsize = us;
213        v2v_up = upind;
214        bdm_assert_debug ( v2v_up.length() == downsize, "rv is not fully in rv_up" );
215}
216
217void datalink_part::set_connection ( const RV &rv, const RV &rv_up ) {
218        rv.dataind ( rv_up, v2v_down, v2v_up );
219        downsize = v2v_down.length();
220        upsize = v2v_up.length();
221}
222
223void datalink_m2e::set_connection ( const RV &rv, const RV &rvc, const RV &rv_up ) {
224        datalink::set_connection ( rv, rv_up );
225        condsize = rvc._dsize();
226        //establish v2c connection
227        rvc.dataind ( rv_up, v2c_lo, v2c_up );
228}
229
230vec datalink_m2e::get_cond ( const vec &val_up ) {
231        vec tmp ( condsize );
232        set_subvector ( tmp, v2c_lo, val_up ( v2c_up ) );
233        return tmp;
234}
235
236void datalink_m2e::pushup_cond ( vec &val_up, const vec &val, const vec &cond ) {
237        bdm_assert_debug ( downsize == val.length(), "Wrong val" );
238        bdm_assert_debug ( upsize == val_up.length(), "Wrong val_up" );
239        set_subvector ( val_up, v2v_up, val );
240        set_subvector ( val_up, v2c_up, cond );
241}
242
243std::ostream &operator<< ( std::ostream &os, const RV &rv ) {
244        int id;
245        for ( int i = 0; i < rv.len ; i++ ) {
246                id = rv.ids ( i );
247                os << id << "(" << RV::SIZES ( id ) << ")" <<  // id(size)=
248                "=" << RV::NAMES ( id )  << "_{"  << rv.times ( i ) << "}; "; //name_{time}
249        }
250        return os;
251}
252
253RV RV::expand_delayes() const {
254        RV rvt = this->remove_time(); //rv at t=0
255        RV tmp = rvt;
256        int td = mint();
257        for ( int i = -1; i >= td; i-- ) {
258                rvt.t_plus ( -1 );
259                tmp.add ( rvt ); //shift u1
260        }
261        return tmp;
262}
263
264str RV::tostr() const {
265        ivec idlist ( dsize );
266        ivec tmlist ( dsize );
267        int i;
268        int pos = 0;
269        for ( i = 0; i < len; i++ ) {
270                idlist.set_subvector ( pos, pos + size ( i ) - 1, ids ( i ) );
271                tmlist.set_subvector ( pos, pos + size ( i ) - 1, times ( i ) );
272                pos += size ( i );
273        }
274        return str ( idlist, tmlist );
275}
276
277ivec RV::dataind ( const RV &rv2 ) const {
278        ivec res ( 0 );
279        if ( rv2._dsize() > 0 ) {
280                str str2 = rv2.tostr();
281                ivec part;
282                int i;
283                for ( i = 0; i < len; i++ ) {
284                        part = itpp::find ( ( str2.ids == ids ( i ) ) & ( str2.times == times ( i ) ) );
285                        res = concat ( res, part );
286                }
287        }
288
289        //bdm_assert_debug ( res.length() == dsize, "this rv is not fully present in crv!" );
290        return res;
291
292}
293
294void RV::dataind ( const RV &rv2, ivec &selfi, ivec &rv2i ) const {
295        //clean results
296        selfi.set_size ( 0 );
297        rv2i.set_size ( 0 );
298
299        // just in case any rv is empty
300        if ( ( len == 0 ) || ( rv2.length() == 0 ) ) {
301                return;
302        }
303
304        //find comon rv
305        ivec cids = itpp::find ( this->findself ( rv2 ) >= 0 );
306
307        // index of
308        if ( cids.length() > 0 ) {
309                str str1 = tostr();
310                str str2 = rv2.tostr();
311
312                ivec part1;
313                ivec part2;
314                int i, j;
315                // find common rv in strs
316                for ( j = 0; j < cids.length(); j++ ) {
317                        i = cids ( j );
318                        part1 = itpp::find ( ( str1.ids == ids ( i ) ) & ( str1.times == times ( i ) ) );
319                        part2 = itpp::find ( ( str2.ids == ids ( i ) ) & ( str2.times == times ( i ) ) );
320                        selfi = concat ( selfi, part1 );
321                        rv2i = concat ( rv2i, part2 );
322                }
323        }
324        bdm_assert_debug ( selfi.length() == rv2i.length(), "this should not happen!" );
325}
326
327RV RV::subt ( const RV &rv2 ) const {
328        ivec res = this->findself ( rv2 ); // nonzeros
329        ivec valid;
330        if ( dsize > 0 ) {
331                valid = itpp::find ( res == -1 );    //-1 => value not found => it remains
332        }
333        return ( *this ) ( valid ); //keep those that were not found in rv2
334}
335
336std::string RV::scalarname ( int scalat ) const {
337        bdm_assert ( scalat < dsize, "Wrong input index" );
338        int id = 0;
339        int scalid = 0;
340        while ( scalid + SIZES ( ids ( id ) ) <= scalat )  {
341                scalid += SIZES ( ids ( id ) );
342                id++;
343        };
344        //now id is the id of variable of interest
345        if ( size ( id ) == 1 )
346                return  NAMES ( ids ( id ) );
347        else
348                return  NAMES ( ids ( id ) ) + "_" + num2str ( scalat - scalid );
349
350}
351
352ivec RV::findself ( const RV &rv2 ) const {
353        int i, j;
354        ivec tmp = -ones_i ( len );
355        for ( i = 0; i < len; i++ ) {
356                for ( j = 0; j < rv2.length(); j++ ) {
357                        if ( ( ids ( i ) == rv2.ids ( j ) ) & ( times ( i ) == rv2.times ( j ) ) ) {
358                                tmp ( i ) = j;
359                                break;
360                        }
361                }
362        }
363        return tmp;
364}
365
366ivec RV::findself_ids ( const RV &rv2 ) const {
367        int i, j;
368        ivec tmp = -ones_i ( len );
369        for ( i = 0; i < len; i++ ) {
370                for ( j = 0; j < rv2.length(); j++ ) {
371                        if ( ( ids ( i ) == rv2.ids ( j ) ) ) {
372                                tmp ( i ) = j;
373                                break;
374                        }
375                }
376        }
377        return tmp;
378}
379
380void RV::from_setting ( const Setting &set ) {
381        Array<string> A;
382        UI::get ( A, set, "names" );
383
384        ivec szs;
385        if ( !UI::get ( szs, set, "sizes" ) )
386                szs = ones_i ( A.length() );
387
388        ivec tms;
389        if ( !UI::get ( tms, set, "times" ) )
390                tms = zeros_i ( A.length() );
391
392        init ( A, szs, tms );
393}
394
395void RV::to_setting ( Setting &set ) const {
396        Array<string> names ( len );
397        ivec sizes ( len );
398        for ( int i = 0; i < len; i++ ) {
399                names ( i ) = name ( i );
400                sizes ( i ) = size ( i );
401        }
402        UI::save ( names, set, "names" );
403        UI::save ( sizes, set, "sizes" );
404        UI::save ( times, set, "times" );
405}
406
407RV concat ( const RV &rv1, const RV &rv2 ) {
408        RV pom = rv1;
409        pom.add ( rv2 );
410        return pom;
411}
412
413RV get_composite_rv ( const Array<shared_ptr<pdf> > &pdfs,
414                      bool checkoverlap ) {
415        RV rv; //empty rv
416        bool rvaddok;
417        for ( int i = 0; i < pdfs.length(); i++ ) {
418                bdm_assert( pdfs(i)->isnamed(), "Can not extract RV from pdf no. " + num2str(i));
419                rvaddok = rv.add ( pdfs ( i )->_rv() ); //add rv to common rvs.
420                // If rvaddok==false, pdfs overlap => assert error.
421                bdm_assert_debug ( rvaddok || !checkoverlap, "mprod::mprod() input pdfs overlap in rv!" );
422        }
423
424        return rv;
425}
426
427void epdf::log_register ( logger &L, const string &prefix ) {
428        root::log_register ( L, prefix );
429
430        RV r;
431        if ( isnamed() ) {
432                r = _rv();
433        } else {
434                r = RV (  dimension() );
435        };
436
437        // log only
438
439        if ( log_level[logmean] )
440                L.add_vector ( log_level, logmean, r, prefix );                 
441        if ( log_level[loglbound] )
442                L.add_vector ( log_level, loglbound, r, prefix );
443        if ( log_level[logubound] )
444                L.add_vector ( log_level, logubound, r, prefix );
445}
446
447void epdf::log_write() const {
448        if ( log_level[logmean] ) {
449                log_level.store( logmean, mean() );
450        }
451        if ( log_level[loglbound] || log_level[logubound] ) {
452                vec lb;
453                vec ub;
454                qbounds ( lb, ub );
455                if (log_level[loglbound])
456                        log_level.store( loglbound, lb );
457                if (log_level[logubound])
458                        log_level.store( logubound, ub );
459        }
460}
461
462
463
464void datalink_buffered::set_connection ( const RV &rv, const RV &rv_up ) {
465        // create link between up and down
466        datalink_part::set_connection ( rv, rv_up); // only non-delayed version
467
468        RV needed_from_hist = rv.subt(rv_up); //rv_up already copied by v2v
469       
470        // we can store only what we get in rv_up - everything else is removed
471        ivec valid_ids = needed_from_hist.findself_ids ( rv_up ); // return on which position the required id is in rv_up
472        RV rv_hist = needed_from_hist.subselect ( find ( valid_ids >= 0 ) ); // select only rvs that are in rv_up, ie ind>0
473        RV rv_hist0 = rv_hist.remove_time(); // these RVs will form history at time =0
474        // now we need to know what is needed from Up
475        rv_hist = rv_hist.expand_delayes(); // full regressor - including time 0
476        Hrv = rv_hist.subt ( rv_hist0 );   // remove time 0
477        history = zeros ( Hrv._dsize() );
478
479        // decide if we need to copy val to history
480        if ( Hrv._dsize() > 0 ) {
481                v2h_up = rv_hist0.dataind ( rv_up ); // indices of elements of rv_up to be copied
482        } // else v2h_up is empty
483
484        Hrv.dataind ( rv, h2v_hist, h2v_down );
485
486        downsize = v2v_down.length() + h2v_down.length();
487        upsize = v2v_up.length();
488}
489
490void datalink_buffered::set_history ( const RV& rv1, const vec &hist0 ) {
491        bdm_assert ( rv1._dsize() == hist0.length(), "hist is not compatible with given rv1" );
492        ivec ind_H;
493        ivec ind_h0;
494        Hrv.dataind ( rv1, ind_H, ind_h0 ); // find indices of rv in
495        set_subvector ( history, ind_H, hist0 ( ind_h0 ) ); // copy given hist to appropriate places
496}
497
498void DS::log_register ( logger &L,  const string &prefix ) {
499        bdm_assert ( dtsize == Drv._dsize(), "invalid DS: dtsize (" + num2str ( dtsize ) + ") different from Drv " + num2str ( Drv._dsize() ) );
500        //bdm_assert ( utsize == Urv._dsize(), "invalid DS: utsize (" + num2str ( utsize ) + ") different from Urv " + num2str ( Urv._dsize() ) );
501
502        root::log_register ( L, prefix );
503
504
505        if ( log_level[logdt] )
506                L.add_vector ( log_level, logdt, Drv, prefix ); 
507        if ( log_level[logut] )
508                L.add_vector ( log_level, logut, Urv, prefix );
509}
510
511void DS::log_write ( ) const {
512        if( log_level[logdt] ) {
513                vec tmp ( Drv._dsize());
514                getdata ( tmp );
515                // d is first in getdata
516                log_level.store( logdt, tmp );
517        }
518        if( log_level[logut] ) { 
519                // NOT_IMPLEMENTED
520        }
521}
522
523
524void DS::from_setting ( const Setting &set ) {
525        RV rv;
526        if( UI::get( rv, set, "drv", UI::optional ) )
527                set_drv ( rv, RV() );
528}
529
530void DS::validate() {
531        if( !Drv._dsize() && dtsize > 0 )
532        {
533                RV *r = new RV();
534                for ( int i = 0; i < dtsize; i++ ) {
535                        r->add ( RV ( "ch" + num2str ( i ), 1, 0 ) );
536                }
537                set_drv ( *r, RV() );
538                delete r;
539        }
540}
541
542void BM::log_register ( logger &L, const string &prefix ) {
543        root::log_register ( L, prefix );
544
545        if ( log_level[logfull] ) {
546                // log full data
547                L.add_setting ( log_level, logfull, prefix + L.separator + "posterior" );
548        } 
549               
550        if ( log_level[logevidence] )
551                L.add_vector ( log_level, logevidence, RV ( 1 ), prefix );     
552
553        if (log_level[logbounds]){
554                prior().log_level[epdf::loglbound]=true;
555                prior().log_level[epdf::logubound]=true;
556        }
557        const_cast<epdf&> ( posterior() ).log_register ( L, prefix + L.separator + "apost" );
558}
559
560void BM::log_write ( ) const {
561        posterior().log_write();
562        if ( log_level[logfull] ) {
563                log_level.store( logfull, &posterior() );
564        } 
565               
566        if( log_level[logevidence] ) 
567                log_level.store( logevidence, ll );
568}
569
570void BM::bayes_batch ( const mat &Data, const vec &cond ) {
571        for ( int t = 0; t < Data.cols(); t++ ) {
572                bayes ( Data.get_col ( t ), cond );
573        }
574}
575
576void BM::bayes_batch ( const mat &Data, const mat &Cond ) {
577        for ( int t = 0; t < Data.cols(); t++ ) {
578                bayes ( Data.get_col ( t ), Cond.get_col ( t ) );
579        }
580}
581
582}
Note: See TracBrowser for help on using the browser.