-
Notifications
You must be signed in to change notification settings - Fork 2
/
control.py
executable file
·1338 lines (1128 loc) · 64 KB
/
control.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=no-member
# pylint: disable=not-an-iterable
import itertools
import numpy as np
from pymdp.maths import softmax, softmax_obj_arr, spm_dot, spm_wnorm, spm_MDP_G, spm_log_single, spm_log_obj_array
from pymdp import utils
import copy
import random
def update_posterior_policies_full(
qs_seq_pi,
A,
B,
C,
policies,
use_utility=True,
use_states_info_gain=True,
use_param_info_gain=False,
prior=None,
pA=None,
pB=None,
F = None,
E = None,
gamma=16.0
):
"""
Update posterior beliefs about policies by computing expected free energy of each policy and integrating that
with the variational free energy of policies ``F`` and prior over policies ``E``. This is intended to be used in conjunction
with the ``update_posterior_states_full`` method of ``inference.py``, since the full posterior over future timesteps, under all policies, is
assumed to be provided in the input array ``qs_seq_pi``.
Parameters
----------
qs_seq_pi: ``numpy.ndarray`` of dtype object
Posterior beliefs over hidden states for each policy. Nesting structure is policies, timepoints, factors,
where e.g. ``qs_seq_pi[p][t][f]`` stores the marginal belief about factor ``f`` at timepoint ``t`` under policy ``p``.
A: ``numpy.ndarray`` of dtype object
Sensory likelihood mapping or 'observation model', mapping from hidden states to observations. Each element ``A[m]`` of
stores an ``numpy.ndarray`` multidimensional array for observation modality ``m``, whose entries ``A[m][i, j, k, ...]`` store
the probability of observation level ``i`` given hidden state levels ``j, k, ...``
B: ``numpy.ndarray`` of dtype object
Dynamics likelihood mapping or 'transition model', mapping from hidden states at ``t`` to hidden states at ``t+1``, given some control state ``u``.
Each element ``B[f]`` of this object array stores a 3-D tensor for hidden state factor ``f``, whose entries ``B[f][s, v, u]`` store the probability
of hidden state level ``s`` at the current time, given hidden state level ``v`` and action ``u`` at the previous time.
C: ``numpy.ndarray`` of dtype object
Prior over observations or 'prior preferences', storing the "value" of each outcome in terms of relative log probabilities.
This is softmaxed to form a proper probability distribution before being used to compute the expected utility term of the expected free energy.
policies: ``list`` of 2D ``numpy.ndarray``
``list`` that stores each policy in ``policies[p_idx]``. Shape of ``policies[p_idx]`` is ``(num_timesteps, num_factors)`` where `num_timesteps` is the temporal
depth of the policy and ``num_factors`` is the number of control factors.
use_utility: ``Bool``, default ``True``
Boolean flag that determines whether expected utility should be incorporated into computation of EFE.
use_states_info_gain: ``Bool``, default ``True``
Boolean flag that determines whether state epistemic value (info gain about hidden states) should be incorporated into computation of EFE.
use_param_info_gain: ``Bool``, default ``False``
Boolean flag that determines whether parameter epistemic value (info gain about generative model parameters) should be incorporated into computation of EFE.
prior: ``numpy.ndarray`` of dtype object, default ``None``
If provided, this is a ``numpy`` object array with one sub-array per hidden state factor, that stores the prior beliefs about initial states.
If ``None``, this defaults to a flat (uninformative) prior over hidden states.
pA: ``numpy.ndarray`` of dtype object, default ``None``
Dirichlet parameters over observation model (same shape as ``A``)
pB: ``numpy.ndarray`` of dtype object, default ``None``
Dirichlet parameters over transition model (same shape as ``B``)
F: 1D ``numpy.ndarray``, default ``None``
Vector of variational free energies for each policy
E: 1D ``numpy.ndarray``, default ``None``
Vector of prior probabilities of each policy (what's referred to in the active inference literature as "habits"). If ``None``, this defaults to a flat (uninformative) prior over policies.
gamma: ``float``, default 16.0
Prior precision over policies, scales the contribution of the expected free energy to the posterior over policies
Returns
----------
q_pi: 1D ``numpy.ndarray``
Posterior beliefs over policies, i.e. a vector containing one posterior probability per policy.
G: 1D ``numpy.ndarray``
Negative expected free energies of each policy, i.e. a vector containing one negative expected free energy per policy.
"""
num_obs, num_states, num_modalities, num_factors = utils.get_model_dimensions(A, B)
horizon = len(qs_seq_pi[0])
num_policies = len(qs_seq_pi)
qo_seq = utils.obj_array(horizon)
for t in range(horizon):
qo_seq[t] = utils.obj_array_zeros(num_obs)
# initialise expected observations
qo_seq_pi = utils.obj_array(num_policies)
# initialize (negative) expected free energies for all policies
G = np.zeros(num_policies)
G1 = np.zeros(num_policies)
G2 = np.zeros(num_policies)
G3 = np.zeros(num_policies)
if F is None:
F = spm_log_single(np.ones(num_policies) / num_policies)
if E is None:
lnE = spm_log_single(np.ones(num_policies) / num_policies)
else:
lnE = spm_log_single(E)
for p_idx, policy in enumerate(policies):
qo_seq_pi[p_idx] = get_expected_obs(qs_seq_pi[p_idx], A)
if use_utility:
G1[p_idx] += calc_expected_utility(qo_seq_pi[p_idx], C)
G[p_idx] += G1[p_idx]
if use_states_info_gain:
G2[p_idx] += calc_states_info_gain(A, qs_seq_pi[p_idx])
G[p_idx] += G2[p_idx]
if use_param_info_gain:
if pA is not None:
G3[p_idx] += calc_pA_info_gain(pA, qo_seq_pi[p_idx], qs_seq_pi[p_idx])
G[p_idx] += G3[p_idx]
if pB is not None:
G3[p_idx] += calc_pB_info_gain(pB, qs_seq_pi[p_idx], prior, policy)
G[p_idx] += G3[p_idx]
q_pi = softmax(G * gamma - F + lnE)
return q_pi, G, G1, G2, G3
def update_posterior_policies(
qs,
A,
B,
C,
policies,
use_utility=True,
use_states_info_gain=True,
use_param_info_gain=False,
pA=None,
pB=None,
E = None,
gamma=16.0
):
"""
Update posterior beliefs about policies by computing expected free energy of each policy and integrating that
with the prior over policies ``E``. This is intended to be used in conjunction
with the ``update_posterior_states`` method of the ``inference`` module, since only the posterior about the hidden states at the current timestep
``qs`` is assumed to be provided, unconditional on policies. The predictive posterior over hidden states under all policies Q(s, pi) is computed
using the starting posterior about states at the current timestep ``qs`` and the generative model (e.g. ``A``, ``B``, ``C``)
Parameters
----------
qs: ``numpy.ndarray`` of dtype object
Marginal posterior beliefs over hidden states at current timepoint (unconditioned on policies)
A: ``numpy.ndarray`` of dtype object
Sensory likelihood mapping or 'observation model', mapping from hidden states to observations. Each element ``A[m]`` of
stores an ``numpy.ndarray`` multidimensional array for observation modality ``m``, whose entries ``A[m][i, j, k, ...]`` store
the probability of observation level ``i`` given hidden state levels ``j, k, ...``
B: ``numpy.ndarray`` of dtype object
Dynamics likelihood mapping or 'transition model', mapping from hidden states at ``t`` to hidden states at ``t+1``, given some control state ``u``.
Each element ``B[f]`` of this object array stores a 3-D tensor for hidden state factor ``f``, whose entries ``B[f][s, v, u]`` store the probability
of hidden state level ``s`` at the current time, given hidden state level ``v`` and action ``u`` at the previous time.
C: ``numpy.ndarray`` of dtype object
Prior over observations or 'prior preferences', storing the "value" of each outcome in terms of relative log probabilities.
This is softmaxed to form a proper probability distribution before being used to compute the expected utility term of the expected free energy.
policies: ``list`` of 2D ``numpy.ndarray``
``list`` that stores each policy in ``policies[p_idx]``. Shape of ``policies[p_idx]`` is ``(num_timesteps, num_factors)`` where `num_timesteps` is the temporal
depth of the policy and ``num_factors`` is the number of control factors.
use_utility: ``Bool``, default ``True``
Boolean flag that determines whether expected utility should be incorporated into computation of EFE.
use_states_info_gain: ``Bool``, default ``True``
Boolean flag that determines whether state epistemic value (info gain about hidden states) should be incorporated into computation of EFE.
use_param_info_gain: ``Bool``, default ``False``
Boolean flag that determines whether parameter epistemic value (info gain about generative model parameters) should be incorporated into computation of EFE.
pA: ``numpy.ndarray`` of dtype object, optional
Dirichlet parameters over observation model (same shape as ``A``)
pB: ``numpy.ndarray`` of dtype object, optional
Dirichlet parameters over transition model (same shape as ``B``)
E: 1D ``numpy.ndarray``, optional
Vector of prior probabilities of each policy (what's referred to in the active inference literature as "habits")
gamma: float, default 16.0
Prior precision over policies, scales the contribution of the expected free energy to the posterior over policies
Returns
----------
q_pi: 1D ``numpy.ndarray``
Posterior beliefs over policies, i.e. a vector containing one posterior probability per policy.
G: 1D ``numpy.ndarray``
Negative expected free energies of each policy, i.e. a vector containing one negative expected free energy per policy.
"""
n_policies = len(policies)
G = np.zeros(n_policies)
G1 = np.zeros(n_policies)
G2 = np.zeros(n_policies)
G3 = np.zeros(n_policies)
q_pi = np.zeros((n_policies, 1))
if E is None:
lnE = spm_log_single(np.ones(n_policies) / n_policies)
else:
lnE = spm_log_single(E)
for idx, policy in enumerate(policies):
qs_pi = get_expected_states(qs, B, policy)
qo_pi = get_expected_obs(qs_pi, A)
if use_utility:
exp_ut = calc_expected_utility(qo_pi, C)
G[idx] += exp_ut
G1[idx] += exp_ut
if use_states_info_gain:
exp_sig = calc_states_info_gain(A, qs_pi)
G[idx] += exp_sig
G2[idx] += exp_sig
if use_param_info_gain:
if pA is not None:
exp_aig = calc_pA_info_gain(pA, qo_pi, qs_pi)
G[idx] += exp_aig
G3[idx] += exp_aig
if pB is not None:
exp_big = calc_pB_info_gain(pB, qs_pi, qs, policy)
G[idx] += exp_big
G3[idx] += exp_big
q_pi = softmax(G * gamma + lnE)
return q_pi, G, G1, G2, G3
def update_posterior_policies_factorized(
qs,
A,
B,
C,
A_factor_list,
B_factor_list,
policies,
use_utility=True,
use_states_info_gain=True,
use_param_info_gain=False,
pA=None,
pB=None,
E = None,
gamma=16.0
):
"""
Update posterior beliefs about policies by computing expected free energy of each policy and integrating that
with the prior over policies ``E``. This is intended to be used in conjunction
with the ``update_posterior_states`` method of the ``inference`` module, since only the posterior about the hidden states at the current timestep
``qs`` is assumed to be provided, unconditional on policies. The predictive posterior over hidden states under all policies Q(s, pi) is computed
using the starting posterior about states at the current timestep ``qs`` and the generative model (e.g. ``A``, ``B``, ``C``)
Parameters
----------
qs: ``numpy.ndarray`` of dtype object
Marginal posterior beliefs over hidden states at current timepoint (unconditioned on policies)
A: ``numpy.ndarray`` of dtype object
Sensory likelihood mapping or 'observation model', mapping from hidden states to observations. Each element ``A[m]`` of
stores an ``numpy.ndarray`` multidimensional array for observation modality ``m``, whose entries ``A[m][i, j, k, ...]`` store
the probability of observation level ``i`` given hidden state levels ``j, k, ...``
B: ``numpy.ndarray`` of dtype object
Dynamics likelihood mapping or 'transition model', mapping from hidden states at ``t`` to hidden states at ``t+1``, given some control state ``u``.
Each element ``B[f]`` of this object array stores a 3-D tensor for hidden state factor ``f``, whose entries ``B[f][s, v, u]`` store the probability
of hidden state level ``s`` at the current time, given hidden state level ``v`` and action ``u`` at the previous time.
C: ``numpy.ndarray`` of dtype object
Prior over observations or 'prior preferences', storing the "value" of each outcome in terms of relative log probabilities.
This is softmaxed to form a proper probability distribution before being used to compute the expected utility term of the expected free energy.
A_factor_list: ``list`` of ``list``s of ``int``
``list`` that stores the indices of the hidden state factor indices that each observation modality depends on. For example, if ``A_factor_list[m] = [0, 1]``, then
observation modality ``m`` depends on hidden state factors 0 and 1.
B_factor_list: ``list`` of ``list``s of ``int``
``list`` that stores the indices of the hidden state factor indices that each hidden state factor depends on. For example, if ``B_factor_list[f] = [0, 1]``, then
the transitions in hidden state factor ``f`` depend on hidden state factors 0 and 1.
policies: ``list`` of 2D ``numpy.ndarray``
``list`` that stores each policy in ``policies[p_idx]``. Shape of ``policies[p_idx]`` is ``(num_timesteps, num_factors)`` where `num_timesteps` is the temporal
depth of the policy and ``num_factors`` is the number of control factors.
use_utility: ``Bool``, default ``True``
Boolean flag that determines whether expected utility should be incorporated into computation of EFE.
use_states_info_gain: ``Bool``, default ``True``
Boolean flag that determines whether state epistemic value (info gain about hidden states) should be incorporated into computation of EFE.
use_param_info_gain: ``Bool``, default ``False``
Boolean flag that determines whether parameter epistemic value (info gain about generative model parameters) should be incorporated into computation of EFE.
pA: ``numpy.ndarray`` of dtype object, optional
Dirichlet parameters over observation model (same shape as ``A``)
pB: ``numpy.ndarray`` of dtype object, optional
Dirichlet parameters over transition model (same shape as ``B``)
E: 1D ``numpy.ndarray``, optional
Vector of prior probabilities of each policy (what's referred to in the active inference literature as "habits")
gamma: float, default 16.0
Prior precision over policies, scales the contribution of the expected free energy to the posterior over policies
Returns
----------
q_pi: 1D ``numpy.ndarray``
Posterior beliefs over policies, i.e. a vector containing one posterior probability per policy.
G: 1D ``numpy.ndarray``
Negative expected free energies of each policy, i.e. a vector containing one negative expected free energy per policy.
"""
n_policies = len(policies)
G = np.zeros(n_policies)
q_pi = np.zeros((n_policies, 1))
if E is None:
lnE = spm_log_single(np.ones(n_policies) / n_policies)
else:
lnE = spm_log_single(E)
for idx, policy in enumerate(policies):
qs_pi = get_expected_states_interactions(qs, B, B_factor_list, policy)
qo_pi = get_expected_obs_factorized(qs_pi, A, A_factor_list)
if use_utility:
G[idx] += calc_expected_utility(qo_pi, C)
if use_states_info_gain:
G[idx] += calc_states_info_gain_factorized(A, qs_pi, A_factor_list)
if use_param_info_gain:
if pA is not None:
G[idx] += calc_pA_info_gain_factorized(pA, qo_pi, qs_pi, A_factor_list)
if pB is not None:
G[idx] += calc_pB_info_gain_interactions(pB, qs_pi, qs, B_factor_list, policy)
q_pi = softmax(G * gamma + lnE)
return q_pi, G
def update_posterior_policies_factorized_expand_G(
qs,
A,
B,
C,
A_factor_list,
B_factor_list,
policies,
use_utility=True,
use_states_info_gain=True,
use_param_info_gain=False,
pA=None,
pB=None,
E = None,
gamma=16.0,
print_util = False
):
"""
Update posterior beliefs about policies by computing expected free energy of each policy and integrating that
with the prior over policies ``E``. This is intended to be used in conjunction
with the ``update_posterior_states`` method of the ``inference`` module, since only the posterior about the hidden states at the current timestep
``qs`` is assumed to be provided, unconditional on policies. The predictive posterior over hidden states under all policies Q(s, pi) is computed
using the starting posterior about states at the current timestep ``qs`` and the generative model (e.g. ``A``, ``B``, ``C``)
Parameters
----------
qs: ``numpy.ndarray`` of dtype object
Marginal posterior beliefs over hidden states at current timepoint (unconditioned on policies)
A: ``numpy.ndarray`` of dtype object
Sensory likelihood mapping or 'observation model', mapping from hidden states to observations. Each element ``A[m]`` of
stores an ``numpy.ndarray`` multidimensional array for observation modality ``m``, whose entries ``A[m][i, j, k, ...]`` store
the probability of observation level ``i`` given hidden state levels ``j, k, ...``
B: ``numpy.ndarray`` of dtype object
Dynamics likelihood mapping or 'transition model', mapping from hidden states at ``t`` to hidden states at ``t+1``, given some control state ``u``.
Each element ``B[f]`` of this object array stores a 3-D tensor for hidden state factor ``f``, whose entries ``B[f][s, v, u]`` store the probability
of hidden state level ``s`` at the current time, given hidden state level ``v`` and action ``u`` at the previous time.
C: ``numpy.ndarray`` of dtype object
Prior over observations or 'prior preferences', storing the "value" of each outcome in terms of relative log probabilities.
This is softmaxed to form a proper probability distribution before being used to compute the expected utility term of the expected free energy.
A_factor_list: ``list`` of ``list``s of ``int``
``list`` that stores the indices of the hidden state factor indices that each observation modality depends on. For example, if ``A_factor_list[m] = [0, 1]``, then
observation modality ``m`` depends on hidden state factors 0 and 1.
B_factor_list: ``list`` of ``list``s of ``int``
``list`` that stores the indices of the hidden state factor indices that each hidden state factor depends on. For example, if ``B_factor_list[f] = [0, 1]``, then
the transitions in hidden state factor ``f`` depend on hidden state factors 0 and 1.
policies: ``list`` of 2D ``numpy.ndarray``
``list`` that stores each policy in ``policies[p_idx]``. Shape of ``policies[p_idx]`` is ``(num_timesteps, num_factors)`` where `num_timesteps` is the temporal
depth of the policy and ``num_factors`` is the number of control factors.
use_utility: ``Bool``, default ``True``
Boolean flag that determines whether expected utility should be incorporated into computation of EFE.
use_states_info_gain: ``Bool``, default ``True``
Boolean flag that determines whether state epistemic value (info gain about hidden states) should be incorporated into computation of EFE.
use_param_info_gain: ``Bool``, default ``False``
Boolean flag that determines whether parameter epistemic value (info gain about generative model parameters) should be incorporated into computation of EFE.
pA: ``numpy.ndarray`` of dtype object, optional
Dirichlet parameters over observation model (same shape as ``A``)
pB: ``numpy.ndarray`` of dtype object, optional
Dirichlet parameters over transition model (same shape as ``B``)
E: 1D ``numpy.ndarray``, optional
Vector of prior probabilities of each policy (what's referred to in the active inference literature as "habits")
gamma: float, default 16.0
Prior precision over policies, scales the contribution of the expected free energy to the posterior over policies
Returns
----------
q_pi: 1D ``numpy.ndarray``
Posterior beliefs over policies, i.e. a vector containing one posterior probability per policy.
G: 1D ``numpy.ndarray``
Negative expected free energies of each policy, i.e. a vector containing one negative expected free energy per policy.
"""
n_policies = len(policies)
G = np.zeros(n_policies)
G1 = np.zeros(n_policies)
G2 = np.zeros(n_policies)
G3 = np.zeros(n_policies)
q_pi = np.zeros((n_policies, 1))
if E is None:
lnE = spm_log_single(np.ones(n_policies) / n_policies)
else:
lnE = spm_log_single(E)
for idx, policy in enumerate(policies):
qs_pi = get_expected_states_interactions(qs, B, B_factor_list, policy)
qo_pi = get_expected_obs_factorized(qs_pi, A, A_factor_list)
if use_utility:
exp_ut = calc_expected_utility(qo_pi, C)
G[idx] += exp_ut
G1[idx] += exp_ut
if use_states_info_gain:
exp_sig = calc_states_info_gain_factorized(A, qs_pi, A_factor_list)
G[idx] += exp_sig
G2[idx] += exp_sig
if use_param_info_gain:
if pA is not None:
exp_aig = calc_pA_info_gain_factorized(pA, qo_pi, qs_pi, A_factor_list)
G[idx] += exp_aig
G3[idx] += exp_aig
if pB is not None:
exp_big = calc_pB_info_gain_interactions(pB, qs_pi, qs, B_factor_list, policy)
G[idx] += exp_big
G3[idx] += exp_big
q_pi = softmax(G * gamma + lnE)
return q_pi, G,G1,G2,G3
def get_expected_states(qs, B, policy):
"""
Compute the expected states under a policy, also known as the posterior predictive density over states
Parameters
----------
qs: ``numpy.ndarray`` of dtype object
Marginal posterior beliefs over hidden states at a given timepoint.
B: ``numpy.ndarray`` of dtype object
Dynamics likelihood mapping or 'transition model', mapping from hidden states at ``t`` to hidden states at ``t+1``, given some control state ``u``.
Each element ``B[f]`` of this object array stores a 3-D tensor for hidden state factor ``f``, whose entries ``B[f][s, v, u]`` store the probability
of hidden state level ``s`` at the current time, given hidden state level ``v`` and action ``u`` at the previous time.
policy: 2D ``numpy.ndarray``
Array that stores actions entailed by a policy over time. Shape is ``(num_timesteps, num_factors)`` where ``num_timesteps`` is the temporal
depth of the policy and ``num_factors`` is the number of control factors.
Returns
-------
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
"""
n_steps = policy.shape[0]
n_factors = policy.shape[1]
# initialise posterior predictive density as a list of beliefs over time, including current posterior beliefs about hidden states as the first element
qs_pi = [qs] + [utils.obj_array(n_factors) for t in range(n_steps)]
# get expected states over time
for t in range(n_steps):
for control_factor, action in enumerate(policy[t,:]):
qs_pi[t+1][control_factor] = B[control_factor][:,:,int(action)].dot(qs_pi[t][control_factor])
return qs_pi[1:]
def get_expected_states_interactions(qs, B, B_factor_list, policy):
"""
Compute the expected states under a policy, also known as the posterior predictive density over states
Parameters
----------
qs: ``numpy.ndarray`` of dtype object
Marginal posterior beliefs over hidden states at a given timepoint.
B: ``numpy.ndarray`` of dtype object
Dynamics likelihood mapping or 'transition model', mapping from hidden states at ``t`` to hidden states at ``t+1``, given some control state ``u``.
Each element ``B[f]`` of this object array stores a 3-D tensor for hidden state factor ``f``, whose entries ``B[f][s, v, u]`` store the probability
of hidden state level ``s`` at the current time, given hidden state level ``v`` and action ``u`` at the previous time.
B_factor_list: ``list`` of ``list`` of ``int``
List of lists of hidden state factors each hidden state factor depends on. Each element ``B_factor_list[i]`` is a list of the factor indices that factor i's dynamics depend on.
policy: 2D ``numpy.ndarray``
Array that stores actions entailed by a policy over time. Shape is ``(num_timesteps, num_factors)`` where ``num_timesteps`` is the temporal
depth of the policy and ``num_factors`` is the number of control factors.
Returns
-------
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
"""
n_steps = policy.shape[0]
n_factors = policy.shape[1]
# initialise posterior predictive density as a list of beliefs over time, including current posterior beliefs about hidden states as the first element
qs_pi = [qs] + [utils.obj_array(n_factors) for t in range(n_steps)]
# get expected states over time
for t in range(n_steps):
for control_factor, action in enumerate(policy[t,:]):
factor_idx = B_factor_list[control_factor] # list of the hidden state factor indices that the dynamics of `qs[control_factor]` depend on
qs_pi[t+1][control_factor] = spm_dot(B[control_factor][...,int(action)], qs_pi[t][factor_idx])
return qs_pi[1:]
def get_expected_obs(qs_pi, A):
"""
Compute the expected observations under a policy, also known as the posterior predictive density over observations
Parameters
----------
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
A: ``numpy.ndarray`` of dtype object
Sensory likelihood mapping or 'observation model', mapping from hidden states to observations. Each element ``A[m]`` of
stores an ``numpy.ndarray`` multidimensional array for observation modality ``m``, whose entries ``A[m][i, j, k, ...]`` store
the probability of observation level ``i`` given hidden state levels ``j, k, ...``
Returns
-------
qo_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over observations expected under the policy, where ``qo_pi[t]`` stores the beliefs about
observations expected under the policy at time ``t``
"""
n_steps = len(qs_pi) # each element of the list is the PPD at a different timestep
# initialise expected observations
qo_pi = []
for t in range(n_steps):
qo_pi_t = utils.obj_array(len(A))
qo_pi.append(qo_pi_t)
# compute expected observations over time
for t in range(n_steps):
for modality, A_m in enumerate(A):
qo_pi[t][modality] = spm_dot(A_m, qs_pi[t])
return qo_pi
def get_expected_obs_factorized(qs_pi, A, A_factor_list):
"""
Compute the expected observations under a policy, also known as the posterior predictive density over observations
Parameters
----------
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
A: ``numpy.ndarray`` of dtype object
Sensory likelihood mapping or 'observation model', mapping from hidden states to observations. Each element ``A[m]`` of
stores an ``numpy.ndarray`` multidimensional array for observation modality ``m``, whose entries ``A[m][i, j, k, ...]`` store
the probability of observation level ``i`` given hidden state levels ``j, k, ...``
A_factor_list: ``list`` of ``list`` of ``int``
List of lists of hidden state factor indices that each observation modality depends on. Each element ``A_factor_list[i]`` is a list of the factor indices that modality i's observation model depends on.
Returns
-------
qo_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over observations expected under the policy, where ``qo_pi[t]`` stores the beliefs about
observations expected under the policy at time ``t``
"""
n_steps = len(qs_pi) # each element of the list is the PPD at a different timestep
# initialise expected observations
qo_pi = []
for t in range(n_steps):
qo_pi_t = utils.obj_array(len(A))
qo_pi.append(qo_pi_t)
# compute expected observations over time
for t in range(n_steps):
for modality, A_m in enumerate(A):
factor_idx = A_factor_list[modality] # list of the hidden state factor indices that observation modality with the index `modality` depends on
qo_pi[t][modality] = spm_dot(A_m, qs_pi[t][factor_idx])
return qo_pi
def calc_expected_utility(qo_pi, C):
"""
Computes the expected utility of a policy, using the observation distribution expected under that policy and a prior preference vector.
Parameters
----------
qo_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over observations expected under the policy, where ``qo_pi[t]`` stores the beliefs about
observations expected under the policy at time ``t``
C: ``numpy.ndarray`` of dtype object
Prior over observations or 'prior preferences', storing the "value" of each outcome in terms of relative log probabilities.
This is softmaxed to form a proper probability distribution before being used to compute the expected utility.
Returns
-------
expected_util: float
Utility (reward) expected under the policy in question
"""
n_steps = len(qo_pi)
# initialise expected utility
expected_util = 0
# loop over time points and modalities
num_modalities = len(C)
# reformat C to be tiled across timesteps, if it's not already
modalities_to_tile = [modality_i for modality_i in range(num_modalities) if C[modality_i].ndim == 1]
# make a deepcopy of C where it has been tiled across timesteps
C_tiled = copy.deepcopy(C)
for modality in modalities_to_tile:
C_tiled[modality] = np.tile(C[modality][:,None], (1, n_steps) )
C_prob = softmax_obj_arr(C_tiled) # convert relative log probabilities into proper probability distribution
for t in range(n_steps):
for modality in range(num_modalities):
lnC = spm_log_single(C_prob[modality][:, t])
expected_util += qo_pi[t][modality].dot(lnC)
return expected_util
def calc_expected_utility_explicit(qo_pi, C):
"""
Computes the expected utility of a policy, using the observation distribution expected under that policy and a prior preference vector.
Parameters
----------
qo_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over observations expected under the policy, where ``qo_pi[t]`` stores the beliefs about
observations expected under the policy at time ``t``
C: ``numpy.ndarray`` of dtype object
Prior over observations or 'prior preferences', storing the "value" of each outcome in terms of relative log probabilities.
This is softmaxed to form a proper probability distribution before being used to compute the expected utility.
Returns
-------
expected_util: float
Utility (reward) expected under the policy in question
"""
n_steps = len(qo_pi)
# initialise expected utility
expected_util = 0
# loop over time points and modalities
num_modalities = len(C)
# reformat C to be tiled across timesteps, if it's not already
modalities_to_tile = [modality_i for modality_i in range(num_modalities) if C[modality_i].ndim == 1]
# make a deepcopy of C where it has been tiled across timesteps
C_tiled = copy.deepcopy(C)
for modality in modalities_to_tile:
C_tiled[modality] = np.tile(C[modality][:,None], (1, n_steps) )
C_prob = softmax_obj_arr(C_tiled) # convert relative log probabilities into proper probability distribution
util_dict = {}
for t in range(n_steps):
action_list = []
for modality in range(num_modalities):
lnC = spm_log_single(C_prob[modality][:, t])
expected_util += qo_pi[t][modality].dot(lnC)
if modality == 2:
action_list.append(qo_pi[t][modality].dot(lnC))
util_dict[t] = action_list
print(util_dict)
#print(f"M{modality}: expected observation for acion {t}: {qo_pi[t][modality]}: {qo_pi[t][modality].dot(lnC)}")
return expected_util
def calc_states_info_gain(A, qs_pi):
"""
Computes the Bayesian surprise or information gain about states of a policy,
using the observation model and the hidden state distribution expected under that policy.
Parameters
----------
A: ``numpy.ndarray`` of dtype object
Sensory likelihood mapping or 'observation model', mapping from hidden states to observations. Each element ``A[m]`` of
stores an ``numpy.ndarray`` multidimensional array for observation modality ``m``, whose entries ``A[m][i, j, k, ...]`` store
the probability of observation level ``i`` given hidden state levels ``j, k, ...``
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
Returns
-------
states_surprise: float
Bayesian surprise (about states) or salience expected under the policy in question
"""
n_steps = len(qs_pi)
states_surprise = 0
for t in range(n_steps):
states_surprise += spm_MDP_G(A, qs_pi[t])
return states_surprise
def calc_states_info_gain_factorized(A, qs_pi, A_factor_list):
"""
Computes the Bayesian surprise or information gain about states of a policy,
using the observation model and the hidden state distribution expected under that policy.
Parameters
----------
A: ``numpy.ndarray`` of dtype object
Sensory likelihood mapping or 'observation model', mapping from hidden states to observations. Each element ``A[m]`` of
stores an ``numpy.ndarray`` multidimensional array for observation modality ``m``, whose entries ``A[m][i, j, k, ...]`` store
the probability of observation level ``i`` given hidden state levels ``j, k, ...``
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
A_factor_list: ``list`` of ``list`` of ``int``
List of lists, where ``A_factor_list[m]`` is a list of the hidden state factor indices that observation modality with the index ``m`` depends on
Returns
-------
states_surprise: float
Bayesian surprise (about states) or salience expected under the policy in question
"""
n_steps = len(qs_pi)
states_surprise = 0
for t in range(n_steps):
for m, A_m in enumerate(A):
factor_idx = A_factor_list[m] # list of the hidden state factor indices that observation modality with the index `m` depends on
states_surprise += spm_MDP_G(A_m, qs_pi[t][factor_idx])
return states_surprise
def calc_states_info_gain_factorized_explicit(A, qs_pi, A_factor_list):
"""
Computes the Bayesian surprise or information gain about states of a policy,
using the observation model and the hidden state distribution expected under that policy.
Parameters
----------
A: ``numpy.ndarray`` of dtype object
Sensory likelihood mapping or 'observation model', mapping from hidden states to observations. Each element ``A[m]`` of
stores an ``numpy.ndarray`` multidimensional array for observation modality ``m``, whose entries ``A[m][i, j, k, ...]`` store
the probability of observation level ``i`` given hidden state levels ``j, k, ...``
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
A_factor_list: ``list`` of ``list`` of ``int``
List of lists, where ``A_factor_list[m]`` is a list of the hidden state factor indices that observation modality with the index ``m`` depends on
Returns
-------
states_surprise: float
Bayesian surprise (about states) or salience expected under the policy in question
"""
n_steps = len(qs_pi)
info_gain_dict = {}
states_surprise = 0
for t in range(n_steps):
action_list = []
for m, A_m in enumerate(A):
factor_idx = A_factor_list[m] # list of the hidden state factor indices that observation modality with the index `m` depends on
states_surprise += spm_MDP_G(A_m, qs_pi[t][factor_idx])
#print(f'action{t}, M{m} = {spm_MDP_G(A_m, qs_pi[t][factor_idx])}')
action_list.append(spm_MDP_G(A_m, qs_pi[t][factor_idx]))
info_gain_dict[t] = action_list
print(info_gain_dict)
return states_surprise
def calc_pA_info_gain(pA, qo_pi, qs_pi):
"""
Compute expected Dirichlet information gain about parameters ``pA`` under a policy
Parameters
----------
pA: ``numpy.ndarray`` of dtype object
Dirichlet parameters over observation model (same shape as ``A``)
qo_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over observations expected under the policy, where ``qo_pi[t]`` stores the beliefs about
observations expected under the policy at time ``t``
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
Returns
-------
infogain_pA: float
Surprise (about Dirichlet parameters) expected under the policy in question
"""
n_steps = len(qo_pi)
num_modalities = len(pA)
wA = utils.obj_array(num_modalities)
for modality, pA_m in enumerate(pA):
wA[modality] = spm_wnorm(pA[modality])
pA_infogain = 0
for modality in range(num_modalities):
wA_modality = wA[modality] * (pA[modality] > 0).astype("float")
for t in range(n_steps):
pA_infogain -= qo_pi[t][modality].dot(spm_dot(wA_modality, qs_pi[t])[:, np.newaxis])
return pA_infogain
def calc_pA_info_gain_factorized(pA, qo_pi, qs_pi, A_factor_list):
"""
Compute expected Dirichlet information gain about parameters ``pA`` under a policy.
In this version of the function, we assume that the observation model is factorized, i.e. that each observation modality depends on a subset of the hidden state factors.
Parameters
----------
pA: ``numpy.ndarray`` of dtype object
Dirichlet parameters over observation model (same shape as ``A``)
qo_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over observations expected under the policy, where ``qo_pi[t]`` stores the beliefs about
observations expected under the policy at time ``t``
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
A_factor_list: ``list`` of ``list`` of ``int``
List of lists, where ``A_factor_list[m]`` is a list of the hidden state factor indices that observation modality with the index ``m`` depends on
Returns
-------
infogain_pA: float
Surprise (about Dirichlet parameters) expected under the policy in question
"""
n_steps = len(qo_pi)
num_modalities = len(pA)
wA = utils.obj_array(num_modalities)
for modality, pA_m in enumerate(pA):
wA[modality] = spm_wnorm(pA[modality])
pA_infogain = 0
for modality in range(num_modalities):
wA_modality = wA[modality] * (pA[modality] > 0).astype("float")
factor_idx = A_factor_list[modality]
for t in range(n_steps):
pA_infogain -= qo_pi[t][modality].dot(spm_dot(wA_modality, qs_pi[t][factor_idx])[:, np.newaxis])
return pA_infogain
def calc_pB_info_gain(pB, qs_pi, qs_prev, policy):
"""
Compute expected Dirichlet information gain about parameters ``pB`` under a given policy
Parameters
----------
pB: ``numpy.ndarray`` of dtype object
Dirichlet parameters over transition model (same shape as ``B``)
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
qs_prev: ``numpy.ndarray`` of dtype object
Posterior over hidden states at beginning of trajectory (before receiving observations)
policy: 2D ``numpy.ndarray``
Array that stores actions entailed by a policy over time. Shape is ``(num_timesteps, num_factors)`` where ``num_timesteps`` is the temporal
depth of the policy and ``num_factors`` is the number of control factors.
Returns
-------
infogain_pB: float
Surprise (about dirichlet parameters) expected under the policy in question
"""
n_steps = len(qs_pi)
num_factors = len(pB)
wB = utils.obj_array(num_factors)
for factor, pB_f in enumerate(pB):
wB[factor] = spm_wnorm(pB_f)
pB_infogain = 0
for t in range(n_steps):
# the 'past posterior' used for the information gain about pB here is the posterior
# over expected states at the timestep previous to the one under consideration
# if we're on the first timestep, we just use the latest posterior in the
# entire action-perception cycle as the previous posterior
if t == 0:
previous_qs = qs_prev
# otherwise, we use the expected states for the timestep previous to the timestep under consideration
else:
previous_qs = qs_pi[t - 1]
# get the list of action-indices for the current timestep
policy_t = policy[t, :]
for factor, a_i in enumerate(policy_t):
wB_factor_t = wB[factor][:, :, int(a_i)] * (pB[factor][:, :, int(a_i)] > 0).astype("float")
pB_infogain -= qs_pi[t][factor].dot(wB_factor_t.dot(previous_qs[factor]))
return pB_infogain
def calc_pB_info_gain_interactions(pB, qs_pi, qs_prev, B_factor_list, policy):
"""
Compute expected Dirichlet information gain about parameters ``pB`` under a given policy
Parameters
----------
pB: ``numpy.ndarray`` of dtype object
Dirichlet parameters over transition model (same shape as ``B``)
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
qs_prev: ``numpy.ndarray`` of dtype object
Posterior over hidden states at beginning of trajectory (before receiving observations)
B_factor_list: ``list`` of ``list`` of ``int``
List of lists, where ``B_factor_list[f]`` is a list of the hidden state factor indices that hidden state factor with the index ``f`` depends on
policy: 2D ``numpy.ndarray``
Array that stores actions entailed by a policy over time. Shape is ``(num_timesteps, num_factors)`` where ``num_timesteps`` is the temporal
depth of the policy and ``num_factors`` is the number of control factors.
Returns
-------
infogain_pB: float
Surprise (about dirichlet parameters) expected under the policy in question
"""
n_steps = len(qs_pi)
num_factors = len(pB)
wB = utils.obj_array(num_factors)
for factor, pB_f in enumerate(pB):
wB[factor] = spm_wnorm(pB_f)
pB_infogain = 0
for t in range(n_steps):
# the 'past posterior' used for the information gain about pB here is the posterior
# over expected states at the timestep previous to the one under consideration
# if we're on the first timestep, we just use the latest posterior in the
# entire action-perception cycle as the previous posterior
if t == 0:
previous_qs = qs_prev
# otherwise, we use the expected states for the timestep previous to the timestep under consideration
else:
previous_qs = qs_pi[t - 1]
# get the list of action-indices for the current timestep
policy_t = policy[t, :]
for factor, a_i in enumerate(policy_t):
wB_factor_t = wB[factor][...,int(a_i)] * (pB[factor][...,int(a_i)] > 0).astype("float")
f_idx = B_factor_list[factor]
pB_infogain -= qs_pi[t][factor].dot(spm_dot(wB_factor_t, previous_qs[f_idx]))
return pB_infogain
def calc_pB_info_gain_interactions_explicit(pB, qs_pi, qs_prev, B_factor_list, policy):
"""
Compute expected Dirichlet information gain about parameters ``pB`` under a given policy
Parameters
----------
pB: ``numpy.ndarray`` of dtype object
Dirichlet parameters over transition model (same shape as ``B``)
qs_pi: ``list`` of ``numpy.ndarray`` of dtype object
Predictive posterior beliefs over hidden states expected under the policy, where ``qs_pi[t]`` stores the beliefs about
hidden states expected under the policy at time ``t``
qs_prev: ``numpy.ndarray`` of dtype object
Posterior over hidden states at beginning of trajectory (before receiving observations)
B_factor_list: ``list`` of ``list`` of ``int``
List of lists, where ``B_factor_list[f]`` is a list of the hidden state factor indices that hidden state factor with the index ``f`` depends on
policy: 2D ``numpy.ndarray``
Array that stores actions entailed by a policy over time. Shape is ``(num_timesteps, num_factors)`` where ``num_timesteps`` is the temporal
depth of the policy and ``num_factors`` is the number of control factors.
Returns
-------
infogain_pB: float
Surprise (about dirichlet parameters) expected under the policy in question
"""