spm_GDEM.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. function [DEM] = spm_GDEM(DEM)
  2. % Dynamic expectation maximisation: Generation and inversion
  3. % FORMAT DEM = spm_GDEM(DEM)
  4. %
  5. % DEM.G - generation model
  6. % DEM.M - inversion model
  7. % DEM.C - causes
  8. % DEM.U - prior expectation of causes
  9. %__________________________________________________________________________
  10. %
  11. % This implementation of DEM is the same as spm_DEM but integrates both the
  12. % generative and inversion models in parallel. Its functionality is exactly
  13. % the same apart from the fact that confounds are not accommodated
  14. % explicitly. The generative model is specified by DEM.G and the veridical
  15. % causes by DEM.C; these may or may not be used as priors on the causes for
  16. % the inversion model DEM.M (i..e, DEM.U = DEM.C). Clearly, DEM.G does not
  17. % requires any priors or precision components; it will use the values of the
  18. % parameters specified in the prior expectation fields.
  19. %
  20. % This routine is not used for model inversion per se but the simulate the
  21. % dynamical inversion of models (as a preclude to coupling the model back to
  22. % the generative process (see spm_ADEM)
  23. %
  24. % hierarchical models G(i) and M(i)
  25. %--------------------------------------------------------------------------
  26. % M(i).g = y(t) = g(x,v,P) {inline function, string or m-file}
  27. % M(i).f = dx/dt = f(x,v,P) {inline function, string or m-file}
  28. %
  29. % M(i).pE = prior expectation of p model-parameters
  30. % M(i).pC = prior covariances of p model-parameters
  31. % M(i).hE = prior expectation of h hyper-parameters (cause noise)
  32. % M(i).hC = prior covariances of h hyper-parameters (cause noise)
  33. % M(i).gE = prior expectation of g hyper-parameters (state noise)
  34. % M(i).gC = prior covariances of g hyper-parameters (state noise)
  35. % M(i).Q = precision components (input noise)
  36. % M(i).R = precision components (state noise)
  37. % M(i).V = fixed precision (input noise)
  38. % M(i).W = fixed precision (state noise)
  39. %
  40. % M(i).m = number of inputs v(i + 1);
  41. % M(i).n = number of states x(i);
  42. % M(i).l = number of output v(i);
  43. %
  44. % Returns the following fields of DEM
  45. %--------------------------------------------------------------------------
  46. %
  47. % true model-states - u
  48. %--------------------------------------------------------------------------
  49. % pU.x = hidden states
  50. % pU.v = causal states v{1} = response (Y)
  51. %
  52. % model-parameters - p
  53. %--------------------------------------------------------------------------
  54. % pP.P = parameters for each level
  55. %
  56. % hyper-parameters (log-transformed) - h ,g
  57. %--------------------------------------------------------------------------
  58. % pH.h = cause noise
  59. % pH.g = state noise
  60. %
  61. % conditional moments of model-states - q(u)
  62. %--------------------------------------------------------------------------
  63. % qU.x = Conditional expectation of hidden states
  64. % qU.v = Conditional expectation of causal states
  65. % qU.z = Conditional prediction errors (v)
  66. % qU.C = Conditional covariance: cov(v)
  67. % qU.S = Conditional covariance: cov(x)
  68. %
  69. % conditional moments of model-parameters - q(p)
  70. %--------------------------------------------------------------------------
  71. % qP.P = Conditional expectation
  72. % qP.C = Conditional covariance
  73. %
  74. % conditional moments of hyper-parameters (log-transformed) - q(h)
  75. %--------------------------------------------------------------------------
  76. % qH.h = Conditional expectation (cause noise)
  77. % qH.g = Conditional expectation (state noise)
  78. % qH.C = Conditional covariance
  79. %
  80. % F = log evidence = log marginal likelihood = negative free energy
  81. %__________________________________________________________________________
  82. %
  83. % spm_DEM implements a variational Bayes (VB) scheme under the Laplace
  84. % approximation to the conditional densities of states (u), parameters (p)
  85. % and hyperparameters (h) of any analytic nonlinear hierarchical dynamic
  86. % model, with additive Gaussian innovations. It comprises three
  87. % variational steps (D,E and M) that update the conditional moments of u, p
  88. % and h respectively
  89. %
  90. % D: qu.u = max <L>q(p,h)
  91. % E: qp.p = max <L>q(u,h)
  92. % M: qh.h = max <L>q(u,p)
  93. %
  94. % where qu.u corresponds to the conditional expectation of hidden states x
  95. % and causal states v and so on. L is the ln p(y,u,p,h|M) under the model
  96. % M. The conditional covariances obtain analytically from the curvature of
  97. % L with respect to u, p and h.
  98. %
  99. % The D-step is embedded in the E-step because q(u) changes with each
  100. % sequential observation. The dynamical model is transformed into a static
  101. % model using temporal derivatives at each time point. Continuity of the
  102. % conditional trajectories q(u,t) is assured by a continuous ascent of F(t)
  103. % in generalised co-ordinates. This means DEM can deconvolve online and can
  104. % represents an alternative to Kalman filtering or alternative Bayesian
  105. % update procedures.
  106. %__________________________________________________________________________
  107. % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
  108. % Karl Friston
  109. % $Id: spm_GDEM.m 5219 2013-01-29 17:07:07Z spm $
  110. % check model, data, priors and confounds and unpack
  111. %--------------------------------------------------------------------------
  112. DEM = spm_DEM_set(DEM);
  113. M = DEM.M;
  114. G = DEM.G;
  115. C = DEM.C;
  116. U = DEM.U;
  117. % ensure embedding dimensions are compatible
  118. %--------------------------------------------------------------------------
  119. g = M(1).E.n;
  120. G(1).E.n = g;
  121. G(1).E.d = g;
  122. % find or create a DEM figure
  123. %--------------------------------------------------------------------------
  124. clear spm_DEM_eval
  125. sw = warning('off');
  126. Fdem = spm_figure('GetWin','DEM');
  127. % order parameters (d = n = 1 for static models) and checks
  128. %==========================================================================
  129. g = g + 1; % embedding order for generation
  130. d = M(1).E.d + 1; % embedding order of q(v)
  131. n = M(1).E.n + 1; % embedding order of q(x) (n >= d)
  132. s = M(1).E.s; % smoothness - s.d. of kernel (bins)
  133. % number of states and parameters
  134. %--------------------------------------------------------------------------
  135. nY = size(C,2); % number of samples
  136. nl = size(M,2); % number of levels
  137. nr = sum(spm_vec(M.l)); % number of v (outputs)
  138. nv = sum(spm_vec(M.m)); % number of v (casual states)
  139. nx = sum(spm_vec(M.n)); % number of x (hidden states)
  140. ny = M(1).l; % number of y (inputs)
  141. nc = M(end).l; % number of c (prior causes)
  142. nu = nv*d + nx*n; % number of generalised states
  143. % number of iterations
  144. %--------------------------------------------------------------------------
  145. try nM = M(1).E.nM; catch, nM = 8; end
  146. try nN = M(1).E.nN; catch, nN = 16; end
  147. % initialise regularisation parameters
  148. %--------------------------------------------------------------------------
  149. td = 1; % integration time for D-Step
  150. te = exp(32); % integration time for E-Step
  151. % precision (R) and covariance of generalised errors
  152. %--------------------------------------------------------------------------
  153. iV = spm_DEM_R(n,s);
  154. % precision components Q{} requiring [Re]ML estimators (M-Step)
  155. %==========================================================================
  156. Q = {};
  157. for i = 1:nl
  158. q0{i,i} = sparse(M(i).l,M(i).l);
  159. r0{i,i} = sparse(M(i).n,M(i).n);
  160. end
  161. Q0 = kron(iV,spm_cat(q0));
  162. R0 = kron(iV,spm_cat(r0));
  163. for i = 1:nl
  164. for j = 1:length(M(i).Q)
  165. q = q0;
  166. q{i,i} = M(i).Q{j};
  167. Q{end + 1} = blkdiag(kron(iV,spm_cat(q)),R0);
  168. end
  169. for j = 1:length(M(i).R)
  170. q = r0;
  171. q{i,i} = M(i).R{j};
  172. Q{end + 1} = blkdiag(Q0,kron(iV,spm_cat(q)));
  173. end
  174. end
  175. % and fixed components P
  176. %--------------------------------------------------------------------------
  177. Q0 = kron(iV,spm_cat(spm_diag({M.V})));
  178. R0 = kron(iV,spm_cat(spm_diag({M.W})));
  179. Qp = blkdiag(Q0,R0);
  180. Q0 = kron(iV,speye(nv));
  181. R0 = kron(iV,speye(nx));
  182. Qu = blkdiag(Q0,R0);
  183. nh = length(Q); % number of hyperparameters
  184. % fixed priors on states (u)
  185. %--------------------------------------------------------------------------
  186. Px = kron(iV(1:n,1:n),sparse(nx,nx));
  187. Pv = kron(iV(1:d,1:d),sparse(nv,nv));
  188. Pu = spm_cat(spm_diag({Px Pv}));
  189. % hyperpriors
  190. %--------------------------------------------------------------------------
  191. ph.h = spm_vec({M.hE M.gE}); % prior expectation of h
  192. ph.c = spm_cat(spm_diag({M.hC M.gC})); % prior covariances of h
  193. qh.h = ph.h; % conditional expectation
  194. qh.c = ph.c; % conditional covariance
  195. ph.ic = inv(ph.c); % prior precision
  196. % priors on parameters (in reduced parameter space)
  197. %==========================================================================
  198. pp.c = cell(nl,nl);
  199. qp.p = cell(nl,1);
  200. for i = 1:(nl - 1)
  201. % eigenvector reduction: p <- pE + qp.u*qp.p
  202. %----------------------------------------------------------------------
  203. qp.u{i} = spm_svd(M(i).pC); % basis for parameters
  204. M(i).p = size(qp.u{i},2); % number of qp.p
  205. qp.p{i} = sparse(M(i).p,1); % initial qp.p
  206. pp.c{i,i} = qp.u{i}'*M(i).pC*qp.u{i}; % prior covariance
  207. end
  208. Up = spm_cat(spm_diag(qp.u));
  209. % initialise and augment with confound parameters B; with flat priors
  210. %--------------------------------------------------------------------------
  211. np = sum(spm_vec(M.p)); % number of model parameters
  212. pp.c = spm_cat(pp.c);
  213. pp.ic = inv(pp.c);
  214. % initialise conditional density q(p) (for D-Step)
  215. %--------------------------------------------------------------------------
  216. qp.e = spm_vec(qp.p);
  217. qp.c = sparse(np,np);
  218. % initialise cell arrays for D-Step; e{i + 1} = (d/dt)^i[e] = e[i]
  219. %==========================================================================
  220. qu.x = cell(n,1);
  221. qu.v = cell(n,1);
  222. qu.y = cell(n,1);
  223. qu.u = cell(n,1);
  224. pu.v = cell(g,1);
  225. pu.x = cell(g,1);
  226. pu.z = cell(g,1);
  227. pu.w = cell(g,1);
  228. [qu.x{:}] = deal(sparse(nx,1));
  229. [qu.v{:}] = deal(sparse(nv,1));
  230. [qu.y{:}] = deal(sparse(ny,1));
  231. [qu.u{:}] = deal(sparse(nc,1));
  232. [pu.v{:}] = deal(sparse(nr,1));
  233. [pu.x{:}] = deal(sparse(nx,1));
  234. [pu.z{:}] = deal(sparse(nr,1));
  235. [pu.w{:}] = deal(sparse(nx,1));
  236. % initialise cell arrays for hierarchical structure of x[0] and v[0]
  237. %--------------------------------------------------------------------------
  238. qu.x{1} = spm_vec({M(1:end - 1).x});
  239. qu.v{1} = spm_vec({M(1 + 1:end).v});
  240. pu.x{1} = spm_vec({G.x});
  241. pu.v{1} = spm_vec({G.v});
  242. % derivatives for Jacobian of D-step
  243. %--------------------------------------------------------------------------
  244. Dx = kron(spm_speye(n,n,1),spm_speye(nx,nx,0));
  245. Dv = kron(spm_speye(d,d,1),spm_speye(nv,nv,0));
  246. Dc = kron(spm_speye(d,d,1),spm_speye(nc,nc,0));
  247. Du = spm_cat(spm_diag({Dx,Dv}));
  248. Dq = spm_cat(spm_diag({Dx,Dv,Dc}));
  249. Dx = kron(spm_speye(g,g,1),spm_speye(nx,nx,0));
  250. Dv = kron(spm_speye(g,g,1),spm_speye(nr,nr,0));
  251. Dp = spm_cat(spm_diag({Dv,Dx,Dv,Dx}));
  252. dfdw = kron(speye(g,g),speye(nx,nx));
  253. dydv = kron(speye(n,g),speye(ny,nr));
  254. % and null blocks
  255. %--------------------------------------------------------------------------
  256. dVdy = sparse(n*ny,1);
  257. dVdc = sparse(d*nc,1);
  258. % gradients and curvatures for conditional uncertainty
  259. %--------------------------------------------------------------------------
  260. dWdu = sparse(nu,1);
  261. dWdp = sparse(np,1);
  262. dWduu = sparse(nu,nu);
  263. dWdpp = sparse(np,np);
  264. % preclude unnecessary iterations
  265. %--------------------------------------------------------------------------
  266. if ~np && ~nh, nN = 1; end
  267. % create innovations (and add causes)
  268. %--------------------------------------------------------------------------
  269. [z,w] = spm_DEM_z(G,nY);
  270. z{end} = C + z{end};
  271. Z = spm_cat(z(:));
  272. W = spm_cat(w(:));
  273. % Iterate DEM
  274. %==========================================================================
  275. Fm = -exp(64);
  276. for iN = 1:nN
  277. % E-Step: (with embedded D-Step)
  278. %======================================================================
  279. % [re-]set accumulators for E-Step
  280. %----------------------------------------------------------------------
  281. dFdp = zeros(np,1);
  282. dFdpp = zeros(np,np);
  283. EE = sparse(0);
  284. ECE = sparse(0);
  285. qp.ic = sparse(0);
  286. qu_c = speye(1);
  287. % [re-]set precisions using ReML hyperparameter estimates
  288. %----------------------------------------------------------------------
  289. iS = Qp;
  290. for i = 1:nh
  291. iS = iS + Q{i}*exp(qh.h(i));
  292. end
  293. % [re-]set states & their derivatives
  294. %----------------------------------------------------------------------
  295. try
  296. qu = qU(1);
  297. end
  298. % D-Step: (nD D-Steps for each sample)
  299. %======================================================================
  300. for iY = 1:nY
  301. % D-Step: until convergence for static systems
  302. %==================================================================
  303. % derivatives of responses and inputs
  304. %------------------------------------------------------------------
  305. pu.z = spm_DEM_embed(Z,g,iY);
  306. pu.w = spm_DEM_embed(W,g,iY);
  307. qu.u = spm_DEM_embed(U,n,iY);
  308. % evaluate generative model
  309. %------------------------------------------------------------------
  310. [pu,dgdv,dgdx,dfdv,dfdx] = spm_DEM_diff(G,pu);
  311. % tensor products for Jabobian
  312. %------------------------------------------------------------------
  313. dgdv = kron(spm_speye(n,n,1),dgdv);
  314. dgdx = kron(spm_speye(n,n,1),dgdx);
  315. dfdv = kron(spm_speye(n,n,0),dfdv);
  316. dfdx = kron(spm_speye(n,n,0),dfdx);
  317. % and pass response to qu.y
  318. %------------------------------------------------------------------
  319. for i = 1:n
  320. y = spm_unvec(pu.v{i},{G.v});
  321. qu.y{i} = y{1};
  322. end
  323. % evaluate recognition model
  324. %------------------------------------------------------------------
  325. [E dE] = spm_DEM_eval(M,qu,qp);
  326. % conditional covariance [of states {u}]
  327. %------------------------------------------------------------------
  328. qu.c = inv(dE.du'*iS*dE.du + Pu);
  329. qu_c = qu_c*qu.c;
  330. % save at qu(t)
  331. %------------------------------------------------------------------
  332. qE{iY} = E;
  333. qC{iY} = qu.c;
  334. qU(iY) = qu;
  335. pU(iY) = pu;
  336. % and conditional covariance [of parameters {P}]
  337. %------------------------------------------------------------------
  338. ECEu = dE.du*qu.c*dE.du';
  339. ECEp = dE.dp*qp.c*dE.dp';
  340. % uncertainty about parameters dWdv, ... ; W = ln(|qp.c|)
  341. %==================================================================
  342. if np
  343. for i = 1:nu
  344. CJp(:,i) = spm_vec(qp.c*dE.dpu{i}'*iS);
  345. dEdpu(:,i) = spm_vec(dE.dpu{i}');
  346. end
  347. dWdu = CJp'*spm_vec(dE.dp');
  348. dWduu = CJp'*dEdpu;
  349. end
  350. % first-order derivatives
  351. %------------------------------------------------------------------
  352. dVdu = -dE.du'*iS*E - dWdu/2;
  353. % and second-order derivatives
  354. %------------------------------------------------------------------
  355. dVduu = -dE.du'*iS*dE.du - dWduu/2;
  356. dVduv = -dE.du'*iS*dE.dy*dydv;
  357. dVduc = -dE.du'*iS*dE.dc;
  358. % D-step update: of causes v{i}, and hidden states x(i)
  359. %==================================================================
  360. % states and conditional modes
  361. %------------------------------------------------------------------
  362. p = {pu.v{1:g} pu.x{1:g} pu.z{1:g} pu.w{1:g}};
  363. q = {qu.x{1:n} qu.v{1:d} qu.u{1:d}};
  364. u = {p{:} q{:}};
  365. % gradient
  366. %------------------------------------------------------------------
  367. dFdu = [ Dp*spm_vec(p);
  368. spm_vec({dVdu; dVdc}) + Dq*spm_vec(q)];
  369. % Jacobian (variational flow)
  370. %------------------------------------------------------------------
  371. dFduu = spm_cat({dgdv dgdx Dv [] [] [];
  372. dfdv dfdx [] dfdw [] [];
  373. [] [] Dv [] [] [];
  374. [] [] [] Dx [] [];
  375. dVduv [] [] [] Du+dVduu dVduc;
  376. [] [] [] [] [] Dc});
  377. % update states q = {x,v,z,w} and conditional modes
  378. %==================================================================
  379. du = spm_dx(dFduu,dFdu,td);
  380. u = spm_unvec(spm_vec(u) + du,u);
  381. % and save them
  382. %------------------------------------------------------------------
  383. pu.v(1:n) = u([1:n]);
  384. pu.x(1:n) = u([1:n] + g);
  385. qu.x(1:n) = u([1:n] + g + g + g + g);
  386. qu.v(1:d) = u([1:d] + g + g + g + g + n);
  387. % Gradients and curvatures for E-Step: W = tr(C*J'*iS*J)
  388. %==================================================================
  389. if np
  390. for i = 1:np
  391. CJu(:,i) = spm_vec(qu.c*dE.dup{i}'*iS);
  392. dEdup(:,i) = spm_vec(dE.dup{i}');
  393. end
  394. dWdp = CJu'*spm_vec(dE.du');
  395. dWdpp = CJu'*dEdup;
  396. end
  397. % Accumulate; dF/dP = <dL/dp>, dF/dpp = ...
  398. %------------------------------------------------------------------
  399. dFdp = dFdp - dWdp/2 - dE.dp'*iS*E;
  400. dFdpp = dFdpp - dWdpp/2 - dE.dp'*iS*dE.dp;
  401. qp.ic = qp.ic + dE.dp'*iS*dE.dp;
  402. % and quantities for M-Step
  403. %------------------------------------------------------------------
  404. EE = E*E'+ EE;
  405. ECE = ECE + ECEu + ECEp;
  406. end % sequence (nY)
  407. % augment with priors
  408. %----------------------------------------------------------------------
  409. dFdp = dFdp - pp.ic*qp.e;
  410. dFdpp = dFdpp - pp.ic;
  411. qp.ic = qp.ic + pp.ic;
  412. qp.c = inv(qp.ic);
  413. % E-step: update expectation (p)
  414. %======================================================================
  415. % update conditional expectation
  416. %----------------------------------------------------------------------
  417. dp = spm_dx(dFdpp,dFdp,{te});
  418. qp.e = qp.e + dp;
  419. qp.p = spm_unvec(qp.e,qp.p);
  420. % M-step - hyperparameters (h = exp(l))
  421. %======================================================================
  422. mh = zeros(nh,1);
  423. dFdh = zeros(nh,1);
  424. dFdhh = zeros(nh,nh);
  425. for iM = 1:nM
  426. % [re-]set precisions using ReML hyperparameter estimates
  427. %------------------------------------------------------------------
  428. iS = Qp;
  429. for i = 1:nh
  430. iS = iS + Q{i}*exp(qh.h(i));
  431. end
  432. S = inv(iS);
  433. dS = ECE + EE - S*nY;
  434. % 1st-order derivatives: dFdh = dF/dh
  435. %------------------------------------------------------------------
  436. for i = 1:nh
  437. dPdh{i} = Q{i}*exp(qh.h(i));
  438. dFdh(i,1) = -trace(dPdh{i}*dS)/2;
  439. end
  440. % 2nd-order derivatives: dFdhh
  441. %------------------------------------------------------------------
  442. for i = 1:nh
  443. for j = 1:nh
  444. dFdhh(i,j) = -trace(dPdh{i}*S*dPdh{j}*S*nY)/2;
  445. end
  446. end
  447. % hyperpriors
  448. %------------------------------------------------------------------
  449. qh.e = qh.h - ph.h;
  450. dFdh = dFdh - ph.ic*qh.e;
  451. dFdhh = dFdhh - ph.ic;
  452. % update ReML estimate of parameters
  453. %------------------------------------------------------------------
  454. dh = spm_dx(dFdhh,dFdh);
  455. qh.h = qh.h + dh;
  456. mh = mh + dh;
  457. % conditional covariance of hyperparameters
  458. %------------------------------------------------------------------
  459. qh.c = -inv(dFdhh);
  460. % convergence (M-Step)
  461. %------------------------------------------------------------------
  462. if (dFdh'*dh < 1e-2) || (norm(dh,1) < exp(-8)), break, end
  463. end % M-Step
  464. % evaluate objective function (F)
  465. %======================================================================
  466. L = - trace(iS*EE)/2 ... % states (u)
  467. - trace(qp.e'*pp.ic*qp.e)/2 ... % parameters (p)
  468. - trace(qh.e'*ph.ic*qh.e)/2 ... % hyperparameters (h)
  469. + spm_logdet(qu_c)/2 ... % entropy q(u)
  470. + spm_logdet(qp.c)/2 ... % entropy q(p)
  471. + spm_logdet(qh.c)/2 ... % entropy q(h)
  472. - spm_logdet(pp.c)/2 ... % entropy - prior p
  473. - spm_logdet(ph.c)/2 ... % entropy - prior h
  474. + spm_logdet(iS)*nY/2 ... % entropy - error
  475. - n*ny*nY*log(2*pi)/2;
  476. % if F is increasing, save expansion point and dervatives
  477. %----------------------------------------------------------------------
  478. if L > (Fm + 1e-2)
  479. Fm = L;
  480. F(iN) = Fm;
  481. % save model-states (for each time point)
  482. %==================================================================
  483. for t = 1:length(qU)
  484. % states
  485. %--------------------------------------------------------------
  486. v = spm_unvec(pU(t).v{1},{G.v});
  487. x = spm_unvec(pU(t).x{1},{G.x});
  488. z = spm_unvec(pU(t).z{1},{G.v});
  489. w = spm_unvec(pU(t).w{1},{G.x});
  490. for i = 1:nl
  491. PU.v{i}(:,t) = spm_vec(v{i});
  492. PU.z{i}(:,t) = spm_vec(z{i});
  493. try
  494. PU.x{i}(:,t) = spm_vec(x{i});
  495. PU.w{i}(:,t) = spm_vec(w{i});
  496. end
  497. end
  498. % conditional modes
  499. %--------------------------------------------------------------
  500. v = spm_unvec(qU(t).v{1},{M(1 + 1:end).v});
  501. x = spm_unvec(qU(t).x{1},{M(1:end - 1).x});
  502. z = spm_unvec(qE{t},{M.v});
  503. for i = 1:(nl - 1)
  504. QU.v{i + 1}(:,t) = spm_vec(v{i});
  505. try
  506. QU.x{i}(:,t) = spm_vec(x{i});
  507. end
  508. QU.z{i}(:,t) = spm_vec(z{i});
  509. end
  510. QU.v{1}(:,t) = spm_vec(qU(t).y{1} - z{1});
  511. QU.z{nl}(:,t) = spm_vec(z{nl});
  512. % and conditional covariances
  513. %--------------------------------------------------------------
  514. i = [1:nx];
  515. QU.S{t} = qC{t}(i,i);
  516. i = [1:nv] + nx*n;
  517. QU.C{t} = qC{t}(i,i);
  518. end
  519. % save conditional densities
  520. %------------------------------------------------------------------
  521. B.QU = QU;
  522. B.PU = PU;
  523. B.qp = qp;
  524. B.qh = qh;
  525. % report and break if convergence
  526. %------------------------------------------------------------------
  527. figure(Fdem)
  528. spm_DEM_qU(QU)
  529. if np
  530. subplot(nl,4,4*nl)
  531. bar(full(Up*qp.e))
  532. xlabel({'parameters';'{minus prior}'})
  533. axis square, grid on
  534. end
  535. if length(F) > 2
  536. subplot(nl,4,4*nl - 1)
  537. plot(F(2:end))
  538. xlabel('updates')
  539. title('log-evidence')
  540. axis square, grid on
  541. end
  542. drawnow
  543. % report (EM-Steps)
  544. %------------------------------------------------------------------
  545. str{1} = sprintf('DEM: %i (%i)',iN,iM);
  546. str{2} = sprintf('F:%.6e',full(Fm));
  547. str{3} = sprintf('p:%.2e',full(dp'*dp));
  548. str{4} = sprintf('h:%.2e',full(mh'*mh));
  549. fprintf('%-16s%-24s%-16s%-16s\n',str{1:4})
  550. else
  551. % otherwise, return to previous expansion point and break
  552. %------------------------------------------------------------------
  553. QU = B.QU;
  554. PU = B.PU;
  555. qp = B.qp;
  556. qh = B.qh;
  557. break
  558. end
  559. end
  560. % Assemble output arguments
  561. %==========================================================================
  562. % Fill in DEM with response and its causes
  563. %--------------------------------------------------------------------------
  564. DEM.Y = PU.v{1};
  565. DEM.pU = PU;
  566. DEM.pP.P = {G.pE};
  567. DEM.pH.h = {G.hE};
  568. DEM.pH.g = {G.gE};
  569. % conditional moments of model-parameters (rotated into original space)
  570. %--------------------------------------------------------------------------
  571. qP.P = spm_unvec(Up*qp.e + spm_vec(M.pE),M.pE);
  572. qP.C = Up*qp.c*Up';
  573. qP.V = spm_unvec(diag(qP.C),M.pE);
  574. % conditional moments of hyper-parameters (log-transformed)
  575. %--------------------------------------------------------------------------
  576. qH.h = spm_unvec(qh.h,{{M.hE} {M.gE}});
  577. qH.g = qH.h{2};
  578. qH.h = qH.h{1};
  579. qH.C = qh.c;
  580. qH.V = spm_unvec(diag(qH.C),{{M.hE} {M.gE}});
  581. qH.W = qH.V{2};
  582. qH.V = qH.V{1};
  583. % assign output variables
  584. %--------------------------------------------------------------------------
  585. DEM.M = M;
  586. DEM.U = U; % causes
  587. DEM.qU = QU; % conditional moments of model-states
  588. DEM.qP = qP; % conditional moments of model-parameters
  589. DEM.qH = qH; % conditional moments of hyper-parameters
  590. DEM.F = F; % [-ve] Free energy
  591. warning(sw);