Index: /library/bdm/mex/mex_BM.h
===================================================================
--- /library/bdm/mex/mex_BM.h (revision 943)
+++ /library/bdm/mex/mex_BM.h (revision 944)
@@ -12,6 +12,9 @@
 		} 
 		void validate() {
-			mexCallMATLAB(0, 0, 1, &data,  "validate");
 			mxArray *tmp;
+			mexCallMATLAB(1, &tmp, 1, &data,  "validate");
+			// new object is in tmp
+			data = tmp;
+			
 			mexCallMATLAB(1, &tmp, 1, &data, "dimensions");
 			vec v=mxArray2vec(tmp);
@@ -20,4 +23,22 @@
 			dimy = v(1);
 			dimc = v(2);
+			
+			mexCallMATLAB(1, &tmp, 1, &data, "get_rv");
+			UImxArray rvtmp(tmp);
+			shared_ptr<RV> r = UI::build<RV>(rvtmp);
+			set_rv(*r);
+			
+			mexCallMATLAB(1, &tmp, 1, &data, "get_rvc");
+			UImxArray rvtmpc(tmp);
+			shared_ptr<RV> rc = UI::build<RV>(rvtmpc);
+			rvtmpc.writeFile("tmpc.cfg");
+			rvc=*rc;
+			
+			mexCallMATLAB(1, &tmp, 1, &data, "get_rvy");
+			UImxArray rvtmpy(tmp);
+			rvtmpy.writeFile("tmpy.cfg");
+			shared_ptr<RV> ry = UI::build<RV>(rvtmpy);
+			yrv = *ry;
+			
 		}
 		void bayes(const vec &dt, const vec &cond) {
@@ -31,8 +52,5 @@
 			
 			mexCallMATLAB(1, &tmp, 3, in, "bayes");
-			if (data!=tmp){
-				mxDestroyArray ( data );
-				data = mxDuplicateArray ( tmp );
-			}			//
+			data = tmp;
 		}
 		epdf* predictor(const vec &cond) const {
@@ -51,4 +69,7 @@
 		}
 		const epdf& posterior() const {
+			mxArray *tmp;
+			mexCallMATLAB(1, &tmp, 1,(mxArray **) &data,  "posterior");
+			const_cast<mexEpdf*>(&est)->set_data(tmp);
 			return est;
 		}
Index: /library/bdm/base/bdmbase.h
===================================================================
--- /library/bdm/base/bdmbase.h (revision 943)
+++ /library/bdm/base/bdmbase.h (revision 944)
@@ -1016,15 +1016,14 @@
 The DataSource has three main data interaction structures:
 \li input, \f$ u_t \f$,
