-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathspm_MDP_VB_X_tutorial.m
1685 lines (1408 loc) · 67.2 KB
/
spm_MDP_VB_X_tutorial.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function [MDP] = spm_MDP_VB_X_tutorial(MDP,OPTIONS)
% UPDATED: 8/28/2024 (modified forgetting rate implementation)
% active inference and learning using variational message passing
% FORMAT [MDP] = spm_MDP_VB_X_tutorial(MDP,OPTIONS)
%
% Input; MDP(m,n) - structure array of m models over n epochs
%
% MDP.V(T - 1,P,F) - P allowable policies (T - 1 moves) over F factors
% or
% MDP.U(1,P,F) - P allowable actions at each move
% MDP.T - number of outcomes
%
% MDP.A{G}(O,N1,...,NF) - likelihood of O outcomes given hidden states
% MDP.B{F}(NF,NF,MF) - transitions among states under MF control states
% MDP.C{G}(O,T) - (log) prior preferences for outcomes (modality G)
% MDP.D{F}(NF,1) - prior probabilities over initial states
% MDP.E(P,1) - prior probabilities over policies
%
% MDP.a{G} - concentration parameters for A
% MDP.b{F} - concentration parameters for B
% MDP.c{G} - concentration parameters for C
% MDP.d{F} - concentration parameters for D
% MDP.e - concentration parameters for E
%
% optional:
% MDP.s(F,T) - matrix of true states - for each hidden factor
% MDP.o(G,T) - matrix of outcomes - for each outcome modality
% or .O{G}(O,T) - likelihood matrix - for each outcome modality
% MDP.u(F,T - 1) - vector of actions - for each hidden factor
%
% MDP.alpha - precision - action selection [512]
% MDP.beta - precision over precision (Gamma hyperprior - [1])
% MDP.chi - Occams window for deep updates
% MDP.tau - time constant for gradient descent [4]
% MDP.eta - learning rate for model parameters
% MDP.omega - forgetting rate for model parameters
% MDP.zeta - Occam's window for polcies [3]
% MDP.erp - resetting of initial states, to simulate ERPs [4]
%
% MDP.demi.C - Mixed model: cell array of true causes (DEM.C)
% MDP.demi.U - Bayesian model average (DEM.U) see: spm_MDP_DEM
% MDP.link - link array to generate outcomes from
% subordinate MDP; for deep (hierarchical) models
%
% OPTIONS.plot - switch to suppress graphics: (default: [0])
% OPTIONS.gamma - switch to suppress precision: (default: [0])
% OPTIONS.D - switch to update initial states over epochs
% OPTIONS.BMR - Bayesian model reduction for multiple trials
% see: spm_MDP_VB_sleep(MDP,BMR)
% Outputs:
%
% MDP.P(M1,...,MF,T) - probability of emitting action M1,.. over time
% MDP.Q{F}(NF,T,P) - expected hidden states under each policy
% MDP.X{F}(NF,T) - and Bayesian model averages over policies
% MDP.R(P,T) - response: conditional expectations over policies
%
% MDP.un - simulated neuronal encoding of hidden states
% MDP.vn - simulated neuronal prediction error
% MDP.xn - simulated neuronal encoding of policies
% MDP.wn - simulated neuronal encoding of precision (tonic)
% MDP.dn - simulated dopamine responses (phasic)
% MDP.rt - simulated reaction times
%
% MDP.F - (P x T) (negative) free energies over time
% MDP.G - (P x T) (negative) expected free energies over time
% MDP.H - (1 x T) (negative) total free energy over time
% MDP.Fa - (1 x 1) (negative) free energy of parameters (a)
% MDP.Fb - ...
%
% This routine provides solutions of active inference (minimisation of
% variational free energy) using a generative model based upon a Markov
% decision process (or hidden Markov model, in the absence of action). The
% model and inference scheme is formulated in discrete space and time. This
% means that the generative model (and process) are finite state machines
% or hidden Markov models whose dynamics are given by transition
% probabilities among states and the likelihood corresponds to a particular
% outcome conditioned upon hidden states.
%
% When supplied with outcomes, in terms of their likelihood (O) in the
% absence of any policy specification, this scheme will use variational
% message passing to optimise expectations about latent or hidden states
% (and likelihood (A) and prior (B) probabilities). In other words, it will
% invert a hidden Markov model. When called with policies, it will
% generate outcomes that are used to infer optimal policies for active
% inference.
%
% This implementation equips agents with the prior beliefs that they will
% maximise expected free energy: expected free energy is the free energy of
% future outcomes under the posterior predictive distribution. This can be
% interpreted in several ways - most intuitively as minimising the KL
% divergence between predicted and preferred outcomes (specified as prior
% beliefs) - while simultaneously minimising ambiguity.
%
% This particular scheme is designed for any allowable policies or control
% sequences specified in MDP.V. Constraints on allowable policies can limit
% the numerics or combinatorics considerably. Further, the outcome space
% and hidden states can be defined in terms of factors; corresponding to
% sensory modalities and (functionally) segregated representations,
% respectively. This means, for each factor or subset of hidden states
% there are corresponding control states that determine the transition
% probabilities.
%
% This specification simplifies the generative model, allowing a fairly
% exhaustive model of potential outcomes. In brief, the agent encodes
% beliefs about hidden states in the past (and in the future) conditioned
% on each policy. The conditional expectations determine the (path
% integral) of free energy that then determines the prior over policies.
% This prior is used to create a predictive distribution over outcomes,
% which specifies the next action.
%
% In addition to state estimation and policy selection, the scheme also
% updates model parameters; including the state transition matrices,
% mapping to outcomes and the initial state. This is useful for learning
% the context. Likelihood and prior probabilities can be specified in terms
% of concentration parameters (of a Dirichlet distribution (a,b,c,..). If
% the corresponding (A,B,C,..) are supplied, they will be used to generate
% outcomes; unless called without policies (in hidden Markov model mode).
% In this case, the (A,B,C,..) are treated as posterior estimates.
%
% If supplied with a structure array, this routine will automatically step
% through the implicit sequence of epochs (implicit in the number of
% columns of the array). If the array has multiple rows, each row will be
% treated as a separate model or agent. This enables agents to communicate
% through acting upon a common set of hidden factors, or indeed sharing the
% same outcomes.
%
% See also: spm_MDP, which uses multiple future states and a mean field
% approximation for control states - but allows for different actions at
% all times (as in control problems).
%
% See also: spm_MDP_game_KL, which uses a very similar formulation but just
% maximises the KL divergence between the posterior predictive distribution
% over hidden states and those specified by preferences or prior beliefs.
%__________________________________________________________________________
% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_MDP_VB_X.m 7943 2020-09-11 17:50:52Z thomas $
% deal with a sequence of trials
%==========================================================================
% options
%--------------------------------------------------------------------------
try, OPTIONS.plot; catch, OPTIONS.plot = 0; end
try, OPTIONS.gamma; catch, OPTIONS.gamma = 0; end
try, OPTIONS.D; catch, OPTIONS.D = 0; end
% check MDP specification
%--------------------------------------------------------------------------
MDP = spm_MDP_check(MDP);
% handle multiple trials, ensuring parameters (and posteriors) are updated
%==========================================================================
if size(MDP,2) > 1
% plotting options
%----------------------------------------------------------------------
GRAPH = OPTIONS.plot;
OPTIONS.plot = 0;
for i = 1:size(MDP,2) % number of MDPs
for m = 1:size(MDP,1) % number of trials
if i > 1 % if previous inversions
% update concentration parameters
%----------------------------------------------------------
MDP(m,i) = spm_MDP_update(MDP(m,i),OUT(m,i - 1));
% update initial states (post-diction)
%----------------------------------------------------------
if any(OPTIONS.D)
nD = numel(MDP(m,i).D);
if numel(OPTIONS.D) ~= nD
OPTIONS.D = ones(nD,1);
end
for f = 1:nD
if OPTIONS.D(f)
MDP(m,i).D{f} = OUT(m,i - 1).X{f}(:,1);
end
end
end
end
end
% solve this trial (for all models synchronously)
%------------------------------------------------------------------
OUT(:,i) = spm_MDP_VB_X_tutorial(MDP(:,i),OPTIONS);
% Bayesian model reduction
%------------------------------------------------------------------
if isfield(OPTIONS,'BMR')
for m = 1:size(MDP,1)
OUT(m,i) = spm_MDP_VB_sleep(OUT(m,i),OPTIONS.BMR);
end
end
end
% plot summary statistics - over trials
%----------------------------------------------------------------------
MDP = OUT;
if GRAPH
if ishandle(GRAPH)
figure(GRAPH); clf
else
spm_figure('GetWin','MDP'); clf
end
spm_MDP_VB_game(MDP(1,:))
end
return
end
% set up and preliminaries
%==========================================================================
% defaults
%--------------------------------------------------------------------------
try, alpha = MDP(1).alpha; catch, alpha = 512; end % action precision
try, beta = MDP(1).beta; catch, beta = 1; end % policy precision
try, zeta = MDP(1).zeta; catch, zeta = 3; end % Occam window policies
try, eta = MDP(1).eta; catch, eta = 1; end % learning rate
try, omega = MDP(1).omega; catch, omega = 1; end % forgetting rate
try, tau = MDP(1).tau; catch, tau = 4; end % update time constant
try, chi = MDP(1).chi; catch, chi = 1/64; end % Occam window updates
try, erp = MDP(1).erp; catch, erp = 4; end % update reset
% preclude precision updates for moving policies
%--------------------------------------------------------------------------
if isfield(MDP,'U'), OPTIONS.gamma = 1; end
% number of updates T & policies V (hidden Markov model with no policies)
%--------------------------------------------------------------------------
[T,V,HMM] = spm_MDP_get_T(MDP);
% initialise model-specific variables
%==========================================================================
Ni = 16; % number of VB iterations
for m = 1:size(MDP,1)
% ensure policy length is less than the number of updates
%----------------------------------------------------------------------
if size(V{m},1) > (T - 1)
V{m} = V{m}(1:(T - 1),:,:);
end
% numbers of transitions, policies and states
%----------------------------------------------------------------------
Ng(m) = numel(MDP(m).A); % number of outcome factors
Nf(m) = numel(MDP(m).B); % number of hidden state factors
Np(m) = size(V{m},2); % number of allowable policies
for f = 1:Nf(m)
Ns(m,f) = size(MDP(m).B{f},1); % number of hidden states
Nu(m,f) = size(MDP(m).B{f},3); % number of hidden controls
end
for g = 1:Ng(m)
No(m,g) = size(MDP(m).A{g},1); % number of outcomes
end
% parameters of generative model and policies
%======================================================================
% likelihood model (for a partially observed MDP)
%----------------------------------------------------------------------
for g = 1:Ng(m)
% ensure probabilities are normalised : A
%------------------------------------------------------------------
MDP(m).A{g} = spm_norm(MDP(m).A{g});
% parameters (concentration parameters): a
%------------------------------------------------------------------
if isfield(MDP,'a')
A{m,g} = spm_norm(MDP(m).a{g});
else
A{m,g} = spm_norm(MDP(m).A{g});
end
% prior concentration paramters for complexity (and novelty)
%------------------------------------------------------------------
if isfield(MDP,'a')
pA{m,g} = MDP(m).a{g};
wA{m,g} = spm_wnorm(MDP(m).a{g}).*(pA{m,g} > 0);
end
end
% transition probabilities (priors)
%----------------------------------------------------------------------
for f = 1:Nf(m)
for j = 1:Nu(m,f)
% controlable transition probabilities : B
%--------------------------------------------------------------
MDP(m).B{f}(:,:,j) = spm_norm(MDP(m).B{f}(:,:,j));
% parameters (concentration parameters): b
%--------------------------------------------------------------
if isfield(MDP,'b') && ~HMM
sB{m,f}(:,:,j) = spm_norm(MDP(m).b{f}(:,:,j) );
rB{m,f}(:,:,j) = spm_norm(MDP(m).b{f}(:,:,j)');
else
sB{m,f}(:,:,j) = spm_norm(MDP(m).B{f}(:,:,j) );
rB{m,f}(:,:,j) = spm_norm(MDP(m).B{f}(:,:,j)');
end
end
% prior concentration paramters for complexity
%------------------------------------------------------------------
if isfield(MDP,'b')
pB{m,f} = MDP(m).b{f};
wB{m,f} = spm_wnorm(MDP(m).b{f}).*(pB{m,f} > 0);
end
end
% priors over initial hidden states - concentration parameters
%----------------------------------------------------------------------
for f = 1:Nf(m)
if isfield(MDP,'d')
D{m,f} = spm_norm(MDP(m).d{f});
elseif isfield(MDP,'D')
D{m,f} = spm_norm(MDP(m).D{f});
else
D{m,f} = spm_norm(ones(Ns(m,f),1));
MDP(m).D{f} = D{m,f};
end
% prior concentration paramters for complexity
%------------------------------------------------------------------
if isfield(MDP,'d')
pD{m,f} = MDP(m).d{f};
wD{m,f} = spm_wnorm(MDP(m).d{f});
end
end
% priors over policies - concentration parameters
%----------------------------------------------------------------------
if isfield(MDP,'e')
E{m} = spm_norm(MDP(m).e);
elseif isfield(MDP,'E')
E{m} = spm_norm(MDP(m).E);
else
E{m} = spm_norm(ones(Np(m),1));
end
qE{m} = spm_log(E{m});
% prior concentration paramters for complexity
%----------------------------------------------------------------------
if isfield(MDP,'e')
pE{m} = MDP(m).e;
end
% prior preferences (log probabilities) : C
%----------------------------------------------------------------------
for g = 1:Ng(m)
if isfield(MDP,'c')
C{m,g} = spm_psi(MDP(m).c{g} + 1/32);
pC{m,g} = MDP(m).c{g};
elseif isfield(MDP,'C')
C{m,g} = MDP(m).C{g};
else
C{m,g} = zeros(No(m,g),1);
end
% assume time-invariant preferences, if unspecified
%------------------------------------------------------------------
if size(C{m,g},2) == 1
C{m,g} = repmat(C{m,g},1,T);
if isfield(MDP,'c')
MDP(m).c{g} = repmat(MDP(m).c{g},1,T);
pC{m,g} = repmat(pC{m,g},1,T);
end
end
C{m,g} = spm_log(spm_softmax(C{m,g}));
end
% initialise posterior expectations of hidden states
%----------------------------------------------------------------------
for f = 1:Nf(m)
xn{m,f} = zeros(Ni,Ns(m,f),1,1,Np(m)) + 1/Ns(m,f);
vn{m,f} = zeros(Ni,Ns(m,f),1,1,Np(m));
x{m,f} = zeros(Ns(m,f),T,Np(m)) + 1/Ns(m,f);
X{m,f} = repmat(D{m,f},1,1);
for k = 1:Np(m)
x{m,f}(:,1,k) = D{m,f};
end
end
% initialise posteriors over polices and action
%----------------------------------------------------------------------
P{m} = zeros([Nu(m,:),1]);
un{m} = zeros(Np(m),1);
u{m} = zeros(Np(m),1);
% if there is only one policy
%----------------------------------------------------------------------
if Np(m) == 1
u{m} = ones(Np(m),T);
end
% if states have not been specified set to 0
%----------------------------------------------------------------------
s{m} = zeros(Nf(m),T);
try
i = find(MDP(m).s);
s{m}(i) = MDP(m).s(i);
end
MDP(m).s = s{m};
% if outcomes have not been specified set to 0
%----------------------------------------------------------------------
o{m} = zeros(Ng(m),T);
try
i = find(MDP(m).o);
o{m}(i) = MDP(m).o(i);
end
MDP(m).o = o{m};
% (indices of) plausible (allowable) policies
%----------------------------------------------------------------------
p{m} = 1:Np(m);
% expected rate parameter (precision of posterior over policies)
%----------------------------------------------------------------------
qb{m} = beta; % initialise rate parameters
w{m} = 1/qb{m}; % posterior precision (policy)
end
% ensure any outcome generating agent is updated first
%--------------------------------------------------------------------------
[M,MDP] = spm_MDP_get_M(MDP,T,Ng);
% belief updating over successive time points
%==========================================================================
for t = 1:T
% generate hidden states and outcomes for each agent or model
%======================================================================
for m = M(t,:)
if ~HMM % not required for HMM
% sample state, if not specified
%--------------------------------------------------------------
for f = 1:Nf(m)
% the next state is generated by action on external states
%----------------------------------------------------------
if MDP(m).s(f,t) == 0
if t > 1
ps = MDP(m).B{f}(:,MDP(m).s(f,t - 1),MDP(m).u(f,t - 1));
else
ps = spm_norm(MDP(m).D{f});
end
MDP(m).s(f,t) = find(rand < cumsum(ps),1);
end
end
% posterior predictive density over hidden (external) states
%--------------------------------------------------------------
for f = 1:Nf(m)
% under selected action (xqq)
%----------------------------------------------------------
if t > 1
xqq{m,f} = sB{m,f}(:,:,MDP(m).u(f,t - 1))*X{m,f}(:,t - 1);
else
xqq{m,f} = X{m,f}(:,t);
end
% Bayesian model average (xq)
%----------------------------------------------------------
xq{m,f} = X{m,f}(:,t);
end
% sample outcome, if not specified
%--------------------------------------------------------------
for g = 1:Ng(m)
% if outcome is not specified
%----------------------------------------------------------
if ~MDP(m).o(g,t)
% outcome is generated by model n
%------------------------------------------------------
if MDP(m).n(g,t)
n = MDP(m).n(g,t);
if n == m
% outcome that minimises free energy (i.e.,
% maximises accuracy)
%----------------------------------------------
F = spm_dot(spm_log(A{m,g}),xqq(m,:));
po = spm_softmax(F*512);
MDP(m).o(g,t) = find(rand < cumsum(po),1);
else
% outcome from model n
%----------------------------------------------
MDP(m).o(g,t) = MDP(n).o(g,t);
end
else
% or sample from likelihood given hidden state
%--------------------------------------------------
ind = num2cell(MDP(m).s(:,t));
po = MDP(m).A{g}(:,ind{:});
MDP(m).o(g,t) = find(rand < cumsum(po),1);
end
end
end
end % HMM
% get probabilistic outcomes from samples or subordinate level
%==================================================================
% get outcome likelihood (O{m})
%------------------------------------------------------------------
for g = 1:Ng(m)
% specified as a likelihood or observation
%--------------------------------------------------------------
if HMM
% specified as a likelihood(HMM)
%----------------------------------------------------------
O{m}{g,t} = MDP(m).O{g}(:,t);
else
% specified as the sampled outcome
%----------------------------------------------------------
O{m}{g,t} = sparse(MDP(m).o(g,t),1,1,No(m,g),1);
end
end
% or generate outcomes from a subordinate MDP
%==================================================================
if isfield(MDP,'link')
% use previous inversions (if available) to reproduce outcomes
%--------------------------------------------------------------
try
mdp = MDP(m).mdp(t);
catch
try
mdp = spm_MDP_update(MDP(m).MDP(t),MDP(m).mdp(t - 1));
catch
try
mdp = spm_MDP_update(MDP(m).MDP(1),MDP(m).mdp(t - 1));
catch
mdp = MDP(m).MDP(1);
end
end
end
% priors over states (of subordinate level)
%--------------------------------------------------------------
mdp.factor = [];
for f = 1:size(MDP(m).link,1)
for g = 1:size(MDP(m).link,2)
if ~isempty(MDP(m).link{f,g})
% subordinate state has hierarchical constraints
%--------------------------------------------------
mdp.factor(end + 1) = f;
% empirical priors over initial states
%--------------------------------------------------
O{m}{g,t} = spm_dot(A{m,g},xq(m,:));
mdp.D{f} = MDP(m).link{f,g}*O{m}{g,t};
% outcomes (i.e., states) are generated by model n
%--------------------------------------------------
if MDP(m).n(g,t)
n = MDP(m).n(g,t);
if m == n
ps = MDP(m).link{f,g}(:,MDP(m).o(g,t));
mdp.s(f,1) = find(ps);
else
mdp.s(f,1) = MDP(n).mdp(t).s(f,1);
end
end
% hidden state for lower level is the outcome
%--------------------------------------------------
try
mdp.s(f,1) = mdp.s(f,1);
catch
ps = MDP(m).link{f,g}(:,MDP(m).o(g,t));
mdp.s(f,1) = find(ps);
end
end
end
end
% empirical prior preferences
%--------------------------------------------------------------
if isfield(MDP,'linkC')
for f = 1:size(MDP(m).linkC,1)
for g = 1:size(MDP(m).linkC,2)
if ~isempty(MDP(m).linkC{f,g})
O{m}{g,t} = spm_dot(A{m,g},xq(m,:));
mdp.C{f} = spm_log(MDP(m).linkC{f,g}*O{m}{g,t});
end
end
end
end
% empirical priors over policies
%--------------------------------------------------------------
if isfield(MDP,'linkE')
mdp.factorE = [];
for g = 1:size(MDP(m).linkE,2)
if ~isempty(MDP(m).linkE{g})
O{m}{g,t} = spm_dot(A{m,g},xq(m,:));
mdp.E = MDP(m).linkE{g}*O{m}{g,t};
end
end
end
% infer hidden states at lower level (outcomes at this level)
%==============================================================
MDP(m).mdp(t) = spm_MDP_VB_X_tutorial(mdp);
% get inferred outcomes from subordinate MDP
%==============================================================
for f = 1:size(MDP(m).link,1)
for g = 1:size(MDP(m).link,2)
if ~isempty(MDP(m).link{f,g})
O{m}{g,t} = MDP(m).link{f,g}'*MDP(m).mdp(t).X{f}(:,1);
end
end
end
% if hierarchical preferences, these contribute to outcomes ...
%--------------------------------------------------------------
if isfield(MDP,'linkC')
for f = 1:size(MDP(m).linkC,1)
for g = 1:size(MDP(m).linkC,2)
if ~isempty(MDP(m).linkC{f,g})
indC = sparse(MDP(m).mdp(t).o(f,:)',1:length(MDP(m).mdp(t).o(f,:)),ones(length(MDP(m).mdp(t).o(f,:)),1),size(MDP(m).mdp(t).C{f},1),size(MDP(m).mdp(t).C{f},2));
O{m}{g,t} = spm_softmax(spm_log(O{m}{g,t}) + MDP(m).linkC{f,g}'*sum((indC.*(MDP(m).mdp(t).C{f})),2));
end
end
end
end
% ... and the same for policies
%--------------------------------------------------------------
if isfield(MDP,'linkE')
for g = 1:size(MDP(m).linkE,2)
if ~isempty(MDP(m).linkE{g})
O{m}{g,t} = spm_softmax(spm_log(O{m}{g,t}) + spm_log(MDP(m).linkE{g}'*MDP(m).mdp(t).R(:,end)));
end
end
end
% Ensure DEM starts with final states from previous inversion
%----------------------------------------------------------
if isfield(MDP(m).MDP,'demi')
MDP(m).MDP.DEM.G(1).x = MDP(m).mdp(t).dem(end).pU.x{1}(:,end);
MDP(m).MDP.DEM.M(1).x = MDP(m).mdp(t).dem(end).qU.x{1}(:,end);
end
end % end of hierarchical mode (link)
% or generate outcome likelihoods from a variational filter
%==================================================================
if isfield(MDP,'demi')
% use previous inversions (if available)
%--------------------------------------------------------------
try
MDP(m).dem(t) = spm_ADEM_update(MDP(m).dem(t - 1));
catch
MDP(m).dem(t) = MDP(m).DEM;
end
% get prior over outcomes
%--------------------------------------------------------------
for g = 1:Ng(m)
O{m}{g,t} = spm_dot(A{m,g},xqq(m,:));
end
% get posterior outcome from Bayesian filtering
%--------------------------------------------------------------
MDP(m).dem(t) = spm_MDP_DEM(MDP(m).dem(t),...
MDP(m).demi,O{m}(:,t),MDP(m).o(:,t));
for g = 1:Ng(m)
O{m}{g,t} = MDP(m).dem(t).X{g}(:,end);
end
end % end outcomes from Bayesian filter
% or generate outcome likelihoods from voice recognition
%==================================================================
if isfield(MDP,'VOX')
% get predictive prior over outcomes if MDP.VOX = 2
%--------------------------------------------------------------
if MDP(m).VOX == 2
% current outcome
%----------------------------------------------------------
for g = 1:Ng(m)
O{m}{g,t} = spm_dot(A{m,g},xqq(m,:));
end
% and next outcome if available
%----------------------------------------------------------
try
for f = 1:Nf(m)
pq{f} = sB{m,f}(:,:)*xqq{m,f};
end
for g = 1:Ng(m)
O{m}{g,t + 1} = spm_dot(A{m,g},pq);
end
end
end
% get likelihood over outcomes - or articulate phrase
%--------------------------------------------------------------
O{m} = spm_MDP_VB_VOX(MDP(m),O{m},t);
% update outcomes
%--------------------------------------------------------------
for g = 1:Ng(m)
po = spm_softmax(O{m}{g,t}*512);
MDP(m).o(g,t) = find(rand < cumsum(po),1);
end
end % end outcomes from voice recognition
% Likelihood of hidden states
%==================================================================
L{m,t} = 1;
for g = 1:Ng(m)
L{m,t} = L{m,t}.*spm_dot(A{m,g},O{m}{g,t});
end
% Variational updates (skip to t = T in HMM mode)
%==================================================================
if ~HMM || T == t
% eliminate unlikely policies
%--------------------------------------------------------------
if ~isfield(MDP,'U') && t > 1
F = log(u{m}(p{m},t - 1));
p{m} = p{m}((F - max(F)) > -zeta);
end
% processing time and reset
%--------------------------------------------------------------
tstart = tic;
for f = 1:Nf(m)
x{m,f} = spm_softmax(spm_log(x{m,f})/erp);
end
% Variational updates (hidden states) under sequential policies
%==============================================================
% variational message passing (VMP)
%--------------------------------------------------------------
S = size(V{m},1) + 1; % horizon
if isfield(MDP,'U')
R = t;
else
R = S;
end
F = zeros(Np(m),1);
for k = p{m} % loop over plausible policies
dF = 1; % reset criterion for this policy
for i = 1:Ni % iterate belief updates
F(k) = 0; % reset free energy for this policy
for j = 1:S % loop over future time points
% curent posterior over outcome factors
%--------------------------------------------------
if j <= t
for f = 1:Nf(m)
xq{m,f} = full(x{m,f}(:,j,k));
end
end
for f = 1:Nf(m)
% hidden states for this time and policy
%----------------------------------------------
sx = full(x{m,f}(:,j,k));
qL = zeros(Ns(m,f),1);
v = zeros(Ns(m,f),1);
% evaluate free energy and gradients (v = dFdx)
%----------------------------------------------
if dF > exp(-8) || i > 4
% marginal likelihood over outcome factors
%------------------------------------------
if j <= t
qL = spm_dot(L{m,j},xq(m,:),f);
qL = spm_log(qL(:));
end
% entropy
%------------------------------------------
qx = spm_log(sx);
% emprical priors (forward messages)
%------------------------------------------
if j < 2
px = spm_log(D{m,f});
v = v + px + qL - qx;
else
px = spm_log(sB{m,f}(:,:,V{m}(j - 1,k,f))*x{m,f}(:,j - 1,k));
v = v + px + qL - qx;
end
% emprical priors (backward messages)
%------------------------------------------
if j < R
px = spm_log(rB{m,f}(:,:,V{m}(j ,k,f))*x{m,f}(:,j + 1,k));
v = v + px + qL - qx;
end
% (negative) free energy
%------------------------------------------
if j == 1 || j == S
F(k) = F(k) + sx'*0.5*v;
else
F(k) = F(k) + sx'*(0.5*v - (Nf(m)-1)*qL/Nf(m));
end
% update
%------------------------------------------
v = v - mean(v);
sx = spm_softmax(qx + v/tau);
else
F(k) = G(k);
end
% store update neuronal activity
%----------------------------------------------
x{m,f}(:,j,k) = sx;
xq{m,f} = sx;
xn{m,f}(i,:,j,t,k) = sx;
vn{m,f}(i,:,j,t,k) = v;
end
end
% convergence
%------------------------------------------------------
if i > 1
dF = F(k) - G(k);
end
G = F;
end
end
% accumulate expected free energy of policies (Q)
%==============================================================
pu = 1; % empirical prior
qu = 1; % posterior
Q = zeros(Np(m),1); % expected free energy
if Np(m) > 1
for k = p{m}
% Bayesian surprise about inital conditions
%------------------------------------------------------
if isfield(MDP,'d')
for f = 1:Nf(m)
Q(k) = Q(k) - spm_dot(wD{m,f},x{m,f}(:,1,k));
end
end
for j = t:S
% get expected states for this policy and time
%--------------------------------------------------
for f = 1:Nf(m)
xq{m,f} = x{m,f}(:,j,k);
end
% (negative) expected free energy
%==================================================
% Bayesian surprise about states
%--------------------------------------------------
Q(k) = Q(k) + spm_MDP_G(A(m,:),xq(m,:));
for g = 1:Ng(m)
% prior preferences about outcomes
%----------------------------------------------
qo = spm_dot(A{m,g},xq(m,:));
Q(k) = Q(k) + qo'*(C{m,g}(:,j));
% Bayesian surprise about parameters
%----------------------------------------------
if isfield(MDP,'a')
Q(k) = Q(k) - spm_dot(wA{m,g},{qo xq{m,:}});
end
end
if isfield(MDP,'b')
for f = 1:Nf(m)
if j < S && k <= size(wB{m,f},3)
Q(k) = Q(k) - spm_dot(wB{m,f}(:,:,k),{xq{m,f},x{m,f}(:,j+1,k)});
end
end
end
end
end
% variational updates - policies and precision
%==========================================================
% previous expected precision
%----------------------------------------------------------
if t > 1
w{m}(t) = w{m}(t - 1);
end
for i = 1:Ni
% posterior and prior beliefs about policies
%------------------------------------------------------
qu = spm_softmax(qE{m}(p{m}) + w{m}(t)*Q(p{m}) + F(p{m}));
pu = spm_softmax(qE{m}(p{m}) + w{m}(t)*Q(p{m}));
% precision (w) with free energy gradients (v = -dF/dw)
%------------------------------------------------------
if OPTIONS.gamma
w{m}(t) = 1/beta;
else
eg = (qu - pu)'*Q(p{m});
dFdg = qb{m} - beta + eg;
qb{m} = qb{m} - dFdg/2;
w{m}(t) = 1/qb{m};
end
% simulated dopamine responses (expected precision)
%------------------------------------------------------
n = (t - 1)*Ni + i;
wn{m}(n,1) = w{m}(t);
un{m}(p{m},n) = qu;
u{m}(p{m},t) = qu;
end
end % end of loop over multiple policies
% Bayesian model averaging of hidden states (over policies)
%--------------------------------------------------------------
for f = 1:Nf(m)
for i = 1:S
X{m,f}(:,i) = reshape(x{m,f}(:,i,:),Ns(m,f),Np(m))*u{m}(:,t);
end
end
% processing (i.e., reaction) time
%--------------------------------------------------------------
rt{m}(t) = toc(tstart);
% record (negative) free energies
%--------------------------------------------------------------
MDP(m).F(:,t) = F;