root/library/doc/tutorial/040devguide_matlab.dox @ 983

Revision 983, 7.9 kB (checked in by smidl, 14 years ago)

doc - extensions

Line 
1/*!
2\page devguide_mat  BDM Development - your first bdm class in Matlab
3
4bdmtoolbox provides a prodefined points of extensions in directory applications/bdmtoolbox/mex/mex_classes.
5
6The easiest way to extend bdmtoolbox is to use clasess starting with "mex". The simplies class of this type is mexFnc, which just contains name of an arbitrary matlab function to call.
7See \ref ug_pdf_fnc example.
8
9This tutorial assumes you are familiar with basic classes of BDM: random variables \ref userguide_pdf and estimators \ref userguide_estim.
10
11If no premade class is suitable for your mneeds, you can create your own class in Matlab via predefined interfaces to class epdf (mexEpdf) and BM (mexBM).
12These classes are treated as regular C++ classes in prepared mex files. Creation of a new estimator (offspring of mexBM) can be achieved by inheriting from class mexBM.
13
14In practice this means creation of a new file, e.g. my_bm.m, with header:
15\code
16class my_bm < mexBM
17\endcode
18This file must be located in directories known to matlab (must be in its path). This can be any directory if you use addpath command.
19See relevant documentation in Matlab.
20
21\section dev_mat_pdf Creating your own probability density
22
23Creation of your own density is achieved by inheriting from mexEpdf:
24\code
25class my_pdf < mexEpdf
26\endcode
27in a file called my_pdf.m.
28
29Calling methods from mexEpdf will result in an error that tells you which functionality is missing.
30It is necessary to give them a meaning.
31
32Epdf is a class representing probability density function of a multivariate (vector) variable.
33
34The easiest example of a density is dirac Delta function:
35\code
36classdef mexDirac < mexEpdf
37    % Dirac delta probability distribution
38    properties                                                 % DATA structures
39        point                                                  % point of the support
40    end
41    methods
42        function m=mean(obj)                                   % compute mean values of the density
43            m = obj.point;
44        end
45        function obj=validate(obj)                             % check if data structures are consistent
46            % point should be a column
47            if (size(obj.point,2)>1)
48                if (size(obj.point,1)==1) % it is row
49                    obj.point = obj.point';
50                end
51            else
52                error('Point in mexDirac is not a vector');
53            end
54        end
55        function dim=dimension(obj)                            % inform others about your dimensions
56            dim = size(obj.point,1);
57        end
58        function v=variance(obj)                               % compute variance
59            v=zeros(size(obj.point));
60        end
61        function l=evallog(obj,x)                              % return logarithm of your density at point x
62            if obj.point==x
63                l = inf;
64            else
65                l=0;
66            end
67        end
68        function s=sample(obj);                                % return random sample from your density
69            s = obj.point;
70        end
71    end
72end
73\endcode
74
75Once you define these functions, this object can be plugged into (almost) an arbitrary algoritm, such as simulator, etc.
76
77For seamless use with other objects, you nedd to define its random variables - via attribute rv, \ref ug_pdf_create.
78
79For inspiration see example class mexLaplace.m and its use in simulation in tutorial/userguide/epdfds_example.m
80
81\section dev_mat_bm Creating your own Bayesian Model (BM)
82
83If you look into the mexBM.m file you see the basic attributes and default functions. mexBM as such will not work as a valid estimator.
84In order to make it work, you need to re-define at least functions <b>dimensions</b> and <b>bayes</b>, and attribute <b>apost_pdf</b>:
85  \code
86  function dims=dimensions(p)
87      %please fill
88      %dims = [size_of_posterior size_of_data size_of_condition]
89      dims = [0,0,0] %
90  end
91  \endcode
92This function announces sizes of random variables to other objects.
93
94These sizes can be fixed for a specific problem, or derived from size of internal objects. E.g. for a Kalman filter, the function would be:
95\code
96function dims=dimensions(p)
97   %please fill
98   %dims = [size_of_posterior size_of_data size_of_condition]
99   dims = [size(A,1), size(C,1), size(B,2)] %
100end
101\endcode
102Which indicates that dimension of \f$x_t\f$ is the rows of matrix A, size of \f$y_t\f$ is the rows of matrix C and the size of \f$u_t\f$ is given by columns of matrix B.
103 
104The argument apost_pdf should be a valid object of class mexEpdf, see previous section how to achieve it.
105
106The second function to extend is
107\code
108function obj=bayes(obj,dt,cond)
109   % transform old estimate into new estimate
110end
111\endcode
112
113Here, you need to define an update (both time- and data-update) of your Bayesian filter.
114
115Note, that statistics of the posterior are stored in attribute apost_pdf. So, the task of this function is to update fileds in apost_pdf.
116
117Any additional sttributes needed for this task shoul be added to properties of the object.
118
119An example calss of BM for Laplace pdf is implemented in class mexLaplaceBM.m. This class represents maximum likelihood estimator of two parameters of the density.
120One parameter is a median of data on a sliding window. 
121This can be interpreted as a coarse approximation of Bayesian filtering with posterior reduced to Dirac delta.
122
123Hence, we need:
124 - apost_pdf to be of type mexDirac,
125 - store information about window length in the properties
126 - store the windown of data in properties
127 - the method bayes adds new data to the window and copies median of the window to the point in apost_pdf.
128 
129This is implemented as follows:
130\code
131classdef mexLaplaceBM < mexBM
132    % Approximate Bayesian estimator of parameters of Laplace distributed observation.
133    % Maximum likelihood approximation of the Bayes rule is used, posterior is in the form of dirac.
134    properties
135        max_window_length = 10;                               % max window length (default = 10)
136        data_window =[];                                      % sliding window of data
137    end
138    methods
139        function obj=validate(obj)                            % prepare all internal objects for use
140            obj.apost_pdf = mexDirac;
141            obj.apost_pdf.point = [0;0];
142            obj.log_evidence = 0;                             % evidence is not computed!
143            disp('val');
144        end
145
146        function dims=dimensions(obj)
147            %please fill: dims = [size_of_posterior size_of_data size_of_condition]
148            dims = [2,1,0]                                    % we have: [2d parameters, 1d observations, 0d condition]
149        end
150        function obj=bayes(obj,dt,cond)                       % approximate bayes rule
151            if size(obj.data_window,2)>=obj.max_window_length
152                obj.data_window = [dt obj.data_window(1:end-1)];
153            else
154                obj.data_window = [dt obj.data_window];
155            end
156            % transform old estimate into new estimate
157            m_hat = mean(obj.data_window);
158            b_hat = sum(abs(obj.data_window-m_hat))/ size(obj.data_window,2);
159            obj.apost_pdf.point = [m_hat; b_hat];             % store result in psoterior pdf
160        end
161        function p=epredictor(obj,cond)                       % when predictive density is needed approximate it by Laplace with point estimates
162            % return predictive density (max likelihood)
163            p = mexLaplace;
164            p.mu = obj.apost_pdf.point(1);
165            p.b  = obj.apost_pdf.point(2);
166            p=p.validate;
167        end
168    end
169
170end
171\endcode
172 
173Similar extensions to mexEpdf and mexBM can be made to other classes. See library/mex/mex_Epdf.h and library/mex/mex_BM.h how it is done.
174As always, feel free to contact the maintainer for help.
175*/
Note: See TracBrowser for help on using the browser.