-\li output \f$ y_t \f$,
-\li data, \f$ d_t=[y_t,u_t, \ldots ]\f$ a collection of all inputs and outputs and possibly some internal variables too.
-
+\li output \f$ d_t \f$,
+In simulators, d_t may contain "hidden" variables as well.
 */
 
 class DS : public root {
-	//! \var log_level_enums logdt
-	//! TODO DOPLNIT
+	//! \var log_level_enums logdt 
+	//! log all outputs
 
 	//! \var log_level_enums logut 
-	//! TODO DOPLNIT
+	//! log all inputs
 	LOG_LEVEL(DS,logdt,logut);
 
Index: /library/bdm/base/datasources.h
===================================================================
--- /library/bdm/base/datasources.h (revision 924)
+++ /library/bdm/base/datasources.h (revision 944)
@@ -77,9 +77,10 @@
 	/*! Create object from the following structure
 	\code
-	{ class = "MemDS";
-	   Data = (...);            // Data matrix or data vector
+	DS.class = "MemDS";
+	DS.Data = (...);               % Data matrix or data vector
 	   --- optional ---
-	   drv = {class="RV"; ...} // Identification how rows of the matrix Data will be known to others
-	   time = 0;               // Index of the first column to user_info,
+	DS.drv = {class="RV"; ...}     % Identification how rows of the matrix Data will be known to others
+	DS.time = 0;                   % Index of the first column to user_info,
+	DS.log_level = "logdt,logut";  % switches to log (or not log) dt or ut
 	}
 	\endcode
Index: /library/bdm/stat/exp_family.h
===================================================================
--- /library/bdm/stat/exp_family.h (revision 924)
+++ /library/bdm/stat/exp_family.h (revision 944)
@@ -1083,4 +1083,5 @@
 
 UIREGISTER2 ( mgnorm, chmat );
+UIREGISTER2 ( mgnorm, ldmat );
 SHAREDPTR2 ( mgnorm, chmat );
 
Index: /library/bdm/stat/emix.h
===================================================================
--- /library/bdm/stat/emix.h (revision 896)
+++ /library/bdm/stat/emix.h (revision 944)
@@ -337,5 +337,9 @@
 		factors = epdfs0;
 	}
-};
+	void from_setting(const Setting &set){
+		UI::get(factors,set,"pdfs",UI::compulsory);
+	}
+};
+UIREGISTER(eprod);
 
 //! similar to eprod but used only internally -- factors are external pointers
@@ -364,9 +368,4 @@
 	mmix() : Coms ( 0 ) { };
 
-
-
-
-
-	
 	double evallogcond ( const vec &dt, const vec &cond ) {
 		double ll = 0.0;
Index: /library/doc/tutorial/000install.dox
===================================================================
--- /library/doc/tutorial/000install.dox (revision 837)
+++ /library/doc/tutorial/000install.dox (revision 944)
@@ -14,8 +14,16 @@
 Installation:
 \li svn checkout http://mys.utia.cas.cz:1800/svn/mixpp/applications/bdmtoolbox/ into your local directory of your choice (this will be denoted \<toolbox_dir\>)
-\li open matlab and type: \>\> addpath \<toolbox_dir\>/mex; addpath \<toolbox_dir\>/mexw32
-\li the toolbox is ready to be used, test it e.g. by: \>\> cd tutorial/userguide; pdfds_example
+\li or download a prepared zip file from http://staff.utia.cas.cz/smidl/Public/bdmtoolbox_win32.zip and extract it to any directory (will be denoted \<toolbox_dir\>)
+\li open matlab and type: 
+\code 
+>> addpath <toolbox_dir>/mex; 
+>> addpath <toolbox_dir>/mexw32
+>> addpath <toolbox_dir>/mex_classes
+\endcode
+\li the toolbox is ready to be used, test it e.g. by: 
+\code >> cd tutorial/userguide; 
+>> pdfds_example \endcode
 \li if no error is given, the toolbox is installed correctly
-\li proceed to http://mys.utia.cas.cz:1800/trac/bdm/doxygen/pages.html to learn how to use it
+\li proceed to tutorial at http://mys.utia.cas.cz:1800/trac/bdm/doxygen/pages.html to learn how to use it
 
 \section src Source code
Index: /library/doc/tutorial/02userguide_estim.dox
===================================================================
--- /library/doc/tutorial/02userguide_estim.dox (revision 944)
+++ /library/doc/tutorial/02userguide_estim.dox (revision 944)
@@ -0,0 +1,181 @@
+/*!
+\page userguide_estim BDM Use - Estimation and Bayes Rule
+
+Baysian theory is predominantly used in system identification, or estimation problems. 
+This section is concerned with recursive estimation, as implemneted in prepared scenario \c estimator.
+
+The function of the \c estimator is graphically illustrated:
+\dot
+digraph estimation{
+	node [shape=box];
+	{rank="same"; "Data Source"; "Bayesian Model"}
+	"Data Source" -> "Bayesian Model" [label="data"];
+	"Bayesian Model" -> "Result Logger" [label="estimation\n result"];
+	"Data Source" -> "Result Logger" [label="Simulated\n data"];
+}
+\enddot
+
+Here,
+\li Data Source is an object (class DS) providing sequential data, \f$ [d_1, d_2, \ldots d_t] \f$.
+\li Bayesian Model is an object (class BM) performing Bayesian filtering,
+\li Result Logger is an object (class logger) dedicated to storing important data from the experiment.
+
+Since objects  datasource and the logger has already been introduced in section \ref userguide, it remains to introduce 
+object \c Bayesian \c Model (bdm::BM).
+
+\section ug2_theory Bayes rule and estimation
+The object bdm::BM is basic software image of the Bayes rule:
+\f[ f(x_t|d_1\ldots d_t) \propto f(d_t|x_t,d_1\ldots d_{t-1}) f(x_t| d_1\ldots d_{t-1}) \f]
+
+Since this operation can not be defined universally, the object is defined as abstract class with methods for:
+ - <b> Bayes rule </b> as defined above, operation bdm::BM::bayes() which expects to get the current data record \c dt, \f$ d_t \f$
+ - <b> evidence </b> i.e. numerical value of \f$ f(d_t|d_1\ldots d_{t-1})\f$ as a typical side-product, since it is required in denominator of the above formula.
+   For some models, computation of this value may require extra effort, and can be swithed off.
+ - <b> prediction </b> the object has enough information to create the one-step ahead predictor, i.e. \f[ f(d_{t+1}| d_1 \ldots d_{t}), \f] 
+	
+Implementation of these operations is heavily dependent on the specific class of prior pdf, or its approximations. We can identify only a few principal approaches to this problem. For example, analytical estimation which is possible within sufficient the Exponential Family, or estimation when both prior and posterior are approximated by empirical densities. 
+These approaches are first level of descendants of class \c BM, classes bdm::BMEF and bdm::PF, repectively.
+
+\section ug2_arx_basic Estimation of ARX models
+
+Autoregressive models has already been introduced in \ref ug_arx_sim where their simulator has been presented.
+We will use results of simulation of the ARX datasource defined there to provide data for estimation using MemDS.
+
+The following code is from bdmtoolbox/tutorial/userguide/arx_basic_example.m
+\code
+A1.class = 'ARX';
+A1.rv = y;
+A1.rgr = RVtimes([y,y],[-3,-1]) ;
+A1.log_level = 'logbounds,logevidence';
+\endcode 
+This is the minimal configuration of an ARX estimator. 
+
+The first three fileds are self explanatory, they identify which data are predicted (field \c rv) and which are in regressor (field \c rgr).
+The field \c log_level is a string of options passed to the object. In particular, class \c BM understand only options related to storing results:
+ - logbounds - store also lower and upper bounds on estimates (obtained by calling BM::posterior().qbounds()),
+ - logevidence - store also evidence of each step of the Bayes rule.
+These values are stored in given logger (\ref ug_loggers). By default, only mean values of the estimate are stored.
+
+Storing of the evidence is useful, e.g. in model selection task when two models are compared.
+
+The bounds are useful e.g. for visualization of the results. Run of the example should provide result like the following:
+\image latex arx_basic_example.png "Typical run of tutorial/userguide/arx_basic_example.m" width=\linewidth
+
+\section ug2_model_sel Model selection
+
+In Bayesian framework, model selection is done via comparison of evidence (marginal likelihood) of the recorded data. See [some theory].
+
+A trivial exammple how this can be done is presented in file bdmtoolbox/tutorial/userguide/arx_selection_example.m. The code extends the basic A1 object as follows:
+\code
+A2=A1;
+A2.constant = 0;
+
+A3=A2;
+A3.frg = 0.95;
+\endcode
+That is, two other ARX estimators are created, 
+ - A2 which is the same as A1 except it does not model constant term in the linear regression. Note that if the constant was set to zero, then this is the correct model.
+ - A3 which is the same as A2, but assumes time-variant parameters with forgetting factor 0.95.
+ 
+Since all estimator were configured to store values of marginal log-likelihood, we can easily compare them by computint total log-likelihood for each of them and converting them to probabilities. Typically, the results should look like:
+\code
+Model_probabilities =
+
+    0.0002    0.7318    0.2680
+\endcode
+Hence, the true model A2 was correctly identified as the most likely to produce this data. 
+
+For this task, additional technical adjustments were needed:
+\code
+A1.name='A1';
+A2.name='A2';
+A2.rv_param = RV({'a2th', 'r'},[2,1],[0,0]);
+A3.name='A3';
+A3.rv_param = RV({'a3th', 'r'},[2,1],[0,0]);
+\endcode
+First, in order to distinguish the estimators from each other, the estimators were given names. Hence, the results will be logged with prefix given by the name, such as M.A1_evidence.
+
+Second, if the parameters of a ARX model are not specified, they are automatically named \c theta and \c r. However, in this case, \c A1 and \c A2 differ in size, hence their random variables differ and can not use the same name. Therefore, we have explicitly used another names (RVs) of the parameters.
+
+\section ug2_bm_composition Composition of estimators
+
+Similarly to pdfs which could be composed via \c mprod, the Bayesian models can be composed togetrer. However, justification of this step is less clear than in the case of epdfs.
+
+One possible theoretical base of composition is the Marginalized particle filter, which splits the prior and the posterior in two parts:
+\f[ f(x_t|d_1\ldots d_t)=f(x_{1,t}|x_{2,t},d_1\ldots d_t)f(x_{2,t}|d_1\ldots d_t) \f]
+each of these parts is estimated using different approach. The first part is assumed to be analytically tractable, while the second is approximated using empirical approximation.
+
+The whole algorithm runs by parallel evaluation of many \c BMs for estimation of \f$ x_{1,t}\f$, each of them conditioned on value of a sample of \f$ x_{2,t}\f$.
+
+For example, the forgetting factor, \f$ \phi \f$ of an ARX model can be considered to be unknown. Then, the whole parameter space is \f$ [\theta_t, r_t, \phi_t]\f$ decomposed as follows:
+\f[ f(\theta_t, r_t, \phi_t) = f(\theta_t, r_t| \phi_t) f(\phi_t) \f]
+Note that for known trajectory of \f$ \phi_t \f$ the standard ARX estimator can be used if we find a way how to feed the changing \f$ \phi_t \f$ into it.
+This is achieved by a trivial extension using inheritance method bdm::BM::condition().
+
+Extension of standard ARX estimator to conditional estimator is implemented as class bdm::ARXfrg. The only difference from standard ARX is that this object will obtain its forgetting factor externally as a conditioning variable. 
+Informally, the name 'ARXfrg' means: "if anybody calls your condition(0.9), it tells you new value of forgetting factor".
+
+The MPF estimator for this case is specified as follows:
+\code
+%%%%%% ARX estimator conditioned on frg
+
+A1.class = 'ARXfrg';
+A1.rv = y;
+A1.rgr = RVtimes([y,u],[-3,-1]) ; 
+A1.log_level ='logbounds,logevidence';
+A1.frg = 0.9;
+A1.name = 'A1';
+
+%%%%%% Random walk on frg - Dirichlet 
+phi_pdf.class = 'mDirich';         % random walk on coefficient phi
+phi_pdf.rv    = RV('phi',2);       % 2D random walk - frg is the first element
+phi_pdf.k     = 0.01;              % width of the random walk
+phi_pdf.betac = [0.01 0.01];       % stabilizing elememnt of random walk
+
+%%%%%% Particle
+p.class = 'MarginalizedParticle';
+p.parameter_pdf = phi_pdf;         % Random walk is the parameter evolution model
+p.bm    = A1;
+
+% prior on ARX
+%%%%%% Combining estimators in Marginalized particle filter
+E.class = 'PF';
+E.particle = p;                    % ARX is the analytical part
+E.res_threshold = 1.0;             % resampling parameter
+E.n = 100;                         % number of particles
+E.prior.class = 'eDirich';         % prior on non-linear part
+E.prior.beta  = [2 1]; % 
+E.log_level = 'logbounds';
+E.name = 'MPF';
+
+M=estimator(DS,{E});
+
+\endcode
+ 
+Here, the configuration structure \c A1 is a description of an ARX model, as used in previous examples, the only difference is in its name 'ARXfrg'. 
+
+The configuration structure \c phi_pdf defines random walk on the forgetting factor. It was chosen as Dirichlet, hence it will produce 2-dimensional vector of \f$[\phi, 1-\phi]\f$. The class \c ARXfrg was designed to read only the first element of its condition.
+The random walk of type mDirich is:
+\f[ f(\phi_t|\phi_{t-1}) = Di (\phi_{t-1}/k + \beta_c) \f]
+where \f$ k \f$ influences the spread of the walk and \f$ \beta_c \f$ has the role of stabilizing, to avoid traps of corner cases such as [0,1] and [1,0].
+Its influence on the results is quite important.
+
+This example is implemented as bdmtoolbox/tutorial/userguide/frg_example.m
+Its typical run should look like the following:
+\image html frg_example_small.png 
+\image latex frg_example.png "Typical run of tutorial/userguide/frg_example.m" width=\linewidth
+
+Note: error bars in this case are not directly comparable with those of previous examples. The MPF class implements the qbounds function as minimum and maximum of bounds in the condidered set (even if its weight is extreemly small). Hence, the bounds of the MPF are probably larger than it should be. Nevertheless, they provide great help when designing and tuning algorithms.
+
+\section ug_est_ext Matlab extensions of the Bayesian estimators
+
+Similarly to the extension of pdf, the estimators (or filters) can be extended via prepared class \c mexBM in directory bdmtoolbox/mex/mex_classes.
+
+An example of such class is mexLaplaceBM in \<toolbox_dir\>\tutorial\userguide\laplace_example.m
+
+Note that matlab-extended classes of mexEpdf, specifically, mexDirac and mexLaplace are used as outputs of methods posterior and epredictor, respectively.
+
+In order to create a new extension of an estimator, copy file with class mexLaplaceBM.m and redefine the methods therein. If needed create new classes for pdfs by inheriting from mexEpdf, it the same way as in the mexLaplace.m example class.
+
+Foro list of all estimators, see \ref app_base.
+*/
Index: /library/doc/tutorial/005userguide0.dox
===================================================================
--- /library/doc/tutorial/005userguide0.dox (revision 853)
+++ /library/doc/tutorial/005userguide0.dox (revision 944)
@@ -4,19 +4,20 @@
 BDM is a library of basic components for Bayesian decision making, hence its direct use is not possible. In order to use BDM the components must be pulled together in order to achieve desired functionality. We expect two kinds of users:
 
- - <b> Experimentators </b> who run prepared scripts with different parameterizations and analyze their results,
- - <b> Algorithms designers </b> who are able to understand the logic of BDM and extend its functionality to new applications.
+ - <b> Experimenters </b> who run prepared scripts with different parameterizations and analyze their results,
+ - <b> Advanced users</b> who are able to extend functionality by filling prepared Matlab classes, 
+ - <b> Porgrammers </b> who are able to implement algorithms withing C++ backend of BDM.
 
-The primary design aim of BDM was to ease development of complex algorithms, hence the target user is the latter. 
-However, running experiments is the first task to learn for both types of users.
+This tutorial is intended for the first two classes of users. Programmers should read it for introduction and then follow to the Doxygen maunal.
 
+The logic of bdmtoolbox is that the experiment is run in C++ via mex-file. Parameterization of the task is done via Matlab structures. 
+A range of selected "callback" functions to Matlab is available. This range can be extended by a Programmer, please contact authors if available extension point are not satisfactory for you.
 
 \section param Experiment is fully parameterized before execution
 
-Experiments in BDM can be performed using either standalone applications or function bindings in high-level environment. A typical example of the latter being mex file in Matlab environment.
-
-The main logic behind the experiment is that all necessary information about it are gathered in advance in a configuration file (for standalone applications) or in configuration structure (Matlab).
+The main logic behind the experiment is that all necessary information about it are gathered in advance in a configuration structure.
 This approach was designed especially for time consuming  experiments and Monte-Carlo studies for which it suits the most. 
 
-For smaller decision making tasks, interactive use of the experiment can be achieved by showing the full configuration structure (or its selected parts), running the experiment on demand and showing the results.
+For smaller decision making tasks, interactive use of the experiment can be achieved by showing the full configuration structure (or its selected parts), 
+running the experiment on demand and showing the results.
 
 Semi-interactive experiments can be designed by sequential run of different algorithms. This topic will be covered in advanced documentation.
@@ -31,10 +32,14 @@
  - <b>Closed loop</b>: sequantial estimation from previous step is complemneted by adaptive controller (or decision maker) that designs control strategy for the next step.
 
+Mex files for some atomic operations with internal objects are provided for comfortable definition of an experiment and analysis.
+These functions are not efficient for use in repettitive way.
+
 These scenarios may serve as a starting point for advanced users who can design specific algorithms tailored for given application domain.
 
 A tutorial how to run the scenarios are:
 
- - \ref userguide
- - \ref userguide2
+ - \ref userguide_pdf
+ - \ref userguide_sim
+- \ref userguide_estim
 
 */
Index: /library/doc/tutorial/01userguide_sim.dox
===================================================================
--- /library/doc/tutorial/01userguide_sim.dox (revision 944)
+++ /library/doc/tutorial/01userguide_sim.dox (revision 944)
@@ -0,0 +1,231 @@
+/*!
+\page userguide_sim BDM Use - System, Data, Simulation
+
+This section serves as introduction to the scenario of data simulation. Since it is the simpliest of all scenarios defined in \ref userguide0 it also serves as introduction to configuration of an experiment (see \ref ui) and basic decision making objects (bdm::RV and bdm::DS).
+
+All experiments are demonstarted on mex file \c simulator, which is also available as a standalone application.
+
+
+\section ug_sim_config Configuration of an experiment
+
+Configuration file (or config structure) is organized as a tree of information. High levels represent complex structures, leafs of the tree are basic data elements such as strings, numbers or vectors.
+
+Specific treatment was developed for objects. Since BDM is designed as object oriented library, the configuration was designed to honor the rule of inheritance. That is, offspring of a class can be used in place of its predecessor. Hence, objects (instances of classes) are configured by a structure  with compulsory field \c class. This is a string variable corresponding to the name of the class to be used. This information is stored in Matlab structures (or objects, see section on Matlab extensions).
+
+Advacnded users can find more information in (\ref ui).
+
+\subsection ug_first First experiment
+
+The first experiment that can be performed is:
+\code
+DS.class='MemDS';
+DS.Data =[1 2 3 4 5 6];
+\endcode
+which can be found in file bdmtoolbox/tutorials/userguide/memds_example.m.
+
+The code above is the minimum necessary information to run scenario \c simulator in matlab. 
+To actually do so, make sure that matlab paths are correctly set, as described in \ref install.
+
+The expected result for Matlab is:
+\code
+>> M=simulator(DS)
+
+M = 
+
+    ch0: [6x1 double]
+\endcode
+
+All that the simulator did was actually copying \c DS.Data to \c M.ch0. Explanation of the experiment and the logic used there follows.
+
+\section ug_sim Systems and DataSources
+
+In standard system theory, the system is typically illustrated graphically as:
+\dot 
+digraph sys{
+	node [shape=box];
+	{"System"}
+	node [shape=plaintext]
+	{rank="same"; "u"; "System"; "y"}
+	"u" -> "System" -> "y" [nodesep=2];
+}
+\enddot
+Where \c u typically denotes input and \c y denotes output of the system. A causal dependence between input and output is typically presumed.
+
+We are predominantly concerned with discrete-time systems, hence, we will add indices \f$ _t \f$ to both input and output, \f$ u_t \f$ and \f$ y_t \f$. We presume that the causal dependence is \f$ u_t \f$ comes before \f$ y_t \f$.
+
+One of the definition of a system is that system is a "set of variables observed on a part of the world". Under this definition system is understood as generator of data. This definition may be a considered too simplistic, but it serves well as a description of what software object \c DataSource is.
+
+DataSource is an object that is essentially able to:
+ -# return data observed at time \f$ t \f$, 
+ -# perform one a time step.
+ -# describe what these data are, via class RV, introduced in ref \ug_pdf_marg,
+ -# store log of its activity into dedicated logger.
+
+No fruther specification, e.g. if the data are pre-recorded or computed on-the-fly, are given.
+For a list of available DataSources, see ...
+
+
+\section ug_memds DataSource of pre-recorded data -- MemDS
+
+The first experiment run in \ref ug_first was actually an instance of DataSource of pre-recorded data that were stored in memory, i.e. the bdm::MemDS class.
+
+Operation of such object is trivial, the data are stored as a matrix and the general operations defined above are specialized as follows:
+ -# data observed at time \f$ t \f$  are columns of the matrix, getdata() ruturns current column,
+ -# time step itself is performed by increasing the column index,
+ -# each row is named as "ch0","ch1",...
+
+This is the default bahavior. It can be customized using the UI mechanism. Full list of options is:
+\code
+DS.class = 'MemDS';
+DS.Data = (...);            // Data matrix or data vector
+	--- optional ---
+DS.drv = RV({"ch0",...} ); // Identification how rows of the matrix Data will be known to others
+DS.time = 0;               // Index of the first column to user_info,
+\endcode
+The compulsory fields are listed at the beginning; the optional fields are separated by string "--- optional ---".
+
+Fields \c time denotes the first record to start counting from. Field \c drv is a the one that specifies identification of the data elements, (point 3. of the general requirements of a DataSource). 
+
+All optionals fields will be filled by default values, it this case:
+\code
+DS.drv  = RV({'ch0'},1,0);
+DS.time = 0;
+\endcode
+Where the first line specifies a universal identification structure: random variable (bdm::RV).
+
+\section ug_rvs What is RV and how to use it
+
+RV stands for \c random \c variable which is a description of random variable or its realization. However, this object serves as general descriptor of fields in vectors of data. 
+
+It is used for:
+ - desription of RV in pdfs, ways how to define marginalization and conditioning,
+ - connection between source of data and computational objects that use them,
+ - connection <b>time</b>, more exactly time shift from \f$ t \f$, defaults to 0.
+
+\subsection ug_rv_connect Storing results
+
+results of an experiment can be stored in many ways. This functionality was abstracted into a class called logger. Exact form of the stored resuls is chosen by choosing appropriate class.
+For example, \c stdlog writes all output in the console, \c dirfilelog writes all data in the dirfilelog format for high-speed data processing, \c mexlog writes data into matlab structure. 
+The \c mexlog is the default option in bdmtoolbox.
+
+Connection between computational blocks and loggers is controlled by structure called \c log_level which governes the level of details to be logged.
+A standard Data source has two levels, \c logdt and \c logut which means "log all outputs, dt" and "log all inputs, ut".
+Readers familiar with Simulink environment may look at the RV as being unique identifiers of inputs and outputs of simulation blocks. The inputs are connected automatically with the outputs with matching RV. This view is however, very incomplete, RV have more roles than this.
+
+\section ug_pdfds How to create a simulator from pdfs 
+For example, we would like to simulate a random Uniform distributed noise on interval <-1,1>. 
+This is achieved by plugging an object representing uniform pdf into general simulator of independent random samples, pdfDS. Uniform density is implemented as class bdm::euni, which is created from the following structure:
+\code
+U.class='euni';
+U.rv   = RV({'a'});
+U.high = 1.0;
+U.low  = -1.0;
+\endcode
+which encodes information:\f[
+f(a) = \mathcal{U}(-1,1)
+\f]
+  
+The datasource itself, i.e. the instanc of \c EpdfDS can be then configured via:
+\code
+DS.class = 'pdfDS';
+DS.pdf  = U;
+\endcode
+where \c U is the structure defined above.
+
+Contrary to the previous example, we need to tell to algorithm \c simulator how many samples from the data source we need. This is configured by variable \c experiment.ndat. The configuration has to be finalized by:
+\code 
+experiment.ndat = 10;
+M=simulator(DS,experiment);
+\endcode
+
+The result is as expected in field \c M.DS_dt_a the name of which corresponds to results form "datasouce" / "output_dt" / "name given in U.rv".
+
+If the task was only to generate random realizations, this would indeed be a very clumsy way of doing it. However, the power of the proposed approach will be revelead in more demanding examples, one of which follows next.
+
+\section ug_arx_sim Simulating autoregressive model
+
+Consider the following autoregressive model: 
+\f[
+f(y_t|y_{t-3},u_{t-1}) = \mathcal{N}( a y_{t-3} + b u_{t-1}, r)
+\f]
+where \f$ a,b \f$ are known constants, and \f$ r \f$ is known variance.
+
+We need to handle two issues:
+ -# extra unsimulated variable \f$ u \f$,
+ -# time delayes of the values.
+
+The first issue can be handled in two ways. First, \f$ u \f$ can be considered as input and as such it could be externally given to the datasource. This solution is used in scenario \c closedloop.
+However, for the \c simulator scenario we will apply the second option, that is we complement \f$ f(y_{t}|y_{t-3},u_{t-1})\f$ by extra pdf:\f[
+f(u_t) = \mathcal{N}(0, r_u)
+\f]
+where \f$ r_u \f$ is another known constant.
+Thus, the joint density is now:\f[
+f(y_{t},u_{t}|y_{t-3},u_{t-1}) = f(y_{t}|y_{t-3},u_{t-1})f(u_{t})
+\f]
+and we have no need for input since the datasource have all necessary information inside. All that is required is to store them and copy their values to appropriate places.
+
+That is done in automatic way (via bdm::datalink_buffered). The only issue a user may need to take care about is the missing initial conditions for simulation.
+By default these are set to zeros. Using the default values, the full configuration of this system is:
+\code
+y = RV({'y'});
+u = RV({'u'});
+
+fy.class = 'mlnorm\<ldmat\>';
+fy.rv    = y;
+fy.rvc   = RV({'y','u'}, [1 1], [-3, -1]);
+fy.A     = [0.5, -0.9];
+fy.const = 0;
+fy.R     = 0.1;
+
+
+fu.class = 'enorm\<ldmat\>';
+fu.rv    = u;
+fu.mu    = 0;
+fu.R     = 0.2;
+
+DS.class = 'pdfDS';
+DS.pdf.class  = 'mprod';
+DS.pdf.pdfs  = {fy, fu};
+\endcode
+
+Explanation of this example will require few remarks:
+ - class of the \c fy object is 'mlnorm\<ldmat\>' which is Normal pdf with mean value given by linear function, and covariance matrix stored in LD decomposition, see bdm::mlnorm for details.
+ - naming convention 'mlnorm\<ldmat\>' relates to the concept of templates in C++. For those unfamiliar with this concept, it is basicaly a way how to share code for different flavours of the same object. Note that mlnorm exist in three versions: mlnorm\<ldmat\>, mlnorm<chmat>, mlnorm<fsqmat>. Those classes act identically the only difference is that the internal data are stored either in LD decomposition, choleski decomposition or full matrices, respectively. 
+ - the same concept is used for enorm, where enorm<chmat> and enorm<fsqmat> are also possible. In this particular use, these objects are equivalent. In specific situation, e.g. Kalman filter implemented on Choleski decomposition (bdm::KalmanCh), only enorm<chmat> is approprate.
+ - class 'mprod' represents the chain rule of probability, see \ref ug_pdf_cond.
+ 
+The code above can be immediatelly run, usin the same execution sequence of \c estimator as above. 
+
+\subsection ug_ini Initializing simulation
+
+When zeros are not appropriate initial conditions, the correct conditions can be set using additional commands:
+\code
+DS.init_rv = RV({'y','y','y'}, [1,1,1], [-1,-2,-3]);
+DS.init_values = [0.1, 0.2, 0.3];
+\endcode
+
+The values of \c init_values will be copied to places in history identified by corresponding values of \c init_rv.
+Initial data is not checked for completeness, i.e. values of random variables missing from \c init_rv (in this case all occurences of \f$ u \f$) are still initialized to 0.
+
+\section ug_store Storing results of simulation
+
+If the simulated data are to be analyzed off-line it may be advantageous to store them and use later on. 
+This operation is straightforward if the class of logger used in the \c simulator is compatible with some datasource class.
+
+For example, the output of \c MemDS can be stored as an .it file (filename is specified in configuration structure) which can be later read by bdm::ITppFileDS.
+
+In matlab, the output of mexlog is a structure of vectors or matrices. The results can be saved in a matlab file using:
+\code
+Data=[M.y; M.u];
+drv = RVjoin({y,u});
+save pdfds_results Data drv
+\endcode
+Such data can be later provided e.g. by MemDS
+\code
+mxDS.class   = 'MemDS';
+mxDS.Data    = 'Data';
+mxDS.drv     = drv;
+\endcode
+
+For list of all DataSources and loggers, see \ref app_base
+*/
Index: /library/doc/tutorial/007userguide_pdf.dox
===================================================================
--- /library/doc/tutorial/007userguide_pdf.dox (revision 778)
+++ /library/doc/tutorial/007userguide_pdf.dox (revision 944)
@@ -4,7 +4,7 @@
 This section serves as an introduction to basic elements of the BDM: probability density functions, pdfs.
 
-The tutorial is written in for the BDM toolbox, if you are interested in use of C++ classes see class reference pages.
+The tutorial is written for the BDM toolbox, if you are interested in use of C++ classes see class reference pages.
 
-\section ugpdf_create Creation of pdfs
+\section ug_pdf_create Using built-in pdfs
 
 In BDM toolbox, a pdf is specified by matlab structure, e.g.
@@ -16,5 +16,5 @@
 \endcode
 Which encodes information \f$ f(a,b) = \mathcal{N}(mu=[3;2],R=eye(2))\f$.
-\li the keyword "enorm\<ldmat\>" means "Unconditional Normal distribution with covariance matrix in L'DL form", othe rpossibilities are: 
+\li the keyword "enorm\<ldmat\>" means "Unconditional Normal distribution with covariance matrix in L'DL form", other possibilities are: 
 "enorm\<chmat\>" for Choleski decomposition, and "enorm\<fsqmat\>" for full (non-decomposed) matrices.
 \li mu denotes mean value
@@ -58,5 +58,5 @@
 \endcode
 
-\section ugpdf_cond Conditioned densities
+\section ug_pdf_cond Conditioned densities
 Note that the result of conditioning is of type "mlnorm\<ldmat\>" which is a special case of pdf with variables in condition, specifically 
 \f[ f(a|b) = \mathcal{N}(A*b+const, R)\f] 
@@ -75,16 +75,51 @@
 Thus it is differently encoded as:
 \code
-fab.class = 'eprod';
+fab.class = 'eprod';         % result is unconditioned pdf
 fab.pdfs  = {fa_b, fb};
 
-fab_c.class = 'mprod';
+fab_c.class = 'mprod';       % result is conditioned pdf
 fab_c.pdfs  = {fa_b, fb_c};
 \endcode
 
+\section ug_pdf_fnc Pdfs with functional transformation
+
+In more general type of pdfs, variables in condition may be transformed by a function. 
+For example Gaussian density with nonlinear transformation of mean value, \f$ f(x|y) = \mathcal{N}(g(y), R)\f$, is represented by class \c mgnorm
+
+\code
+fx.class  = 'mgnorm<ldmat>';             
+fx.g      = 'mexFunction';              % function is evaluated in matlab
+fx.g.function = 'test_function';         % name of the matlab function to evaluate
+fx.g.dim  = 2;                          % expected dimension of output
+fx.g.dimc = 2;                          % expected dimension of input
+fx.R      = eye(2);                     % variance R
+\endcode
+
+This example is using generic function specified by name of Matlab .m file. 
+Compulsory fields \c g.dim and \c g.dimc are used to check correct dimension of inputs and outputs of the function. 
 
 
+\section ug_pdf_mex Creating user-defined pdfs in Matlab
+
+Definition of new pdf classes in matlab is done by extending (inheriting from) class mexPdf which is defined in file: bdmtoolbox/mex/mex_classes/mexEpdf.m
+
+The file lists all necessary functions that must be filled in order to plug the new class into other bdm algorithms.
+
+Please read Matlab manual for details on its implementation of object oriented programming. 
+
+For easier start, an example class, mexLaplace, is defined in \<toolbox_dir\>/mex/mex_classes/mexLaplace.m 
+
+Using matlab-extended classes is done via a structure with only two required fields:
+\code 
+fL.class = 'mexEpdf';         % declaration of derivative from mexEpdf
+fL.object = mexLaplace;       % any particular instance of mexEpdf
+
+fL.object.mu = 1;             % set values of attributes of the chosen class, in this case mexLaplace
+fL.object.b = 1;              
+\endcode
+
+See example bdmtoolbox/tutorial/userguide/mexpdf_example.m
 
 
-
-
+For list of all available pdf objects, see \ref app_base
 */
Index: /library/doc/tutorial/05append_objects.dox
===================================================================
--- /library/doc/tutorial/05append_objects.dox (revision 944)
+++ /library/doc/tutorial/05append_objects.dox (revision 944)
@@ -0,0 +1,131 @@
+/*!
+\page app_base bdmtoolbox - List of available basic objects
+
+Basic objects of BDM are:
+ - <b>RV</b> decriptor of data vectors and random variables
+ - <b>fnc</b> functions of vector arguments
+ - <b>pdf</b> pdf with non-empty conditioning part
+ - <b>epdf</b> pdf with empty conditioning part
+ - <b>BM</b> Bayesian model - (approximate) calculation of specific type of the Bayes rule, 
+ - <b>DS</b> Data Sources - recursive sources of data
+ - <b>logger</b> object storing results of all experiments
+ 
+ See, \ref userguide_pdf and \ref userguide_sim for their introduction.
+
+
+
+\section app_base_rv Working with RV
+
+In bdmtoolbox, RV is represented by a matlab structure. It is recommended to use the following function to work with it:
+
+ - <b>RV</b>, <b>rva=RV('a',1)</b>, <b>rvab=RV({'b','c'},[1,2])</b> create empty RV, RV named "a" of size 1, and vector of RV "b" and "c" of sizes 1 and 2, respectively.
+ - <b>RVtimes(rva,-1)</b> set time (delay) of rva to -1 from current time.
+ - <b>RVjoin([rva,rvb])</b> joins rva and rvb into a vector
+ 
+\section app_base_fnc Basic functions
+ 
+Predefined functions are:
+ - <b>constfn</b> Class representing function , here rv is empty
+ - <b>linfn</b> Class representing function 
+ - <b>mexFnc</b> Matlab extension of a function, calling predefined matlab functions
+ - <b>grid_fnc</b> Function defined by values on a fixed grid and interpolated inbetween them
+ 
+\section app_base_sq Square root decompositions of symetric matrices
+
+For information purpose, these matrices are used in epdfs:
+ - <b>chmat</b> Symmetric matrix stored in square root decomposition using upper cholesky
+ - <b>fsqmat</b> Fake sqmat. This class maps sqmat operations to operations on full matrix
+ - <b>ldmat</b> Matrix stored in LD form, (commonly known as UD)
+
+\section app_base_epdf Basic epdfs accessible from matlab are:
+ - <b>dirac</b> Dirac delta function distribution
+ - <b>eDirich</b> Dirichlet posterior density
+ - <b>eEF</b> General conjugate exponential family posterior density
+ - <b>eEmp</b> Weighted empirical density
+ - <b>egamma</b> Gamma posterior density
+ - <b>egiw</b> Gauss-inverse-Wishart density stored in LD form
+ - <b>egrid</b> Discrete density defined on a continuous grid
+ - <b>eigamma</b> Inverse-Gamma posterior density
+ - <b>eiWishartCh</b> Inverse Wishart on Choleski decomposition
+ - <b>enorm<ldmat></b> Gaussian density with positive definite (decomposed) covariance matrix
+ - <b>enorm<chmat></b> Gaussian density with positive definite (decomposed) covariance matrix
+ - <b>enorm<fsqmat></b> Gaussian density with positive definite (decomposed) covariance matrix
+ - <b>elognorm</b> LogNormal density
+ - <b>emix</b> Mixture of epdfs
+ - <b>eprod</b> Product of densities, elements may be unconditional, however, the result should be unconditioned pdf.
+ - <b>estudent< ldmat></b> Student-t density
+ - <b>estudent< ldmat></b> Student-t density
+ - <b>estudent< ldmat></b> Student-t density
+ - <b>euni</b> Uniform density on rectangular support
+ - <b>eWishartCh</b> Wishart in choleski decomposition 
+ 
+\section app_base_pdf Basic (conditioned) pdfs accessible from matlab are:
+ - <b>mDirich</b> Dirichlet random walk
+ - <b>mexBM</b> BM with functions implemented in matlab
+ - <b>mexEpdf</b> Epdf with functions implemented in matlab
+ - <b>mgamma</b> Gamma random walk
+ - <b>mgamma_fix</b> Gamma random walk around a fixed point
+ - <b>mgdirac</b> Dirac delta pdf with geenral function of the support point 
+ - <b>mgnorm< ldmat ></b> Gaussian Pdf with general function for mean value
+ - <b>mgnorm< chmat ></b> Gaussian Pdf with general function for mean value
+ - <b>mgnorm< fsqmat ></b> Gaussian Pdf with general function for mean value
+ - <b>mguni</b> Uniform density with geenral function of mean value
+ - <b>migamma</b> Inverse-Gamma random walk
+ - <b>migamma_ref</b> Inverse-Gamma random walk around a fixed point
+ - <b>mlnorm< ldmat></b> Normal distribution with linear function with linear function of mean value;
+ - <b>mlnorm< chmat></b> Normal distribution with linear function with linear function of mean value;
+ - <b>mlnorm< fsqmat></b> Normal distribution with linear function with linear function of mean value;
+ - <b>mlognorm</b> Log-Normal random walk
+ - <b>mlstudent</b> Student distributed linear function with linear function of mean value;
+ - <b>mmix</b> Mixture of pdfs with constant weights, all pdfs are of equal RV and RVC
+ - <b>mprod</b> Chain rule decomposition of epdf
+ - <b>mratio</b> Class representing ratio of two densities which arise e.g. by applying the Bayes rule. 
+ - <b>rwiWishartCh</b> Random Walk on inverse Wishart
+ 
+\section app_base_ds DataSources 
+ - <b>MemDS</b> Memory storage of off-line data column-wise
+ - <b>CsvFileDS</b> CSV file data storage The constructor creates Data matrix from the records in a CSV file fname. The orientation can be of two types: 1. BY_COL which is default - the data are stored in columns; one column per time , one row per data item. 2. BY_ROW if the data are stored the classical CSV style. Then each column stores the values for data item, for ex. , one row for each discrete time instant
+ - <b>EpdfDS</b> Simulate data from a static pdf (epdf)
+ - <b>PdfDS</b> Simulate data from conditional density Still having only one density but allowing conditioning on either input or delayed values
+ 
+ \section app_base_log Loggers - storage of results
+ - <b>mexlog</b> Logger storing results into an mxArray
+ - <b>dirfilelog</b> Logging into dirfile with buffer in memory
+ - <b>stdlog</b> Simple logger used for debugging All data records are written out to std from where they could be send to file
+ - <b>ITppFileDS</b> Read Data Matrix from an IT file
+ 
+\section app_base_merg Mergers
+ - <b>merger_base</b> Base class for general combination of pdfs on discrete support
+ - <b>merger_mix</b> Merger using importance sampling with mixture proposal density
+
+  
+\section app_base_bm Bayesian Models   
+
+Basic filters:
+
+ - <b>ARX</b> Linear Autoregressive model with Gaussian noise
+ - <b>ARXfrg</b> ARX with conditioned on forgetting factor
+ - <b>ARXg</b> ARX with Non-linear transformation + Gaussian noise
+ - <b>EKFCh</b> Extended Kalman Filter in Square root
+ - <b>EKFfull</b> Extended Kalman Filter in full matrices
+ - <b>KalmanCh</b> Kalman filter in square root form
+ - <b>KalmanFull</b> Basic Kalman filter with full matrices
+ - <b>MixEF</b> Estimator of Mixtures of Exponential Family Densities
+ - <b>multiBM</b> Estimator for Multinomial density
+ - <b>MultiModel</b> (Switching) Multiple Models. The model runs several BMs in parallel and evaluates thier weights (fittness)
+ - <b>PF</b> Particle filtering: Wrapper for particles 
+    - <b>BootstrapParticle</b> Class used in PF
+    - <b>MarginalizedParticle</b> Class used in PF
+ 
+\section app_base_ctrl Controllers (and related classes)
+ - <b>LQG</b> Basic class computing LQG control
+ - <b>LQG_ARX</b> Controller using ARX model for estimation and LQG designer for control
+ - <b>StateFromARX</b> conversion function
+ - <b>StateSpace< ldmat></b> Basic elements of linear state-space model
+ - <b>StateSpace< chmat></b> Basic elements of linear state-space model
+
+\section app_base_mpdm Multiple Patricipant Decision Makers
+* <b>ARXAgent</b> ARX agent
+ 
+ 
+*/
Index: /brary/doc/tutorial/01userguide.dox
===================================================================
--- /library/doc/tutorial/01userguide.dox (revision 897)
+++  (revision )
@@ -1,291 +1,0 @@
-/*!
-\page userguide BDM Use - System, Data, Simulation
-
-This section serves as introduction to the scenario of data simulation. Since it is the simpliest of all scenarios defined in \ref userguide0 it also serves as introduction to configuration of an experiment (see \ref ui) and basic decision making objects (bdm::RV and bdm::DS).
-
-All experiments are demonstarted on scenario simulator which can be either standalone application or mex file (simulator.mex**).
-
-
-\section ug_config Configuration of an experiment
-
-Configuration file (or config structure) is organized as a tree of information. High levels represent complex structures, leafs of the tree are basic data elements such as strings, numbers or vectors.
-
-Specific treatment was developed for objects. Since BDM is designed as object oriented library, the configuration was designed to honor the rule of inheritance. That is, offspring of a class can be used in place of its predecessor. Hence, objects (instances of classes) are configured by a structure  with compulsory field \c class. This is a string variable corresponding to the name of the class to be used.
-
-The configuration has two possible options:
- - configuration file using syntax of libconfig (see \ref ui),
- - matlab structure.
-For the purpose of tutorial, we will use the matlab notation. 
-These two options can be mutually converted from one to another using prepared mex files: config2mxstruct.mex and mxstruct2config.mex. Naturally, these scripts require matlab to run. If it is not available, manual conversion is relatively trivial, the major difference is in using different types of brackets (\ref ui)
-
-\subsection ug_first First experiment
-
-The first experiment that can be performed is:
-\code
-DS.class='MemDS';
-DS.Data =[1 2 3 4 5 6];
-\endcode
-which can be found in file bdmtoolbox/tutorials/userguide/memds_example.m.
-
-The code above is the minimum necessary information to run scenario \c simulator in matlab. 
-To actually do so, make sure that matlab can find the simulator.mex file, e.g. by running:
-\code 
->> addpath _path_to_/bmtoolbox/mex/
-\endcode
-
-The expected result for Matlab is:
-\code
->> M=simulator(DS)
-
-M = 
-
-    ch0: [6x1 double]
-\endcode
-
-If you see this result, you have configured BDM correctly and you have sucessfully run you first experiment. In other cases, please check your installation, \ref install. 
-All that the simulator did was actually copying \c DS.Data to \c M.ch0. Explanation of the experiment and the logic used there follows.
-
-\section ug_sim Systems and DataSources
-
-In standard system theory, the system is typically illustrated graphically as:
-\dot 
-digraph sys{
-	node [shape=box];
-	{"System"}
-	node [shape=plaintext]
-	{rank="same"; "u"; "System"; "y"}
-	"u" -> "System" -> "y" [nodesep=2];
-}
-\enddot
-Where \c u typically denotes input and \c y denotes output of the system. A causal dependence between input and output is typically presumed.
-
-We are predominantly concerned with discrete-time systems, hence, we will add indices \f$ _t \f$ to both input and output, \f$ u_t \f$ and \f$ y_t \f$. We presume that the causal dependence is \f$ u_t \f$ comes before \f$ y_t \f$.
-
-One of the definition of a system is that system is a "set of variables observed on a part of the world". Under this definition system is understood as generator of data. This definition may be a considered too simplistic, but it serves well as a description of what software object \c DataSource is.
-
-DataSource is an object that is essentially:
- -# able to return data observed at time \f$ t \f$, (bdm::DS::getdata()),
- -# able to perform one a time step, (bdm::DS::step()).
- -# able to describe what these data are, (bdm::DS::_drv()),
-
-No fruther specification, e.g. if the data are pre-recorded or computed on-the-fly, are given.
-Specific behaviour of various DataSources is implemented as specialization of the root class bdm::DS.
-
-
-\section ug_memds DataSource of pre-recorded data -- MemDS
-
-The first experiment run in \ref ug_first was actually an instance of DataSource of pre-recorded data that were stored in memory, i.e. the bdm::MemDS class.
-
-Operation of such object is trivial, the data are stored as a matrix and the general operations defined above are specialized as follows:
- -# data observed at time \f$ t \f$  are columns of the matrix, getdata() ruturns current column,
- -# time step itself is performed by increasing the column index,
- -# each row is named as "ch0","ch1",...
-
-This is the default bahavior. It can be customized using the UI mechanism.
-When the object of class MemDS is created it calls method  bdm::MemDS::from_setting() and the input structure is parsed for settings. All available settings are documented in the method, see bdm::MemDS::from_setting(). The options are:
-\code
-DS.class = 'MemDS';
-DS.Data = (...);            // Data matrix or data vector
-	--- optional ---
-DS.drv = RV({"ch0",...} ); // Identification how rows of the matrix Data will be known to others
-DS.time = 0;               // Index of the first column to user_info,
-DS.rowid = [1,2,3...];     // ids of rows to be used
-\endcode
-The compulsory fields are listed at the beginning; the optional fields are separated by string "--- optional ---".
-
-Fields \c time and \c rowid are self-explanatory. Field \c drv is a the one that specifies identification of the data elements, (point 3. of the general requirements of a DataSource). 
-
-All optionals fields will be filled by default values, it this case:
-\code
-DS.drv  = RV({'ch0'},1,0);
-DS.time = 0;
-DS.rowid = [1];
-\endcode
-Where the first line specifies a universal identification structure: random variable (bdm::RV).
-
-\section ug_rvs What is RV and how to use it
-
-RV stands for \c random \c variable which is a description of random variable or its realization. This object playes role of identifier of elements of vectors of data (in datasources), expected inputs to functions (in pdfs), or required results (operations conditioning). 
-
-Mathematical interpretation of RV is straightforward. Consider pdf \f$ f(a)\f$, then \f$ a \f$ is the part represented by RV. Explicit naming of random variables may seem unnecessary for many operations with pdf, e.g. for generation of a uniform sample from <0,1> it is not necessary to specify any random variable. For this reason, RV are often optional information to specify. However, the considered scenanrio \c simulator is build in a way that requires RV to be given.
-
-In software, \c RV has three compulsory properties:
- - <b>name</b>, unique identifier, two RV with the same name are considered to be identical
- - <b>size</b>, size of the random variable, if not given it is assumed to be 1,
- - <b>time</b>, more exactly time shift from \f$ t \f$, defaults to 0.
- For example, scalar \f$ x_{t-2} \f$ is encoded as (name='x',sizes=1,time=-2).
- Each RV stores array of these elements, hence RV with:
- \code
- names={'a', 'b'};
- sizes=[ 2 , 3];
- times=[-1, 1];
- \endcode 
- denotes 5-dimensional vector \f$ [a_{t-1}, b_{t+1}] \f$.
- 
-\subsection ug_rv_alg Algebra on RVs
-Algebra on RVs (adding, searching in, subtraction, intersection, etc.) is implemented, see bdm::RV.
-
-For convenience in Matlab, the following operations are defined:
- - RV(names,sizes,times) creates configuration structure for RV,
- - RVjoin(rvs) joins configuration structures for array of RVs rvs=[rv1,rv2,...],
- - RVtimes(rvs,times) assign times to corresponding rvs.
-
-See examples in bdmtoolbox/tutorial/userguide
-
-\subsection ug_rv_connect
-
-The \c simulator scenario connects the DataSource to second basic class of BDM, bdm:logger. The logger is a class that take care of storing results -- in this case, results of simulation.
-The connection between these blocks is done automatically. The logger stores results of simulations under the names specified in drv.  
-Readers familiar with Simulink environment may look at the RV as being unique identifiers of inputs and outputs of simulation blocks. The inputs are connected automatically with the outputs with matching RV. This view is however, very incomplete, RV have more roles than this.
-
-
-\section ug_loggers Loggers for flexible handling of results
-Loggers are universal objects for storing and manipulating the results of an experiment. Similar to DataSource, every logger has to provide basic functionality:
- -# initialize its storage (bdm::logger.init()),
- -# assign a connection point to each interested object (bdm::logger.logadd()),
- -# accept data to be logged to given connection (bdm::logger.logit()),
- -# finalize the storage when experiment is finished.
-
-These abstarct operations can be specialized in many ways. For example, storing all results in memory and writing them to disc when finished (bdm::memlog), storing data in a matlab structure (bdm::mexlog), writing them out in ascii (bdm::stdlog) or more sophisticated buffered output to harddrive (bdm::dirfilelog).
-
-Since all experiments are performed in matlab, the default mexlog class will be used. However, the way how the results are to be stored can be configured using configuration structure filled by fields from \c from_setting of the chosen logger, and passing it as third argument to \c simulator.
-
-\section ug_datasource Class inheritance and DataSources
-
-As mentioned above, the scenario \c simulator is written to accept any datasource (i.e. any offspring of bdm::DS). For full list of offsprings, click see Classes > Class Hierarchy.
-
-At the time of writing this tutorial, available datasources are
-bdm::DS
- - bdm::EpdfDS
- - bdm::MemDS
-   - bdm::FileDS
-     - bdm::CsvFileDS
-     - bdm::ITppFileDS
- - bdm::PdfDS
- - bdm::stateDS
-
-The MemDS has already been introduced in the example in \ref ug_memds.
-However, any of the classes listed above can be used to replace it in the example.
-This will be demonstrated on the \c EpdfDS class.
-
-Brief decription of the class states that EpdfDS "Simulate data from a static pdf (epdf)". The static pdf means unconditional pdf in the sense that the random variable is conditioned by numerical values only. In mathematical notation it could be both \f$ f(a) \f$ and \f$ f(x_t |d_1 \ldots d_t)\f$. The latter case is true only when all \f$ d \f$ denotes observed values.
-
-For example, we wish to simulate realizations of a Uniform pdf on interval <-1,1>. 
-This is achieved by plugging an object representing uniform pdf into general simulator of independent random samples, EpdfDS. Uniform density is implemented as class bdm::euni.
-An instance of \c euni can be again created method \c from_setting, in this case bdm::euni.from_setting(). Using documentation we define it with the following code:
-\code
-U.class='euni';
-U.rv   = RV({'a'});
-U.high = 1.0;
-U.low  = -1.0;
-\endcode
-which encodes information:\f[
-f(a) = \mathcal{U}(-1,1)
-\f]
-  
-The datasource itself, i.e. the instanc of \c EpdfDS can be then configured via:
-\code
-DS.class = 'EpdfDS';
-DS.epdf  = U;
-\endcode
-where \c U is the structure defined above.
-
-Contrary to the previous example, we need to tell to algorithm \c simulator how many samples from the data source we need. This is configured by variable \c experiment.ndat. The configuration has to be finalized by:
-\code 
-experiment.ndat = 10;
-M=simulator(DS,experiment);
-\endcode
-
-The result is as expected in field \c M.a the name of which corresponds to name of \c U.rv .
-
-If the task was only to generate random realizations, this would indeed be a very clumsy way of doing it. However, the power of the proposed approach will be revelead in more demanding examples, one of which follows next.
-
-\section ug_arx_sim Simulating autoregressive model
-
-Consider the following autoregressive model: 
-\f[
-f(y_t|y_{t-3},u_{t-1}) = \mathcal{N}( a y_{t-3} + b u_{t-1}, r)
-\f]
-where \f$ a,b \f$ are known constants, and \f$ r \f$ is known variance.
-
-Direct application of \c EpdfDS is not possible, since the pdf above is conditioned on values of \f$ y_{t-3}\f$ and \f$ u_{t-1}\f$.
-We need to handle two issues:
- -# extra unsimulated variable \f$ u \f$,
- -# time delayes of the values.
-
-The first issue can be handled in two ways. First, \f$ u \f$ can be considered as input and as such it could be externally given to the datasource. This solution is used in scenario \c closedloop.
-However, for the \c simulator scenario we will apply the second option, that is we complement \f$ f(y_{t}|y_{t-3},u_{t-1})\f$ by extra pdf:\f[
-f(u_t) = \mathcal{N}(0, r_u)
-\f]
-where \f$ r_u \f$ is another known constant.
-Thus, the joint density is now:\f[
-f(y_{t},u_{t}|y_{t-3},u_{t-1}) = f(y_{t}|y_{t-3},u_{t-1})f(u_{t})
-\f]
-and we have no need for input since the datasource have all necessary information inside. All that is required is to store them and copy their values to appropriate places.
-
-That is done in automatic way using dedicated class bdm::datalink_buffered. The only issue a user may need to take care about is the missing initial conditions for simulation.
-By default these are set to zeros. Using the default values, the full configuration of this system is:
-\code
-y = RV({'y'});
-u = RV({'u'});
-
-fy.class = 'mlnorm\<ldmat\>';
-fy.rv    = y;
-fy.rvc   = RV({'y','u'}, [1 1], [-3, -1]);
-fy.A     = [0.5, -0.9];
-fy.const = 0;
-fy.R     = 0.1;
-
-
-fu.class = 'enorm\<ldmat\>';
-fu.rv    = u;
-fu.mu    = 0;
-fu.R     = 0.2;
-
-DS.class = 'pdfDS';
-DS.pdf.class  = 'mprod';
-DS.pdf.pdfs  = {fy, fu};
-\endcode
-
-Explanation of this example will require few remarks:
- - class of the \c fy object is 'mlnorm\<ldmat\>' which is Normal pdf with mean value given by linear function, and covariance matrix stored in LD decomposition, see bdm::mlnorm for details.
- - naming convention 'mlnorm\<ldmat\>' relates to the concept of templates in C++. For those unfamiliar with this concept, it is basicaly a way how to share code for different flavours of the same object. Note that mlnorm exist in three versions: mlnorm\<ldmat\>, mlnorm<chmat>, mlnorm<fsqmat>. Those classes act identically the only difference is that the internal data are stored either in LD decomposition, choleski decomposition or full matrices, respectively. 
- - the same concept is used for enorm, where enorm<chmat> and enorm<fsqmat> are also possible. In this particular use, these objects are equivalent. In specific situation, e.g. Kalman filter implemented on Choleski decomposition (bdm::KalmanCh), only enorm<chmat> is approprate.
- - class 'mprod' represents the chain rule of probability. Attribute \c pdfs of its configuration structure is a list of conditional densities. Conditional density \f$ f(a|b)\f$ is represented by class \c pdf and its offsprings. Class \c RV is used to describe both variables before conditioning (field \c rv ) and after conditioning sign (field \c rvc).
- 
- 
-The code above can be immediatelly run, usin the same execution sequence of \c estimator as above. 
-
-\subsection ug_ini Initializing simulation
-
-When zeros are not appropriate initial conditions, the correct conditions can be set using additional commands (see bdm::pdfDS.from_setting() ):
-\code
-DS.init_rv = RV({'y','y','y'}, [1,1,1], [-1,-2,-3]);
-DS.init_values = [0.1, 0.2, 0.3];
-\endcode
-
-The values of \c init_values will be copied to places in history identified by corresponding values of \c init_rv.
-Initial data is not checked for completeness, i.e. values of random variables missing from \c init_rv (in this case all occurences of \f$ u \f$) are still initialized to 0.
-
-
-\section ug_store Storing results of simulation
-
-If the simulated data are to be analyzed off-line it may be advantageous to store them and use later on. 
-This operation is straightforward if the class of logger used in the \c simulator is compatible with some datasource class.
-
-For example, the output of \c MemDS can be stored as an .it file (filename is specified in configuration structure) which can be later read by bdm::ITppFileDS.
-
-In matlab, the output of mexlog is a structure of vectors or matrices. The results can be saved in a matlab file using:
-\code
-Data=[M.y; M.u];
-drv = RVjoin({y,u});
-save pdfds_results Data drv
-\endcode
-Such data can be later provided e.g. by MemDS
-\code
-mxDS.class   = 'MemDS';
-mxDS.Data    = 'Data';
-mxDS.drv     = drv;
-\endcode
-
-*/
Index: /brary/doc/tutorial/02userguide2.dox
===================================================================
--- /library/doc/tutorial/02userguide2.dox (revision 870)
+++  (revision )
@@ -1,170 +1,0 @@
-/*!
-\page userguide2 BDM Use - Estimation and Bayes Rule
-
-Baysian theory is predominantly used in system identification, or estimation problems. 
-This section is concerned with recursive estimation, as implemneted in prepared scenario \c estimator.
-
-The function of the \c estimator is graphically illustrated:
-\dot
-digraph estimation{
-	node [shape=box];
-	{rank="same"; "Data Source"; "Bayesian Model"}
-	"Data Source" -> "Bayesian Model" [label="data"];
-	"Bayesian Model" -> "Result Logger" [label="estimation\n result"];
-	"Data Source" -> "Result Logger" [label="Simulated\n data"];
-}
-\enddot
-
-Here,
-\li Data Source is an object (class DS) providing sequential data, \f$ [d_1, d_2, \ldots d_t] \f$.
-\li Bayesian Model is an object (class BM) performing Bayesian filtering,
-\li Result Logger is an object (class logger) dedicated to storing important data from the experiment.
-
-Since objects  datasource and the logger has already been introduced in section \ref userguide, it remains to introduce 
-object \c Bayesian \c Model (bdm::BM).
-
-\section ug2_theory Bayes rule and estimation
-The object bdm::BM is basic software image of the Bayes rule:
-\f[ f(x_t|d_1\ldots d_t) \propto f(d_t|x_t,d_1\ldots d_{t-1}) f(x_t| d_1\ldots d_{t-1}) \f]
-
-Since this operation can not be defined universally, the object is defined as abstract class with methods for:
- - <b> Bayes rule </b> as defined above, operation bdm::BM::bayes() which expects to get the current data record \c dt, \f$ d_t \f$
- - <b> log-likelihood </b> i.e. numerical value of \f$ f(d_t|d_1\ldots d_{t-1})\f$ as a typical side-product, since it is required in denominator of the above formula.
-   For some models, computation of this value may require extra effort, hence it computation can be suppressed by setting BM::set_evalll(false).
- - <b> prediction </b> the object has enough information to create the one-step ahead predictor, i.e. \f[ f(d_{t+1}| d_1 \ldots d_{t}), \f] 
- 	this object can be either created bdm::BM::predictor(), sometimes it is enought only a few values of prediction hence construction of the full predictor would be too expensive operation. For this situation were designed cheaper operations bdm::BM::logpred() or bdm::BM::epredictor().
-These are only basic operations, see full documentation for full range of defined operations.
-	
-These operation are abstract, i.e. not implemented for the general class. 
-Implementation of these operations is heavily dependent on the specific class of prior pdf, or its approximations. We can identify only a few principal approaches to this problem. For example, analytical estimation which is possible within sufficient the Exponential Family, or estimation when both prior and posterior are approximated by empirical densities. 
-These approaches are first level of descendants of class \c BM, classes bdm::BMEF and bdm::PF, repectively.
-
-Variants of these approaches are implemented as descendats of these level-two classes. This way, each estimation method (represented a class) is fitted in its place in the tree of approximations. This is useful even from software point of view, since related approximations have common methods and data fields.
-
-\section ug2_arx_basic Estimation of ARX models
-
-Autoregressive models has already been introduced in \ref ug_arx_sim where their simulator has been presented.
-We will use results of simulation of the ARX datasource defined there to provide data for estimation using MemDS.
-
-The following code is from bdmtoolbox/tutorial/userguide/arx_basic_example.m
-\code
-A1.class = 'ARX';
-A1.rv = y;
-A1.rgr = RVtimes([y,y],[-3,-1]) ;
-A1.log_level = 'logbounds,logevidence';
-\endcode 
-This is the minimal configuration of an ARX estimator. Optional elements of bdm::ARX::from_setting() were set using their default values:
-
-The first three fileds are self explanatory, they identify which data are predicted (field \c rv) and which are in regressor (field \c rgr).
-The field \c log_level is a string of options passed to the object. In particular, class \c BM understand only options related to storing results:
- - logbounds - store also lower and upper bounds on estimates (obtained by calling BM::posterior().qbounds()),
- - logevidence - store also loglikelihood of each step of the Bayes rule.
-These values are stored in given logger (\ref ug_loggers). By default, only mean values of the estimate are stored.
-
-Storing of the log-likelihood is useful, e.g. in model selection task when two models are compared.
-
-The bounds are useful e.g. for visualization of the results. Run of the example should provide result like the following:
-\image html arx_basic_example_small.png 
-\image latex arx_basic_example.png "Typical run of tutorial/userguide/arx_basic_example.m" width=\linewidth
-
-\section ug2_model_sel Model selection
-
-In Bayesian framework, model selection is done via comparison of marginal likelihood of the recorded data. See [some theory].
-
-A trivial exammple how this can be done is presented in file bdmtoolbox/tutorial/userguide/arx_selection_example.m. The code extends the basic A1 object as follows:
-\code
-A2=A1;
-A2.constant = 0;
-
-A3=A2;
-A3.frg = 0.95;
-\endcode
-That is, two other ARX estimators are created, 
- - A2 which is the same as A1 except it does not model constant term in the linear regression. Note that if the constant was set to zero, then this is the correct model.
- - A3 which is the same as A2, but assumes time-variant parameters with forgetting factor 0.95.
- 
-Since all estimator were configured to store values of marginal log-likelihood, we can easily compare them by computint total log-likelihood for each of them and converting them to probabilities. Typically, the results should look like:
-\code
-Model_probabilities =
-
-    0.0002    0.7318    0.2680
-\endcode
-Hence, the true model A2 was correctly identified as the most likely to produce this data. 
-
-For this task, additional technical adjustments were needed:
-\code
-A1.name='A1';
-A2.name='A2';
-A2.rv_param = RV({'a2th', 'r'},[2,1],[0,0]);
-A3.name='A3';
-A3.rv_param = RV({'a3th', 'r'},[2,1],[0,0]);
-\endcode
-First, in order to distinguish the estimators from each other, the estimators were given names. Hence, the results will be logged with prefix given by the name, such as M.A1ll for field \c ll.
-
-Second, if the parameters of a ARX model are not specified, they are automatically named \c theta and \c r. However, in this case, \c A1 and \c A2 differ in size, hence their random variables differ and can not use the same name. Therefore, we have explicitly used another names (RVs) of the parameters.
-
-\section ug2_bm_composition Composition of estimators
-
-Similarly to pdfs which could be composed via \c mprod, the Bayesian models can be composed. However, justification of this step is less clear than in the case of epdfs.
-
-One possible theoretical base of composition is the Marginalized particle filter, which splits the prior and the posterior in two parts:
-\f[ f(x_t|d_1\ldots d_t)=f(x_{1,t}|x_{2,t},d_1\ldots d_t)f(x_{2,t}|d_1\ldots d_t) \f]
-each of these parts is estimated using different approach. The first part is assumed to be analytically tractable, while the second is approximated using empirical approximation.
-
-The whole algorithm runs by parallel evaluation of many \c BMs for estimation of \f$ x_{1,t}\f$, each of them conditioned on value of a sample of \f$ x_{2,t}\f$.
-
-For example, the forgetting factor, \f$ \phi \f$ of an ARX model can be considered to be unknown. Then, the whole parameter space is \f$ [\theta_t, r_t, \phi_t]\f$ decomposed as follows:
-\f[ f(\theta_t, r_t, \phi_t) = f(\theta_t, r_t| \phi_t) f(\phi_t) \f]
-Note that for known trajectory of \f$ \phi_t \f$ the standard ARX estimator can be used if we find a way how to feed the changing \f$ \phi_t \f$ into it.
-This is achieved by a trivial extension using inheritance method bdm::BM::condition().
-
-Extension of standard ARX estimator to conditional estimator is implemented as class bdm::ARXfrg. The only difference from standard ARX is that this object will change its forgetting factor via method ARXfrg::condition(). Existence of this function is assumed by the MPF estimator.
-Informally, the name 'ARXfrg' means: "if anybody calls your condition(0.9), it tells you new value of forgetting factor".
-
-The MPF estimator is implemented by class bdm::MPF. In the toolbox, it can be constructed as follows:
-\code
-%%%%%% ARX estimator conditioned on frg
-
-A1.class = 'ARXfrg';
-A1.rv = y;
-A1.rgr = RVtimes([y,u],[-3,-1]) ; 
-A1.log_level ='logbounds,logevidence';
-A1.frg = 0.9;
-A1.name = 'A1';
-
-%%%%%% Random walk on frg - Dirichlet 
-phi_pdf.class = 'mDirich';         % random walk on coefficient phi
-phi_pdf.rv    = RV('phi',2);       % 2D random walk - frg is the first element
-phi_pdf.k     = 0.01;              % width of the random walk
-phi_pdf.betac = [0.01 0.01];       % stabilizing elememnt of random walk
-
-%%%%%% Combining estimators in Marginalized particle filter
-E.class = 'MPF';
-E.BM = A1;                         % ARX is the analytical part
-E.parameter_pdf = phi_pdf;         % Random walk is the parameter evolution model
-E.n = 20;                          % number of particles
-E.prior.class = 'eDirich';         % prior on non-linear part
-E.prior.beta  = [1 1]; % 
-E.log_level ='logbounds,logevidence';
-E.name = 'MPF';
-
-M=estimator(DS,{E});
-
-\endcode
- 
-Here, the configuration structure \c A1 is a description of an ARX model, as used in previous examples, the only difference is in its name 'ARXfrg'. 
-
-The configuration structure \c phi_pdf defines random walk on the forgetting factor. It was chosen as Dirichlet, hence it will produce 2-dimensional vector of \f$[\phi, 1-\phi]\f$. The class \c ARXfrg was designed to read only the first element of its condition.
-The random walk of type mDirich is:
-\f[ f(\phi_t|\phi_{t-1}) = Di (\phi_{t-1}/k + \beta_c) \f]
-where \f$ k \f$ influences the spread of the walk and \f$ \beta_c \f$ has the role of stabilizing, to avoid traps of corner cases such as [0,1] and [1,0].
-Its influence on the results is quite important.
-
-This example is implemented as bdmtoolbox/tutorial/userguide/frg_example.m
-Its typical run should look like the following:
-\image html frg_example_small.png 
-\image latex frg_example.png "Typical run of tutorial/userguide/frg_example.m" width=\linewidth
-
-Note: error bars in this case are not directly comparable with those of previous examples. The MPF class implements the qbounds function as minimum and maximum of bounds in the condidered set (even if its weight is extreemly small). Hence, the bounds of the MPF are probably larger than it should be. Nevertheless, they provide great help when designing and tuning algorithms.
-
-*/
Index: /applications/bdmtoolbox/tutorial/userguide/test_function.m
===================================================================
--- /applications/bdmtoolbox/tutorial/userguide/test_function.m (revision 944)
+++ /applications/bdmtoolbox/tutorial/userguide/test_function.m (revision 944)
@@ -0,0 +1,2 @@
+function out = test_fuction(in)
+out = [sin(in(1)+in(2)); in(2) - in(1)*in(2)];
Index: /applications/bdmtoolbox/tutorial/userguide/pdfds2_example.m
===================================================================
--- /applications/bdmtoolbox/tutorial/userguide/pdfds2_example.m (revision 944)
+++ /applications/bdmtoolbox/tutorial/userguide/pdfds2_example.m (revision 944)
@@ -0,0 +1,27 @@
+clear all
+% name random variables
+x = RV({'x'},2);
+
+
+fx.class  = 'mgnorm<ldmat>';             
+fx.rv     = x;             
+fx.rvc    = RVtimes(x,-1);             
+fx.g.class= 'mexFnc';                   % function is evaluated in matlab
+fx.g.function = 'test_function';        % name of the matlab function to evaluate
+fx.g.dim  = 2;                          % expected dimension of output
+fx.g.dimc = 2;                          % expected dimension of input
+fx.R      = eye(2);                     % variance R
+
+
+% create DS
+DS.class = 'PdfDS';
+DS.pdf = fx;
+DS.init_rv = RVtimes([x], [-1]);
+DS.init_values = [0.1, 0.2];
+
+experiment.ndat=100;
+
+%M=estimator(DS,{},experiment);
+M=estimator(DS,{},experiment);
+
+%%% store results
Index: /applications/bdmtoolbox/tutorial/userguide/pdfds_example.m
===================================================================
--- /applications/bdmtoolbox/tutorial/userguide/pdfds_example.m (revision 940)
+++ /applications/bdmtoolbox/tutorial/userguide/pdfds_example.m (revision 944)
@@ -1,27 +1,23 @@
 clear all
 % name random variables
-y = RV({'y'},1);
-u = RV({'u'},1);
+x = RV({'x'},2);
 
-% create f(y_t| y_{t-3}, u_{t-1})
-fy.class = 'mlnorm<ldmat>';
-fy.rv    = y;
-fy.rvc   = RVtimes([y,u], [-3, -1]);
-fy.A     = [0.5, -0.9];
-fy.const = 0;
-fy.R     = 1e-2;
 
-% create f(u_t| )
-fu.class = 'enorm<ldmat>';
-fu.rv    = u;
-fu.mu    = 0;
-fu.R     = 1e-1;
+fx.class  = 'mgnorm<ldmat>';             
+fx.rv     = x;             
+fx.rvc    = RVtimes(x,-1);             
+fx.g      = 'mexFunction';              % function is evaluated in matlab
+fx.g.function = 'test_function';         % name of the matlab function to evaluate
+fx.g.dim  = 2;                          % expected dimension of output
+fx.g.dimc = 2;                          % expected dimension of input
+fx.R      = eye(2);                     % variance R
+
 
 % create DS
 DS.class = 'PdfDS';
 DS.pdf.class  = 'mprod';
-DS.pdf.pdfs  = {fy, fu};
-DS.init_rv = RVtimes([y,y,y], [-1,-2,-3]);
-DS.init_values = [0.1, 0.2, 0.3];
+DS.pdf.pdfs  = {fx, fu};
+DS.init_rv = RVtimes([x], [-1]);
+DS.init_values = [0.1, 0.2];
 
 experiment.ndat=100;
Index: /applications/bdmtoolbox/tutorial/userguide/laplace_example.m
===================================================================
--- /applications/bdmtoolbox/tutorial/userguide/laplace_example.m (revision 944)
+++ /applications/bdmtoolbox/tutorial/userguide/laplace_example.m (revision 944)
@@ -0,0 +1,21 @@
+% load data created by the MpdfDS_example
+clear all
+load pdfds_results
+
+DS.class   = 'MemDS';
+DS.Data    = Data;
+DS.drv     = drv;
+
+%%%%%% Laplace estimator
+
+L.class = 'mexBM';
+L.object = mexLaplaceBM;
+L.object.rvy = y;
+L.object = validate(L.object);
+L.log_level = 'logmean';
+
+M=estimator(DS,{L});
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% plot results
+plot(M.L_mean)
Index: /applications/bdmtoolbox/mex/RV.m
===================================================================
--- /applications/bdmtoolbox/mex/RV.m (revision 937)
+++ /applications/bdmtoolbox/mex/RV.m (revision 944)
@@ -3,5 +3,5 @@
 
 if nargin<1
-    names='';
+    names={};
 end
 r.class='RV';
Index: /applications/bdmtoolbox/mex/estimator.cpp
===================================================================
--- /applications/bdmtoolbox/mex/estimator.cpp (revision 863)
+++ /applications/bdmtoolbox/mex/estimator.cpp (revision 944)
@@ -89,15 +89,5 @@
 		if ( n_input>3 ) {
 			Cfg.addGroup ( input[3],"logger" );
-		}/*else{
-		// define logger as mexlog
-		Setting &S=Cfg.getRoot();
-		S.add("logger",Setting::TypeGroup);
-		S["logger"].add("class",Setting::TypeString);
-		S["logger"]["class"]="mexlog";
-		S["logger"].add("maxlen",Setting::TypeInt);
-		int maxlen;
-		S["experiment"].lookupValue("ndat",maxlen);
-		S["logger"]["maxlen"]=maxlen;
-	}*/
+		}
 	} catch ( SettingException e ) {
 		it_error ( "error: "+string ( e.getPath() ) );
Index: /applications/bdmtoolbox/mex/mex_classes/mexBM.m
===================================================================
--- /applications/bdmtoolbox/mex/mex_classes/mexBM.m (revision 943)
+++ /applications/bdmtoolbox/mex/mex_classes/mexBM.m (revision 944)
@@ -1,12 +1,19 @@
 classdef mexBM
     properties
-      % from wikipedia
-      rv
-      rvc
-      rvy
+        % description of internal variables
+        rv=RV
+        rvc=RV
+        rvy=RV
+        % log of evidence (marginal likelihood) potentially computed by the
+        % bayes rule for one step
+        log_evidence
+        % posterior density - offspring of mexEpdf!
+        apost_pdf
+        %
     end
+
     methods
-        function validate(p)
-		    % checks if all paramateres match
+        function p=validate(p)
+            % checks if all paramateres match
         end
         function dims=dimensions(p)
@@ -21,4 +28,21 @@
             % return posterior density
         end
+
+        %%%%%%%% default functions %%%%%%%%%%%%%%
+        function r = get_rv(obj)
+            r=obj.rv;
+        end
+        function r = get_rvc(obj)
+            r=obj.rvc;
+        end
+        function r = get_rvy(obj)
+            r=obj.rvy;
+        end
+        function ev = logevidence(obj)
+            ev = obj.log_evidence;
+        end
+        function post=posterior(obj);
+            post = obj.apost_pdf;
+        end
     end
 end
Index: /applications/bdmtoolbox/mex/mex_classes/mexEpdf.m
===================================================================
--- /applications/bdmtoolbox/mex/mex_classes/mexEpdf.m (revision 943)
+++ /applications/bdmtoolbox/mex/mex_classes/mexEpdf.m (revision 944)
@@ -20,5 +20,5 @@
         end
         
-        %%% default function %%%
+        %%% default functions -- no need to redefine %%%
         
         function l=evallog_nn(p,x)
Index: /applications/bdmtoolbox/mex/mex_classes/mexLaplaceBM.m
===================================================================
--- /applications/bdmtoolbox/mex/mex_classes/mexLaplaceBM.m (revision 944)
+++ /applications/bdmtoolbox/mex/mex_classes/mexLaplaceBM.m (revision 944)
@@ -0,0 +1,42 @@
+classdef mexLaplaceBM < mexBM
+    % Approximate Bayesian estimator of parameters of Laplace distributed observation.
+    % Maximum likelihood approximation of the Bayes rule is used, posterior is in the form of dirac.
+    properties
+        max_window_length = 10;   % max window length
+        data_window =[];          % estimate of mu is median of observations
+    end
+    methods
+        function obj=validate(obj)
+            % prepare all internal objects for use
+            obj.apost_pdf = mexDirac;
+            obj.apost_pdf.point = [0;0];
+            obj.log_evidence = 0; % evidence is not computed!
+            disp('val');
+        end
+
+        function dims=dimensions(obj)
+            %please fill
+            %dims = [size_of_posterior size_of_data size_of_condition]
+            dims = [2,1,0] % we have: [2d parameters, 1d observations, 0d condition]
+        end
+        function obj=bayes(obj,dt,cond)
+            if size(obj.data_window,2)>=obj.max_window_length
+                obj.data_window = [dt obj.data_window(1:end-1)];
+            else
+                obj.data_window = [dt obj.data_window];
+            end
+            % transform old estimate into new estimate
+            m_hat = mean(obj.data_window);
+            b_hat = sum(abs(obj.data_window-m_hat))/ size(obj.data_window,2);
+            obj.apost_pdf.point = [m_hat; b_hat];
+        end
+        function p=epredictor(obj,cond)
+            % return predictive density (max likelihood)
+            p = mexLaplace;
+            p.mu = obj.apost_pdf.point(1);
+            p.b  = obj.apost_pdf.point(2);
+            p=p.validate;
+        end
+    end
+
+end
Index: /applications/bdmtoolbox/mex/mex_classes/mexLaplace.m
===================================================================
--- /applications/bdmtoolbox/mex/mex_classes/mexLaplace.m (revision 937)
+++ /applications/bdmtoolbox/mex/mex_classes/mexLaplace.m (revision 944)
@@ -6,25 +6,25 @@
     end
     methods
-        function m=mean(p)
-            m = p.mu;
+        function m=mean(obj)
+            m = obj.mu;
         end
-        function validate(p)
-            if size(p.mu)<1 & (size(p.b)<1)
+        function obj=validate(obj)
+            if length(obj.mu)~=length(obj.b)
                 error('incompatible mu and b');
             end
         end
-        function dim=dimension(p)
-            dim = size(p.mu,1);
+        function dim=dimension(obj)
+            dim = size(obj.mu,1);
         end
-        function v=variance(p)
-            v=2*p.b^2;
+        function v=variance(obj)
+            v=2*obj.b^2;
         end
-        function l=evallog(p,x)
-            l=-log(2*p.b)-abs(x-p.mu)/p.b;
+        function l=evallog(obj,x)
+            l=-log(2*obj.b)-abs(x-obj.mu)/obj.b;
         end
-        function s=sample(p);
+        function s=sample(obj)
             v=-log(rand);%sample_exponential(0,1);
             z = randn;
-            s = p.mu+p.b*sqrt(2*v)*z;
+            s = obj.mu+obj.b*sqrt(2*v)*z;
         end
     end
Index: /applications/bdmtoolbox/mex/mex_classes/mexDirac.m
===================================================================
--- /applications/bdmtoolbox/mex/mex_classes/mexDirac.m (revision 944)
+++ /applications/bdmtoolbox/mex/mex_classes/mexDirac.m (revision 944)
@@ -0,0 +1,37 @@
+classdef mexDirac < mexEpdf
+    % Dirac delta probability distribution
+    properties
+        point % point of the support
+    end
+    methods
+        function m=mean(obj)
+            m = obj.point;
+        end
+        function obj=validate(obj)
+            % point should be a column
+            if (size(obj.point,2)>1)
+                if (size(obj.point,1)==1) % it is row
+                    obj.point = obj.point';
+                end
+            else
+                error('Point in mexDirac is not a vector');
+            end
+        end
+        function dim=dimension(obj)
+            dim = size(obj.point,1);
+        end
+        function v=variance(obj)
+            v=zeros(size(obj.point));
+        end
+        function l=evallog(obj,x)
+            if obj.point==x
+                l = inf;
+            else
+                l=0;
+            end
+        end
+        function s=sample(obj);
+            s = obj.point;
+        end
+    end
+end
Index: /applications/bdmtoolbox/mex/class_defaults.cpp
===================================================================
--- /applications/bdmtoolbox/mex/class_defaults.cpp (revision 797)
+++ /applications/bdmtoolbox/mex/class_defaults.cpp (revision 944)
@@ -17,4 +17,5 @@
 #include <mex/mex_parser.h>
 #include <mex/mex_function.h>
+#include <mex/mex_BM.h>
 
 void mexFunction ( int n_output, mxArray *output[], int n_input, const mxArray *input[] ) {
@@ -25,5 +26,5 @@
 		                                "output:\n"
 		                                "  the same structure filled with the defaults.\n\n"
-		                                "This operation is usefull for obtaining info about a class construction" );
+		                                "This operation is usefull for obtaining info about class defaults, or success of passing info to it" );
 
 	RV::clear_all();
