annotate toolboxes/FullBNT-1.0.7/bnt/general/sample_dbn.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
rev   line source
wolffd@0 1 function seq = sample_dbn(bnet, varargin)
wolffd@0 2 % SAMPLE_DBN Generate a random sequence from a DBN.
wolffd@0 3 % seq = sample_dbn(bnet, ...)
wolffd@0 4 %
wolffd@0 5 % seq{i,t} contains the values of the i'th node in the t'th slice.
wolffd@0 6 %
wolffd@0 7 % Optional arguments:
wolffd@0 8 %
wolffd@0 9 % length - length of sequence to be generated (can also just use sample_dbn(bnet,T))
wolffd@0 10 % stop_test - name of a function which is used to decide when to stop;
wolffd@0 11 % This will be called as feval(stop_test, seq(:,t))
wolffd@0 12 % i.e., stop_test is passed a cell array containing all the nodes in the current slice.
wolffd@0 13 % evidence - initial evidence; if evidence{i,t} is non-empty, this node won't be sampled.
wolffd@0 14
wolffd@0 15 args = varargin;
wolffd@0 16 nargs = length(args);
wolffd@0 17
wolffd@0 18 if (nargs == 1) & ~isstr(args{1})
wolffd@0 19 % Old syntax: sample_dbn(bnet, T)
wolffd@0 20 T = args{1};
wolffd@0 21 else
wolffd@0 22 % get length
wolffd@0 23 T = 1;
wolffd@0 24 for i=1:2:nargs
wolffd@0 25 switch args{i},
wolffd@0 26 case 'length', T = args{i+1};
wolffd@0 27 case 'evidence', T = size(args{i+1}, 2);
wolffd@0 28 end
wolffd@0 29 end
wolffd@0 30 end
wolffd@0 31
wolffd@0 32 ss = length(bnet.intra);
wolffd@0 33 % set default arguments
wolffd@0 34 seq = cell(ss, T);
wolffd@0 35 stop_test = [];
wolffd@0 36 for i=1:2:nargs
wolffd@0 37 switch args{i},
wolffd@0 38 case 'evidence', seq = args{i+1}; % initialise observed nodes
wolffd@0 39 case 'stop_test', stop_test = args{i+1};
wolffd@0 40 end
wolffd@0 41 end
wolffd@0 42
wolffd@0 43 t = 1;
wolffd@0 44 for i=1:ss
wolffd@0 45 if ~isempty(stop_test) | isempty(seq{i,t})
wolffd@0 46 ps = parents(bnet.dag, i);
wolffd@0 47 e = bnet.equiv_class(i,1);
wolffd@0 48 pvals = seq(ps);
wolffd@0 49 seq{i,t} = sample_node(bnet.CPD{e}, pvals);
wolffd@0 50 %fprintf('sample i=%d,t=%d,val=%d,ps\n', i, t, seq(i,t)); pvals(:)'
wolffd@0 51 end
wolffd@0 52 end
wolffd@0 53 t = 2;
wolffd@0 54 done = 0;
wolffd@0 55 while ~done
wolffd@0 56 for i=1:ss
wolffd@0 57 if ~isempty(stop_test) | isempty(seq{i,t})
wolffd@0 58 ps = parents(bnet.dag, i+ss) + (t-2)*ss;
wolffd@0 59 e = bnet.equiv_class(i,2);
wolffd@0 60 pvals = seq(ps);
wolffd@0 61 seq{i,t} = sample_node(bnet.CPD{e}, pvals);
wolffd@0 62 %fprintf('sample i=%d,t=%d,val=%d,ps\n', i, t, seq(i,t)); pvals(:)'
wolffd@0 63 end
wolffd@0 64 end
wolffd@0 65 if ~isempty(stop_test)
wolffd@0 66 done = feval(stop_test, seq(:,t));
wolffd@0 67 else
wolffd@0 68 if t==T
wolffd@0 69 done = 1;
wolffd@0 70 end
wolffd@0 71 end
wolffd@0 72 t = t + 1;
wolffd@0 73 end