Index: /plications/bdmtoolbox/mex/mexBM.cpp
===================================================================
--- /applications/bdmtoolbox/mex/mexBM.cpp (revision 925)
+++  (revision )
@@ -1,105 +1,0 @@
-#include <itpp/itmex.h>
-#include <estim/arx.h>
-#include "config2mxstruct.h"
-
-using namespace bdm;
-
-class mexEpdf: public epdf{
-	protected:
-		mxArray *data;
-	public:
-		mexEpdf() {};
-		void from_setting(const Setting &S)  {
-			data = S["object"];
-		} 
-		void validate() {
-			mexCallMATLAB(1, &data, 0, 0, ("validate").c_str());
-			dim = mexCallMATLAB(1, &data, 0, 0, ("dimension").c_str());
-		}
-		vec mean() const {
-			mxArray *tmp;
-			mexCallMATLAB(1, &tmp, 1, (mxArray **) &data, "mean".c_str());
-			return mxArray2vec(tmp);
-		}
-		
-};
-UIREGISTER(mexEpdf);
-
-class mexBM: public BM{
-	protected :
-		string name;
-		mexEpdf est;
-		mxArray *data;
-	public:
-		mexBM() {}
-
-		mxArray *get_data() {
-			//mexCallMATLAB(0, NULL, 1, &data, "dump");
-			return mxDuplicateArray(data);
-		}
-
-		void from_setting(const Setting &S)  {
-			name = (const char *) S["name"];
-			UImxConfig conf(S);
-			data = mxDuplicateArray(conf.mxconfig);
-			//string fname = name+"_new";
-			//mexCallMATLAB(1, &data, 0, 0, (name+"_new").c_str());
-			//the following works as long as the posterior is the
-			//only member object there could be a structure of 
-			//member objects in the setting and a for cycle over
-			//all of them right here in the code
-			Setting &posterior = S["posterior"]; 
-			est.from_setting(posterior);
-		}
-		void bayes(const vec &dt)  {
-		//void bayes()  {
-			mxArray *tmp, *old;
-			mxArray *in[2];
-			in[0] = data;
-			in[1] = mxCreateDoubleMatrix(dt.size(), 1, mxREAL);
-			vec2mxArray(dt, in[1]);
-			mexCallMATLAB(1, &tmp, 2, in, (name+"_bayes").c_str());
-			old = data;
-			data = mxDuplicateArray(tmp);
-			if (old) mxDestroyArray(old);
-			if (tmp) mxDestroyArray(tmp);
-			//mexCallMATLAB(0, NULL, 1, &data, "dump");
-		} 
-		//! return correctly typed posterior (covariant return)
-		const mexEpdf& posterior() const  {
-			return est;
-		} //tohle by melo zustat!!
-		const mexEpdf* _e() const  {
-			return &est;
-		} //tohle by melo zustat!!
-};
-UIREGISTER(mexBM);
-
-void mexFunction(int n_output, mxArray *output[], int n_input, const mxArray *input[])
-{
-    // Check the number of inputs and output arguments
-	if(n_input!=1) mexErrMsgTxt("Wrong number of input variables - expected parameter 'filename'!");
-
- 	// ------------------ Start of routine ---------------------------
-
-	//mexBM mB(mxArray2string(input[0])); // naplni
-	//mB.bayes(vec_1(1.3));
-	string filename = mxArray2string(input[0]);
-	Config config;
-	config.readFile(filename.c_str());
-	mexBM mb;
-	Setting &root = config.getRoot();
-	mb.from_setting(root);
-	vec dt = "18.0";
-	mb.bayes(dt);
-	if(n_output>0) output[0] = mb.get_data();
-	
-
-	// ------------------ End of routine -----------------------------
-
-    // Create output vectors
-	//output[0] = mxCreateDoubleMatrix(1,1, mxREAL);
-
-    // Convert the IT++ format to Matlab format for output
-	//vec2mxArray(mB.posterior().mean(), output[0]);
-}
