File: gaussian_markov_chain.py

package info (click to toggle)
python-bayespy 0.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,132 kB
  • sloc: python: 22,402; makefile: 156
file content (2098 lines) | stat: -rw-r--r-- 73,623 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
################################################################################
# Copyright (C) 2012-2014 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################


"""
This module contains VMP nodes for Gaussian Markov chains.
"""

import numpy as np
import scipy

from bayespy.utils import misc
from bayespy.utils import linalg

from .node import Node, message_sum_multiply
from .deterministic import Deterministic
from .expfamily import ExponentialFamily
from .expfamily import ExponentialFamilyDistribution
from .expfamily import useconstructor
from .gaussian import (Gaussian,
                       GaussianMoments,
                       GaussianWishartMoments,
                       GaussianGammaMoments,
                       WrapToGaussianGamma,
                       WrapToGaussianWishart)
from .wishart import Wishart, WishartMoments
from .gamma import Gamma, GammaMoments
from .categorical import CategoricalMoments
from .node import Moments, ensureparents


class GaussianMarkovChainMoments(Moments):


    def __init__(self, N, D):
        self.N = N
        self.D = D
        return super().__init__()


    def compute_fixed_moments(self, x):
        u0 = x
        u1 = x[...,:,np.newaxis] * x[...,np.newaxis,:]
        u2 = x[...,:-1,:,np.newaxis] * x[...,1:,np.newaxis,:]
        return [u0, u1, u2]


    def rotate(self, u, R, logdet=None):

        if logdet is None:
            logdet = np.linalg.slogdet(R)[1]

        N = np.shape(u[0])[-2]

        # Transform moments and g
        u0 = linalg.mvdot(R, u[0])
        u1 = linalg.dot(R, u[1], R.T)
        u2 = linalg.dot(R, u[2], R.T)
        u = [u0, u1, u2]
        dg = -N * logdet

        return (u, dg)


class TemplateGaussianMarkovChainDistribution(ExponentialFamilyDistribution):
    """
    Sub-classes implement distribution specific computations.
    """


    def __init__(self, N, D):
        self.N = N
        self.D = D
        self.moments = GaussianMarkovChainMoments(N, D)
        super().__init__()

    def compute_message_to_parent(self, parent, index, u_self, *u_parents):
        raise NotImplementedError()

    def compute_weights_to_parent(self, index, weights):
        raise NotImplementedError()

    def compute_phi_from_parents(self, *u_parents, mask=True):
        raise NotImplementedError()

    def compute_moments_and_cgf(self, phi, mask=True):
        """
        Compute the moments and the cumulant-generating function.

        This basically performs the filtering and smoothing for the variable.

        Parameters
        ----------
        phi

        Returns
        -------
        u
        g
        """

        # Solve the Kalman filtering and smoothing problem
        y = phi[0]
        A = -2*phi[1]
        # Don't multiply phi[2] by two because it is a sum of the super- and
        # sub-diagonal blocks so we would need to divide by two anyway.
        B = -phi[2]

        (CovXnXn, CovXpXn, Xn, ldet) = linalg.block_banded_solve(A, B, y)

        # Compute moments
        u0 = Xn
        u1 = CovXnXn + Xn[...,:,np.newaxis] * Xn[...,np.newaxis,:]
        u2 = CovXpXn + Xn[...,:-1,:,np.newaxis] * Xn[...,1:,np.newaxis,:]
        u = [u0, u1, u2]

        # Compute cumulant-generating function
        g = -0.5 * np.einsum('...ij,...ij', u[0], phi[0]) + 0.5*ldet

        return (u, g)

    def compute_cgf_from_parents(self, *u_parents):
        raise NotImplementedError()

    def compute_fixed_moments_and_f(self, x, mask=True):
        """
        Compute u(x) and f(x) for given x.
        """
        u0 = x
        u1 = x[...,:,np.newaxis] * x[...,np.newaxis,:]
        u2 = x[...,:-1,:,np.newaxis] * x[...,1:,np.newaxis,:]
        u = [u0, u1, u2]

        f = -0.5 * np.shape(x)[-2] * np.shape(x)[-1] * np.log(2*np.pi)
        return (u, f)

    def plates_to_parent(self, index, plates):
        """
        Computes the plates of this node with respect to a parent.

        Child classes must implement this.

        Parameters
        -----------
        index : int
            The index of the parent node to use.
        """
        raise NotImplementedError()

    def plates_from_parent(self, index, plates):
        """
        Compute the plates using information of a parent node.

        Child classes must implement this.

        Parameters
        ----------
        index : int
            Index of the parent to use.
        """
        raise NotImplementedError()


    def rotate(self, u, phi, R, inv=None, logdet=None):

        (u, dg) = self.moments.rotate(u, R, logdet=logdet)

        # It would be more efficient and simpler, if you just rotated the
        # moments and didn't touch phi. However, then you would need to call
        # update() before lower_bound_contribution. This is more error-safe.

        if inv is None:
            inv = np.linalg.inv(R)

        # Transform parameters
        phi0 = linalg.mvdot(inv.T, phi[0])
        phi1 = linalg.dot(inv.T, phi[1], inv)
        phi2 = linalg.dot(inv.T, phi[2], inv)
        phi = [phi0, phi1, phi2]

        return (u, phi, dg)


    def compute_rotation_bound(self, u, u_mu_Lambda, u_A_V, R, inv=None, logdet=None):

        (Lambda_mu, Lambda_mumu, Lambda, logdetLambda) = u_mu_Lambda
        (V_A, V_AA, V, logdetV) = u_A_V

        V = misc.make_diag(V, ndim=1)

        R_XnXn = linalg.dot(R, self.XnXn)
        R_XpXp = linalg.dot(R, self.XpXp)
        R_X0X0 = linalg.dot(R, self.X0X0)

        tracedot(dot(Lambda, R_X0X0), R.T)
        tracedot(dot(V, R_XnXn), R.T)
        tracedot(dot(V_AA, R_XpXp), R.T)
        tracedot(dot(V_A, R_XpXn), R.T)
        (N - 1) * logdetV
        2 * N * logdetR

        logp = random.gaussian_logpdf(
            Lambda_R_X0X0_R + V_R_XnXn_R,
            V_A_R_XpXn_R,
            V_AA_R_XpXp_R,
            (N - 1) * logdetV + 2 * N * logdetR
        )

        logH = random.gaussian_entropy(
            -2 * M * logdetR,
            0
        )

        dlogp

        dlogH

        return (L, dL)


class _TemplateGaussianMarkovChain(ExponentialFamily):
    r"""
    VMP abstract node for Gaussian Markov chain.

    This is a general base class for different Gaussian Markov chain nodes.

    Output is Gaussian variables with mean, covariance and one-step
    cross-covariance.

    self.phi and self.u are defined in a particular way but otherwise the parent
    nodes may vary.

    Child classes must implement the following methods:
        _plates_to_parent
        _plates_from_parent

    See also
    --------
    bayespy.inference.vmp.nodes.gaussian.Gaussian
    bayespy.inference.vmp.nodes.wishart.Wishart

    """

    def random(self, *phi, plates=None):
        raise NotImplementedError()


def _compute_cgf_for_gaussian_markov_chain(mumu_Lambda, logdet_Lambda,
                                           logdet_nu, N):
    """
    Compute CGF using the moments of the parents.
    """

    g0 = -0.5 * mumu_Lambda #np.einsum('...ij,...ij->...', mumu, Lambda)

    g1 = 0.5 * logdet_Lambda
    if np.ndim(logdet_nu) == 1:
        g1 = g1 + 0.5 * (N-1) * np.sum(logdet_nu, axis=-1)
    elif np.shape(logdet_nu)[-2] == 1:
        g1 = g1 + 0.5 * (N-1) * np.sum(logdet_nu, axis=(-1,-2))
    else:
        g1 = g1 + 0.5 * np.sum(logdet_nu, axis=(-1,-2))

    return g0 + g1


class GaussianMarkovChainDistribution(TemplateGaussianMarkovChainDistribution):
    r"""
    Implementation of VMP formulas for Gaussian Markov chain

    The log probability density function of the prior:

    .. todo::  Fix inputs and their weight matrix in the equations.

    .. math::

       \log p(\mathbf{X} | \boldsymbol{\mu}, \mathbf{\Lambda},
       \mathbf{A}, \mathbf{B}, \boldsymbol{\nu})
       =& \log \mathcal{N}(\mathbf{x}_0|\boldsymbol{\mu}, \mathbf{\Lambda})
       + \sum^N_{n=1} \log \mathcal{N}(
         \mathbf{x}_n | \mathbf{Ax}_{n-1} + \mathbf{Bu}_n,
                        \mathrm{diag}(\boldsymbol{\nu}))
       \\
       =&
       - \frac{1}{2} \mathbf{x}_0^T \mathbf{\Lambda} \mathbf{x}_0
       + \frac{1}{2} \mathbf{x}_0^T \mathbf{\Lambda} \boldsymbol{\mu}
       + \frac{1}{2} \boldsymbol{\mu}^T \mathbf{\Lambda} \mathbf{x}_0
       - \frac{1}{2} \boldsymbol{\mu}^T \mathbf{\Lambda} \boldsymbol{\mu}
       + \frac{1}{2} \log|\mathbf{\Lambda}|
       \\
       &
       - \frac{1}{2} \sum^N_{n=1} \mathbf{x}_n^T \mathrm{diag}(\boldsymbol{\nu}) \mathbf{x}_n
       + \frac{1}{2} \sum^N_{n=1} \mathbf{x}_n^T \mathrm{diag}(\boldsymbol{\nu}) \mathbf{A} \mathbf{x}_{n-1}
       + \frac{1}{2} \sum^N_{n=1} \mathbf{x}_{n-1}^T\mathbf{A}^T \mathrm{diag}(\boldsymbol{\nu}) \mathbf{x}_n
       - \frac{1}{2} \sum^N_{n=1} \mathbf{x}_{n-1}^T\mathbf{A}^T \mathrm{diag}(\boldsymbol{\nu}) \mathbf{A} \mathbf{x}_{n-1}
       \\ &
       + \sum^N_{n=1} \sum^D_{d=1} \log\nu_d - \frac{1}{2} (N+1) D \log(2\pi)
       \\
       =&
       \begin{bmatrix}
         \mathbf{x}_0 \\ \mathbf{x}_1 \\ \vdots \\ \mathbf{x}_{N-1} \\ \mathbf{x}_N
       \end{bmatrix}^T
       \begin{bmatrix}
         -\frac{1}{2}\mathbf{\Lambda} - \frac{1}{2}\mathbf{A}\mathrm{diag}(\boldsymbol{\nu})\mathbf{A}^T
         &
         \frac{1}{2} \mathbf{A}^T\mathrm{diag}(\boldsymbol{\nu})
         &
         &
         &
         \\
         \frac{1}{2} \mathrm{diag}(\boldsymbol{\nu}) \mathbf{A}
         &
         -\frac{1}{2} \mathrm{diag}(\boldsymbol{\nu})
         - \frac{1}{2}\mathbf{A}^T\mathrm{diag}(\boldsymbol{\nu})\mathbf{A}^T
         &
         \frac{1}{2} \mathbf{A}^T\mathrm{diag}(\boldsymbol{\nu})
         &
         &
         \\
         &
         \ddots
         &
         \ddots
         &
         \ddots
         &
         \\
         &
         &
         \frac{1}{2} \mathrm{diag}(\boldsymbol{\nu}) \mathbf{A}
         &
         -\frac{1}{2} \mathrm{diag}(\boldsymbol{\nu})
         - \frac{1}{2}\mathbf{A}^T\mathrm{diag}(\boldsymbol{\nu})\mathbf{A}^T
         &
         \frac{1}{2} \mathbf{A}^T\mathrm{diag}(\boldsymbol{\nu})
         \\
         &
         &
         &
         \frac{1}{2} \mathrm{diag}(\boldsymbol{\nu}) \mathbf{A}
         &
         -\frac{1}{2} \mathrm{diag}(\boldsymbol{\nu})
       \end{bmatrix}
       \begin{bmatrix}
         \mathbf{x}_0 \\ \mathbf{x}_1 \\ \vdots \\ \mathbf{x}_{N-1} \\ \mathbf{x}_N
       \end{bmatrix}
       \\
       &
       + \frac{1}{2} \mathbf{x}_0^T \mathbf{\Lambda} \boldsymbol{\mu}
       + \frac{1}{2} \boldsymbol{\mu}^T \mathbf{\Lambda} \mathbf{x}_0
       - \frac{1}{2} \boldsymbol{\mu}^T \mathbf{\Lambda} \boldsymbol{\mu}
       + \frac{1}{2} \log|\mathbf{\Lambda}|
       + \sum^N_{n=1} \sum^D_{d=1} \log\nu_d - \frac{1}{2} (N+1) D \log(2\pi)


    For simplicity, :math:`\boldsymbol{\nu}` and :math:`\mathbf{A}` are assumed
    not to depend on :math:`n` in the above equation, but this distribution
    class supports that dependency. One only needs to do the following
    replacements in the equations: :math:`\boldsymbol{\nu} \leftarrow \boldsymbol{\nu}_n` and
    :math:`\mathbf{A} \leftarrow \mathbf{A}_n`, where :math:`n=1,\ldots,N`.

    .. math::

       u(\mathbf{X}) &=
       \begin{bmatrix}
         \begin{bmatrix} \mathbf{x}_0 & \ldots & \mathbf{x}_N \end{bmatrix}
         \\
         \begin{bmatrix} \mathbf{x}_0\mathbf{x}_0^T & \ldots & \mathbf{x}_N\mathbf{x}_N^T \end{bmatrix}
         \\
         \begin{bmatrix} \mathbf{x}_0\mathbf{x}_1^T & \ldots & \mathbf{x}_{N-1}\mathbf{x}_N^T \end{bmatrix}
       \end{bmatrix}
       \\
       \phi(\boldsymbol{\mu}, \mathbf{\Lambda}, \mathbf{A}, \boldsymbol{\nu}) &=
       \begin{bmatrix}
         \begin{bmatrix}
           \mathbf{\Lambda} \boldsymbol{\mu} & \mathbf{0} & \ldots & \mathbf{0}
         \end{bmatrix}
         \\
         \begin{bmatrix}
           -\frac{1}{2}\mathbf{\Lambda} - \frac{1}{2} \mathbf{A}\mathrm{diag}(\boldsymbol{\nu})\mathbf{A}^T &
           -\frac{1}{2}\mathrm{diag}(\boldsymbol{\nu}) - \frac{1}{2} \mathbf{A}\mathrm{diag}(\boldsymbol{\nu})\mathbf{A}^T &
           \ldots &
           -\frac{1}{2}\mathrm{diag}(\boldsymbol{\nu}) - \frac{1}{2} \mathbf{A}\mathrm{diag}(\boldsymbol{\nu})\mathbf{A}^T &
           -\frac{1}{2}\mathrm{diag}(\boldsymbol{\nu})
         \end{bmatrix}
         \\
         \begin{bmatrix}
           \mathbf{A}^T \mathrm{diag}(\boldsymbol{\nu}) & \ldots & \mathbf{A}^T \mathrm{diag}(\boldsymbol{\nu})
         \end{bmatrix}
       \end{bmatrix}
       \\
       g(\boldsymbol{\mu}, \mathbf{\Lambda}, \mathbf{A}, \boldsymbol{\nu}) &=
       \frac{1}{2}\log|\mathbf{\Lambda}| + \frac{1}{2} \sum^N_{n=1}\sum^D_{d=1}\log\nu_d
       \\
       f(\mathbf{X}) &= -\frac{1}{2} (N+1) D \log(2\pi)

    The log probability denisty function of the posterior approximation:

    .. math::

       \log q(\mathbf{X}) &=
       \begin{bmatrix}
         \mathbf{x}_0
         \\
         \mathbf{x}_1
         \\
         \vdots
         \\
         \mathbf{x}_{N-1}
         \\
         \mathbf{x}_N
       \end{bmatrix}^T
       \begin{bmatrix}
         \mathbf{\Phi}_0^{(2)} & \frac{1}{2}\mathbf{\Phi}_1^{(3)} & & &
         \\
         \frac{1}{2}{\mathbf{\Phi}_1^{(3)}}^T & \mathbf{\Phi}_1^{(2)} & \frac{1}{2}\mathbf{\Phi}_2^{(3)} & &
         \\
         & \ddots & \ddots & \ddots &
         \\
         & & \frac{1}{2}{\mathbf{\Phi}_{N-1}^{(3)}}^T & \mathbf{\Phi}_{N-1}^{(2)} & \frac{1}{2}\mathbf{\Phi}_N^{(3)}
         \\
         & & & \frac{1}{2}{\mathbf{\Phi}_N^{(3)}}^T & \mathbf{\Phi}_N^{(2)}
       \end{bmatrix}
       \begin{bmatrix}
         \mathbf{x}_0
         \\
         \mathbf{x}_1
         \\
         \vdots
         \\
         \mathbf{x}_{N-1}
         \\
         \mathbf{x}_N
       \end{bmatrix}
       + \ldots

    """


    def compute_message_to_parent(self, parent, index, u, u_mu_Lambda, u_A_nu, *u_inputs):
        r"""
        Compute a message to a parent.

        Parameters
        ----------
        index : int
            Index of the parent requesting the message.
        u : list of ndarrays
            Moments of this node.
        u_mu_Lambda : list of ndarrays
            Moments of parents :math:`(\boldsymbol{\mu}, \mathbf{\Lambda})`.
        u_A_nu : list of ndarrays
            Moments of parents :math:`(\mathbf{A}, \boldsymbol{\nu})`.
        u_inputs : list of ndarrays
            Moments of input signals.
        """

        D = np.shape(u[0])[-1]

        if index == 0:   # (mu, Lambda) -- GaussianWishartMoments
            x0 = u[0][...,0,:]
            x0x0 = u[1][...,0,:,:]
            m0 = x0
            m1 = -0.5
            m2 = -0.5 * x0x0
            m3 = 0.5
            return [m0, m1, m2, m3]

        elif index == 1: # (A, nu) -- GaussianGammaMoments
            XnXn = u[1]
            XpXn = u[2]

            # (..., N-1, D, D)
            m0 = XpXn.swapaxes(-1,-2)
            # (..., N-1, D, D, D)
            m1 = -0.5 * XnXn[..., :-1, None, :, :]
            # (..., N-1, D)
            m2 = -0.5 * np.einsum('...ii->...i', XnXn[...,1:,:,:])
            # (..., N-1, D)
            m3 = 0.5

            if len(u_inputs):
                Xn = u[0]
                z = u_inputs[0][0]
                zz = u_inputs[0][1]
                D_inputs = np.shape(z)[-1]
                m0_B = Xn[...,1:,:,None] * z[...,None,:]
                m1_BB = -0.5 * zz[..., None, :, :]
                m1_AB = -0.5 * Xn[..., :-1, None, :, None] * z[..., None, None, :]

                # Construct full message arrays from blocks
                m0 = np.concatenate([m0, m0_B], axis=-1)
                row1 = np.concatenate([m1, m1_AB], axis=-1)
                row2 = np.concatenate([m1_AB.swapaxes(-1,-2), m1_BB], axis=-1)
                m1 = np.concatenate([row1, row2], axis=-2)

            return [m0, m1, m2, m3]


        #     m1 = 0.5
        elif index == 2: # input signals

            # (..., N-1, D)
            Xn = u[0][...,1:,:]
            # (..., N-1, D)
            Xp = u[0][...,:-1,:]
            # (..., N-1, D, K)
            B = u_A_nu[0][...,D:]
            # (..., N-1, D, D, K)
            AB = u_A_nu[1][...,:D,D:]
            # (..., N-1, D, K, K)
            BB = u_A_nu[1][...,D:,D:]

            # (..., N-1, K)
            m0 = (
                np.einsum('...dk,...d->...k', B, Xn) -
                np.einsum('...dk,...d->...k', np.sum(AB, axis=-3), Xp)
            )
            # (..., N-1, K, K)
            m1 = -0.5 * np.sum(BB, axis=-3)

            return [m0, m1]

        raise IndexError("Parent index out of bounds")


    def compute_weights_to_parent(self, index, weights):

        if index == 0:   # mu_Lambda
            return weights
        elif index == 1: # A_nu
            return weights[...,np.newaxis,np.newaxis]
        elif index == 2: # input signals
            return weights[...,np.newaxis]
        else:
            raise ValueError("Index out of bounds")


    def compute_phi_from_parents(self, u_mu_Lambda, u_A_nu, *u_inputs, mask=True):
        """
        Compute the natural parameters using parents' moments.

        Parameters
        ----------
        u_parents : list of list of arrays
           List of parents' lists of moments.

        Returns
        -------
        phi : list of arrays
           Natural parameters.
        dims : tuple
           Shape of the variable part of phi.

        """

        # Dimensionality of the Gaussian states
        D = np.shape(u_mu_Lambda[0])[-1]

        # Number of time instances in the process
        N = self.N

        # Helpful variables (show shapes in comments)
        Lambda_mu = u_mu_Lambda[0]   # (..., D)
        Lambda = u_mu_Lambda[2]      # (..., D, D)
        nu_A = u_A_nu[0][...,:D]     # (..., N-1, D, D)
        nu_AA = u_A_nu[1][...,:D,:D] # (..., N-1, D, D, D)
        nu_B = u_A_nu[0][...,D:]     # (..., N-1, D, inputs)
        nu_BB = u_A_nu[1][...,D:,D:] # (..., N-1, D, inputs, inputs)
        nu_AB = u_A_nu[1][...,:D,D:] # (..., N-1, D, D, inputs)
        nu = u_A_nu[2] * np.ones(D)  # (..., N-1, D)
        # mu = u_mu[0]           # (..., D)
        # Lambda = u_Lambda[0]   # (..., D, D)
        # A = u_A[0][...,:D]     # (..., N-1, D, D)
        # AA = u_A[1][...,:D,:D] # (..., N-1, D, D, D)
        # B = u_A[0][...,D:]     # (..., N-1, D, inputs)
        # BB = u_A[1][...,D:,D:] # (..., N-1, D, inputs, inputs)
        # AB = u_A[1][...,:D,D:] # (..., N-1, D, D, inputs)
        # v = u_v[0]             # (..., N-1, D)
        if len(u_inputs):
            inputs = u_inputs[0][0]
        else:
            inputs = None

        # Allocate memory (take into account effective plates)
        if inputs is not None:
            plates_phi0 = misc.broadcasted_shape(np.shape(Lambda_mu)[:-1],
                                                 np.shape(nu_B)[:-3],
                                                 np.shape(nu_AB)[:-4])
        else:
            plates_phi0 = misc.broadcasted_shape(np.shape(Lambda_mu)[:-1])

        plates_phi1 = misc.broadcasted_shape(np.shape(Lambda)[:-2],
                                             np.shape(nu_AA)[:-4])
        plates_phi2 = misc.broadcasted_shape(np.shape(nu_A)[:-3])

        phi0 = np.zeros(plates_phi0+(N,D))
        phi1 = np.zeros(plates_phi1+(N,D,D))
        phi2 = np.zeros(plates_phi2+(N-1,D,D))

        # Parameters for x0
        phi0[...,0,:] = Lambda_mu #np.einsum('...ik,...k->...i', Lambda, mu)
        phi1[...,0,:,:] = -0.5 * Lambda

        # Effect of the input signals
        if inputs is not None:
            phi0[...,1:,:] += np.einsum('...ij,...j->...i', nu_B, inputs)
            phi0[...,:-1,:] -= np.einsum(
                '...ij,...j->...i',
                np.sum(nu_AB, axis=-3),
                inputs
            )

        # Diagonal blocks: -0.5 * (V_i + A_{i+1}' * V_{i+1} * A_{i+1})
        phi1[..., 1:, :, :] = -0.5 * misc.diag(nu, ndim=1)
        phi1[..., :-1, :, :] += -0.5 * np.sum(nu_AA, axis=-3) #np.einsum('...kij,...k->...ij', AA, v)
        #phi1 *= -0.5

        # Super-diagonal blocks: 0.5 * A.T * V
        # However, don't multiply by 0.5 because there are both super- and
        # sub-diagonal blocks (sum them together)
        phi2[..., :, :, :] = linalg.transpose(nu_A, ndim=1) # np.einsum('...ji,...j->...ij', A, v)

        return (phi0, phi1, phi2)

    def compute_cgf_from_parents(self, u_mu_Lambda, u_A_nu, *u_inputs):
        """
        Compute CGF using the moments of the parents.
        """
        g = _compute_cgf_for_gaussian_markov_chain(u_mu_Lambda[1],
                                                   u_mu_Lambda[3],
                                                   u_A_nu[3],
                                                   self.N)

        if len(u_inputs):
            D = np.shape(u_mu_Lambda[0])[-1]
            uu = u_inputs[0][1]
            nu_BB = u_A_nu[1][...,D:,D:]
            nu = u_A_nu[2]
            #BB_v = np.einsum('...d,...dij->...ij', v, BB)
            g_inputs = -0.5 * np.einsum(
                '...ij,...ij->...',
                uu,
                np.sum(nu_BB, axis=-3)
                #BB_v
            )
            # Sum over time axis
            if np.ndim(g_inputs) == 0 or np.shape(g_inputs)[-1] == 1:
                g_inputs *= self.N - 1
            if np.ndim(g_inputs) > 0:
                g_inputs = np.sum(g_inputs, axis=-1)
            g = g + g_inputs

        return g


    def plates_to_parent(self, index, plates):
        """
        Computes the plates of this node with respect to a parent.

        If this node has plates (...), the latent dimensionality is D
        and the number of time instances is N, the plates with respect
        to the parents are:
          (mu, Lambda): (...)
          (A, nu):      (...,N-1,D)

        Parameters
        ----------
        index : int
            The index of the parent node to use.
        """

        if index == 0:   # (mu, Lambda)
            return plates
        elif index == 1: # (A, nu)
            return plates + (self.N-1, self.D)
        elif index == 2: # input signals
            return plates + (self.N-1,)
        else:
            raise ValueError("Invalid parent index.")

    def plates_from_parent(self, index, plates):
        """
        Compute the plates using information of a parent node.

        If the plates of the parents are:
          (mu, Lambda): (...)
          (A, nu):      (...,N-1,D)
        the resulting plates of this node are (...)

        Parameters
        ----------
        index : int
            Index of the parent to use.
        """
        if index == 0:   # (mu, Lambda)
            return plates
        elif index == 1: # (A, nu)
            return plates[:-2]
        elif index == 2: # input signals
            return plates[:-1]
        else:
            raise ValueError("Invalid parent index.")


class GaussianMarkovChain(_TemplateGaussianMarkovChain):
    r"""
    Node for Gaussian Markov chain random variables.

    In a simple case, the graphical model can be presented as:

    .. bayesnet::

       \tikzstyle{latent} += [minimum size=30pt];

       \node[latent] (x0) {$\mathbf{x}_0$};
       \node[latent, right=of x0] (x1) {$\mathbf{x}_1$};
       \node[right=of x1] (dots) {$\cdots$};
       \node[latent, right=of dots] (xn) {$\mathbf{x}_{N-1}$};
       \edge {x0}{x1};
       \edge {x1}{dots};
       \edge {dots}{xn};

       \node[latent, above left=1 and 0.1 of x0] (mu) {$\boldsymbol{\mu}$};
       \node[latent, above right=1 and 0.1 of x0] (Lambda) {$\mathbf{\Lambda}$};
       \node[latent, above left=1 and 0.1 of dots] (A) {$\mathbf{A}$};
       \node[latent, above right=1 and 0.1 of dots] (nu) {$\boldsymbol{\nu}$};
       \edge {mu,Lambda} {x0};
       \edge {A,nu} {x1,dots,xn};

    where :math:`\boldsymbol{\mu}` and :math:`\mathbf{\Lambda}` are the mean and
    the precision matrix of the initial state, :math:`\mathbf{A}` is the state
    dynamics matrix and :math:`\boldsymbol{\nu}` is the precision of the
    innovation noise.  It is possible that :math:`\mathbf{A}` and/or
    :math:`\boldsymbol{\nu}` are different for each transition instead of being
    constant.

    The probability distribution is

    .. math::

       p(\mathbf{x}_0, \ldots, \mathbf{x}_{N-1}) = p(\mathbf{x}_0)
       \prod^{N-1}_{n=1} p(\mathbf{x}_n | \mathbf{x}_{n-1})

    where

    .. math::

       p(\mathbf{x}_0) &= \mathcal{N}(\mathbf{x}_0 | \boldsymbol{\mu}, \mathbf{\Lambda})
       \\
       p(\mathbf{x}_n|\mathbf{x}_{n-1}) &= \mathcal{N}(\mathbf{x}_n |
       \mathbf{A}_{n-1}\mathbf{x}_{n-1}, \mathrm{diag}(\boldsymbol{\nu}_{n-1})).

    Parameters
    ----------

    mu : Gaussian-like node or (...,D)-array
        :math:`\boldsymbol{\mu}`, mean of :math:`x_0`, :math:`D`-dimensional
        with plates (...)

    Lambda : Wishart-like node or (...,D,D)-array
        :math:`\mathbf{\Lambda}`, precision matrix of :math:`x_0`,
        :math:`D\times D` -dimensional with plates (...)

    A : Gaussian-like node or (D,D)-array or (...,1,D,D)-array or (...,N-1,D,D)-array
        :math:`\mathbf{A}`, state dynamics matrix, :math:`D`-dimensional with
        plates (D,) or (...,1,D) or (...,N-1,D)

    nu : gamma-like node or (D,)-array or (...,1,D)-array or (...,N-1,D)-array
        :math:`\boldsymbol{\nu}`, diagonal elements of the precision of the
        innovation process, plates (D,) or (...,1,D) or (...,N-1,D)

    n : int, optional
        :math:`N`, the length of the chain. Must be given if :math:`\mathbf{A}`
        and :math:`\boldsymbol{\nu}` are constant over time.

    See also
    --------

    Gaussian, GaussianARD, Wishart, Gamma, SwitchingGaussianMarkovChain,
    VaryingGaussianMarkovChain, CategoricalMarkovChain
    """


    def __init__(self, mu, Lambda, A, nu, n=None, inputs=None, **kwargs):
        """
        Create GaussianMarkovChain node.
        """
        super().__init__(mu, Lambda, A, nu, n=n, inputs=inputs, **kwargs)


    @classmethod
    def _constructor(cls, mu, Lambda, A, nu, n=None, inputs=None, **kwargs):
        """
        Constructs distribution and moments objects.

        Compute the dimensions of phi and u.

        The plates and dimensions of the parents should be:
        mu:     (...)                    and D-dimensional
        Lambda: (...)                    and D-dimensional
        A:      (...,1,D) or (...,N-1,D) and D-dimensional
        v:      (...,1,D) or (...,N-1,D) and 0-dimensional
        N:      ()                       and 0-dimensional (dummy parent)

        Check that the dimensionalities of the parents are proper.
        For instance, A should be a collection of DxD matrices, thus
        the dimensionality and the last plate should both equal D.
        Similarly, `v` should be a collection of diagonal innovation
        matrix elements, thus the last plate should equal D.
        """

        mu_Lambda = WrapToGaussianWishart(mu, Lambda)
        A_nu = WrapToGaussianGamma(A, nu, ndim=1)

        D = mu_Lambda.dims[0][0]

        if inputs is not None:
            inputs = cls._ensure_moments(inputs, GaussianMoments, ndim=1)

        # Check whether to use input signals or not
        if inputs is None:
            _parent_moments = (GaussianWishartMoments((D,)),
                               GaussianGammaMoments((D,)))
        else:
            K = inputs.dims[0][0]
            _parent_moments = (GaussianWishartMoments((D,)),
                               GaussianGammaMoments((D,)),
                               GaussianMoments((K,)))

        # Time instances from input signals
        if inputs is not None and len(inputs.plates) >= 1:
            n_inputs = inputs.plates[-1]
        else:
            n_inputs = 1
        # Time instances from state dynamics matrix
        if len(A_nu.plates) >= 2:
            n_A_nu = A_nu.plates[-2]
        else:
            n_A_nu = 1
        # Check consistency of the number of time instances
        if n_inputs != n_A_nu and n_inputs != 1 and n_A_nu != 1:
            raise Exception("Plates of parents are giving different number of time instances")
        n_parents = max(n_A_nu, n_inputs)
        if n is None:
            if n_parents == 1:
                raise Exception("The number of time instances could not be "
                                "determined automatically. Give the number of "
                                "time instances.")
            n = n_parents + 1
        elif n_parents != 1 and n_parents+1 != n:
            raise Exception("The number of time instances must match "
                            "the number of last plates of parents: "
                            "%d != %d+1" % (n, n_parents))

        # Dimensionality of the states
        D = mu_Lambda.dims[0][0]
        # Number of states
        M = n
        # Dimensionality of the inputs
        if inputs is None:
            D_inputs = 0
        else:
            D_inputs = inputs.dims[0][0]

        # Check (mu, Lambda)
        if mu_Lambda.dims != ( (D,), (), (D, D), () ):
            raise Exception("Initial state parameters have wrong dimensionality")
        # Check (A, nu)
        if A_nu.dims != ( (D+D_inputs,), (D+D_inputs,D+D_inputs), (), () ):
            raise Exception("Dynamics matrix has wrong dimensionality")
        if len(A_nu.plates) == 0 or A_nu.plates[-1] != D:
            raise Exception("Dynamics matrix should have a last plate "
                            "equal to the dimensionality of the "
                            "system.")
        if (len(A_nu.plates) >= 2
            and A_nu.plates[-2] != 1
            and A_nu.plates[-2] != M-1):
            raise ValueError("The second last plate of the dynamics matrix "
                             "should have length equal to one or "
                             "N-1, where N is the number of time "
                             "instances.")
        # Check input signals
        if inputs is not None:
            if inputs.dims != ( (D_inputs,), (D_inputs, D_inputs) ):
                raise ValueError("Input signals have wrong dimensionality")

        moments = GaussianMarkovChainMoments(M, D)
        dims = ( (M,D), (M,D,D), (M-1,D,D) )
        distribution = GaussianMarkovChainDistribution(M, D)

        if inputs is None:
            parents = [mu_Lambda, A_nu]
        else:
            parents = [mu_Lambda, A_nu, inputs]

        return ( parents,
                 kwargs,
                 dims,
                 cls._total_plates(kwargs.get('plates'),
                                   distribution.plates_from_parent(0, mu_Lambda.plates),
                                   distribution.plates_from_parent(1, A_nu.plates)),
                 distribution,
                 moments,
                 _parent_moments)


    def rotate(self, R, inv=None, logdet=None):

        # It would be more efficient and simpler, if you just rotated the
        # moments and didn't touch phi. However, then you would need to call
        # update() before lower_bound_contribution. This is more error-safe.
        (u, phi, dg) = self._distribution.rotate(
            self.u,
            self.phi,
            R,
            inv=inv,
            logdet=logdet
        )
        self.u = u
        self.phi = phi
        self.g = self.g + dg

        return


class VaryingGaussianMarkovChainDistribution(TemplateGaussianMarkovChainDistribution):
    """
    Sub-classes implement distribution specific computations.
    """


    def compute_message_to_parent(self, parent, index, u, u_mu, u_Lambda, u_B,
                                   u_S, u_v):
        """
        Compute a message to a parent.

        Parameters
        -----------
        index : int
            Index of the parent requesting the message.
        u : list of ndarrays
            Moments of this node.
        u_mu : list of ndarrays
            Moments of parent `mu`.
        u_Lambda : list of ndarrays
            Moments of parent `Lambda`.
        u_B : list of ndarrays
            Moments of parent `B`.
        u_S : list of ndarrays
            Moments of parent `S`.
        u_v : list of ndarrays
            Moments of parent `v`.
        """

        if index == 0:   # mu
            raise NotImplementedError()
        elif index == 1: # Lambda
            raise NotImplementedError()
        elif index == 2: # B, (...,D)x(D,K)
            XnXn = u[1] # (...,N,D,D)
            XpXn = u[2] # (...,N,D,D)
            S = misc.atleast_nd(u_S[0], 2)  # (...,N,K)
            SS = misc.atleast_nd(u_S[1], 3) # (...,N,K,K)
            v = misc.atleast_nd(u_v[0], 2)  # (...,N,D)

            # m0: (...,D,D,K)
            m0 = np.einsum('...nji,...nk,...ni->...ijk',
                           XpXn,
                           S,
                           v)

            # m1: (...,D,D,K,D,K)

            if np.ndim(v) >= 2 and np.shape(v)[-2] > 1:
                raise ValueError("Innovation noise is time dependent")

            m1 = np.einsum('...nij,...nkl->...ikjl',
                           XnXn[...,:-1,:,:],
                           SS)
            m1 = -0.5 * np.einsum('...ikjl,...d->...dikjl',
                                  m1,
                                  v[...,0,:])

        elif index == 3: # S, (...,N-1)x(K)
            XnXn = u[1] # (...,N,D,D)
            XpXn = u[2] # (...,N,D,D)
            B = u_B[0]  # (...,D,D,K)
            BB = u_B[1] # (...,D,D,K,D,K)
            v = u_v[0]  # (...,N,D)

            # m0: (...,N,K)
            m0 = np.einsum('...nji,...ijk,...ni->...nk',
                           XpXn,
                           B,
                           np.atleast_2d(v))

            # m1: (...,N,K,K)

            if np.ndim(v) >= 2 and np.shape(v)[-2] > 1:
                raise ValueError("Innovation noise is time dependent")
            m1 = np.einsum('...dikjl,...d->...ikjl',
                           BB,
                           np.atleast_2d(v)[...,0,:])
            m1 = -0.5 * np.einsum('...nij,...ikjl->...nkl',
                                  XnXn[...,:-1,:,:],
                                  m1)

        elif index == 4: # v
            raise NotImplementedError()
        elif index == 5: # N
            raise NotImplementedError()

        return [m0, m1]


    def compute_weights_to_parent(self, index, weights):

        if index == 0: # mu
            return weights
        elif index == 1: # Lambda
            return weights
        elif index == 2: # B
            return weights[...,np.newaxis] # new plate axis for D
        elif index == 3: # S
            return weights[...,np.newaxis] # new plate axis for N
        elif index == 4: # v
            return weights[...,np.newaxis,np.newaxis] # new plate axis for N and D
        elif index == 5: # N
            return weights
        else:
            raise ValueError("Invalid index")


    def compute_phi_from_parents(self, u_mu, u_Lambda, u_B, u_S, u_v,
                                 mask=True):
        """
        Compute the natural parameters using parents' moments.

        Parameters
        ----------
        u_parents : list of list of arrays
           List of parents' lists of moments.

        Returns
        -------
        phi : list of arrays
           Natural parameters.
        dims : tuple
           Shape of the variable part of phi.

        """

        # Dimensionality of the Gaussian states
        D = np.shape(u_mu[0])[-1]

        # Number of time instances in the process
        N = self.N

        # Helpful variables (show shapes in comments)
        mu = u_mu[0]         # (..., D)
        Lambda = u_Lambda[0] # (..., D, D)
        B = u_B[0]           # (..., D, D, K)
        BB = u_B[1]          # (..., D, D, K, D, K)
        S = u_S[0]           # (..., N-1, K) or (..., 1, K)
        SS = u_S[1]          # (..., N-1, K, K)
        v = u_v[0]           # (..., N-1, D) or (..., 1, D)

        # TODO/FIXME: Take into account plates!
        plates_phi0 = misc.broadcasted_shape(np.shape(mu)[:-1],
                                             np.shape(Lambda)[:-2])
        plates_phi1 = misc.broadcasted_shape(np.shape(Lambda)[:-2],
                                             np.shape(v)[:-2],
                                             np.shape(BB)[:-5],
                                             np.shape(SS)[:-3])
        plates_phi2 = misc.broadcasted_shape(np.shape(B)[:-3],
                                             np.shape(S)[:-2],
                                             np.shape(v)[:-2])
        phi0 = np.zeros(plates_phi0 + (N,D))
        phi1 = np.zeros(plates_phi1 + (N,D,D))
        phi2 = np.zeros(plates_phi2 + (N-1,D,D))

        # Parameters for x0
        phi0[...,0,:] = np.einsum('...ik,...k->...i', Lambda, mu)
        phi1[...,0,:,:] = Lambda


        # Diagonal blocks: -0.5 * (V_i + A_{i+1}' * V_{i+1} * A_{i+1})
        phi1[..., 1:, :, :] = v[...,np.newaxis]*np.identity(D)
        if np.ndim(v) >= 2 and np.shape(v)[-2] > 1:
            raise Exception("This implementation is not efficient if "
                            "innovation noise is time-dependent.")
            phi1[..., :-1, :, :] += np.einsum('...dikjl,...kl,...d->...ij',
                                              BB[...,None,:,:,:,:,:],
                                              SS,
                                              v)
        else:
            # We know that S does not have the D plate so we can sum that plate
            # axis out
            v_BB = np.einsum('...dikjl,...d->...ikjl',
                             BB[...,None,:,:,:,:,:],
                             v)
            phi1[..., :-1, :, :] += np.einsum('...ikjl,...kl->...ij',
                                              v_BB,
                                              SS)

        #phi1[..., :-1, :, :] += np.einsum('...kij,...k->...ij', AA, v)
        phi1 *= -0.5

        # Super-diagonal blocks: 0.5 * A.T * V
        # However, don't multiply by 0.5 because there are both super- and
        # sub-diagonal blocks (sum them together)
        phi2[..., :, :, :] = np.einsum('...jik,...k,...j->...ij',
                                       B[...,None,:,:,:],
                                       S,
                                       v)
        #phi2[..., :, :, :] = np.einsum('...ji,...j->...ij', A, v)

        return (phi0, phi1, phi2)

    def compute_cgf_from_parents(self, u_mu, u_Lambda, u_B, u_S, u_v):
        """
        Compute CGF using the moments of the parents.
        """

        u_mumu_Lambda = linalg.inner(u_Lambda[0], u_mu[1], ndim=2)
        return _compute_cgf_for_gaussian_markov_chain(u_mumu_Lambda,
                                                      u_Lambda[1],
                                                      u_v[1],
                                                      self.N)

    def plates_to_parent(self, index, plates):
        """
        Computes the plates of this node with respect to a parent.

        If this node has plates (...), the latent dimensionality is D
        and the number of time instances is N, the plates with respect
        to the parents are:
          mu:     (...)
          Lambda: (...)
          A:      (...,N-1,D)
          v:      (...,N-1,D)

        Parameters
        -----------
        index : int
            The index of the parent node to use.
        """

        if index == 0:   # mu
            return plates
        elif index == 1: # Lambda
            return plates
        elif index == 2: # B
            return plates + (self.D,)
        elif index == 3: # S
            return plates + (self.N-1,)
        elif index == 4: # v
            return plates + (self.N-1,self.D)
        else:
            raise ValueError("Invalid parent index.")

    def plates_from_parent(self, index, plates):
        """
        Compute the plates using information of a parent node.

        If the plates of the parents are:
          mu:     (...)
          Lambda: (...)
          B:      (...,D)
          S:      (...,N-1)
          v:      (...,N-1,D)
          N:      ()
        the resulting plates of this node are (...)

        Parameters
        ----------
        index : int
            Index of the parent to use.
        """
        if index == 0:   # mu
            return plates
        elif index == 1: # Lambda
            return plates
        elif index == 2: # B, remove last plate D
            return plates[:-1]
        elif index == 3: # S, remove last plate N-1
            return plates[:-1]
        elif index == 4: # v, remove last plates N-1,D
            return plates[:-2]
        else:
            raise ValueError("Invalid parent index.")




class VaryingGaussianMarkovChain(_TemplateGaussianMarkovChain):
    r"""
    Node for Gaussian Markov chain random variables with time-varying dynamics.

    The node models a sequence of Gaussian variables
    :math:`\mathbf{x}_0,\ldots,\mathbf{x}_{N-1}` with linear Markovian dynamics.
    The time variability of the dynamics is obtained by modelling the state
    dynamics matrix as a linear combination of a set of matrices with
    time-varying linear combination weights.  The
    graphical model can be presented as:

    .. bayesnet::

       \tikzstyle{latent} += [minimum size=40pt];

       \node[latent] (x0) {$\mathbf{x}_0$};
       \node[latent, right=of x0] (x1) {$\mathbf{x}_1$};
       \node[right=of x1] (dots) {$\cdots$};
       \node[latent, right=of dots] (xn) {$\mathbf{x}_{N-1}$};
       \edge {x0}{x1};
       \edge {x1}{dots};
       \edge {dots}{xn};

       \node[latent, above left=1 and 0.1 of x0] (mu) {$\boldsymbol{\mu}$};
       \node[latent, above right=1 and 0.1 of x0] (Lambda) {$\mathbf{\Lambda}$};
       \node[det, below=of x1] (A0) {$\mathbf{A}_0$};
       \node[right=of A0] (Adots) {$\cdots$};
       \node[det, right=of Adots] (An) {$\mathbf{A}_{N-2}$};
       \node[latent, above=of dots] (nu) {$\boldsymbol{\nu}$};
       \edge {mu,Lambda} {x0};
       \edge {nu} {x1,dots,xn};
       \edge {A0} {x1};
       \edge {Adots} {dots};
       \edge {An} {xn};

       \node[latent, below=of A0] (s0) {$s_{0,k}$};
       \node[right=of s0] (sdots) {$\cdots$};
       \node[latent, right=of sdots] (sn) {$\mathbf{s}_{N-2,k}$};
       \node[latent, left=of s0] (B) {$\mathbf{B}_k$};
       \edge {B} {A0, Adots, An};
       \edge {s0} {A0};
       \edge {sdots} {Adots};
       \edge {sn} {An};

       \plate {K} {(B)(s0)(sdots)(sn)} {$k=0,\ldots,K-1$};

    where :math:`\boldsymbol{\mu}` and :math:`\mathbf{\Lambda}` are the mean and
    the precision matrix of the initial state, :math:`\boldsymbol{\nu}` is the
    precision of the innovation noise, and :math:`\mathbf{A}_n` are the state
    dynamics matrix obtained by mixing matrices :math:`\mathbf{B}_k` with
    weights :math:`s_{n,k}`.

    The probability distribution is

    .. math::

       p(\mathbf{x}_0, \ldots, \mathbf{x}_{N-1}) = p(\mathbf{x}_0)
       \prod^{N-1}_{n=1} p(\mathbf{x}_n | \mathbf{x}_{n-1})

    where

    .. math::

       p(\mathbf{x}_0) &= \mathcal{N}(\mathbf{x}_0 | \boldsymbol{\mu}, \mathbf{\Lambda})
       \\
       p(\mathbf{x}_n|\mathbf{x}_{n-1}) &= \mathcal{N}(\mathbf{x}_n |
       \mathbf{A}_{n-1}\mathbf{x}_{n-1}, \mathrm{diag}(\boldsymbol{\nu})),
       \quad \text{for } n=1,\ldots,N-1,
       \\
       \mathbf{A}_n & = \sum^{K-1}_{k=0} s_{n,k} \mathbf{B}_k, \quad \text{for }
       n=0,\ldots,N-2.


    Parameters
    ----------

    mu : Gaussian-like node or (...,D)-array
        :math:`\boldsymbol{\mu}`, mean of :math:`x_0`, :math:`D`-dimensional
        with plates (...)

    Lambda : Wishart-like node or (...,D,D)-array
        :math:`\mathbf{\Lambda}`, precision matrix of :math:`x_0`,
        :math:`D\times D` -dimensional with plates (...)

    B : Gaussian-like node or (...,D,D,K)-array
        :math:`\{\mathbf{B}_k\}_{k=0}^{K-1}`, a set of state dynamics matrix,
        :math:`D \times K`-dimensional with plates (...,D)

    S : Gaussian-like node or (...,N-1,K)-array

        :math:`\{\mathbf{s}_0,\ldots,\mathbf{s}_{N-2}\}`, time-varying weights
        of the linear combination, :math:`K`-dimensional with plates (...,N-1)

    nu : gamma-like node or (...,D)-array
        :math:`\boldsymbol{\nu}`, diagonal elements of the precision of the
        innovation process, plates (...,D)

    n : int, optional
        :math:`N`, the length of the chain. Must be given if :math:`\mathbf{S}`
        does not have plates over the time domain (which would not make sense).

    See also
    --------

    Gaussian, GaussianARD, Wishart, Gamma, GaussianMarkovChain,
    SwitchingGaussianMarkovChain

    Notes
    -----

    Equivalent model block can be constructed with :class:`GaussianMarkovChain`
    by explicitly using :class:`SumMultiply` to compute the linear combination.
    However, that approach is not very efficient for large datasets because it
    does not utilize the structure of :math:`\mathbf{A}_n`, thus it explicitly
    computes huge moment arrays.

    References
    ----------

    :cite:`Luttinen:2014`

    """

    def __init__(self, mu, Lambda, B, S, nu, n=None, **kwargs):
        """
        Create VaryingGaussianMarkovChain node.
        """
        super().__init__(mu, Lambda, B, S, nu, n=n, **kwargs)


    @classmethod
    def _constructor(cls, mu, Lambda, B, S, v, n=None, **kwargs):
        """
        Constructs distribution and moments objects.

        Compute the dimensions of phi and u.

        The plates and dimensions of the parents should be:
        mu:     (...)                    and D-dimensional
        Lambda: (...)                    and D-dimensional
        B:      (...,D)                  and (D,K)-dimensional
        S:      (...,N-1)                and K-dimensional
        v:      (...,1,D) or (...,N-1,D) and 0-dimensional
        N:      ()                       and 0-dimensional (dummy parent)

        Check that the dimensionalities of the parents are proper.
        """

        mu = cls._ensure_moments(mu, GaussianMoments, ndim=1)
        Lambda = cls._ensure_moments(Lambda, WishartMoments, ndim=1)
        B = cls._ensure_moments(B, GaussianMoments, ndim=2)
        S = cls._ensure_moments(S, GaussianMoments, ndim=1)
        v = cls._ensure_moments(v, GammaMoments)

        (D, K) = B.dims[0]

        parent_moments = (
            GaussianMoments((D,)),
            WishartMoments((D,)),
            GaussianMoments((D, K)),
            GaussianMoments((K,)),
            GammaMoments()
        )

        # A dummy wrapper for the number of time instances.
        n_S = 1
        if len(S.plates) >= 1:
            n_S = S.plates[-1]
        n_v = 1
        if len(v.plates) >= 2:
            n_v = v.plates[-2]
        if n_v != n_S and n_v != 1 and n_S != 1:
            raise Exception(
                "Plates of A and v are giving different number of time "
                "instances")
        n_S = max(n_v, n_S)
        if n is None:
            if n_S == 1:
                raise Exception(
                    "The number of time instances could not be determined "
                    "automatically. Give the number of time instances.")

            n = n_S + 1
        elif n_S != 1 and n_S+1 != n:
            raise Exception(
                "The number of time instances must match the number of last "
                "plates of parents:" "%d != %d+1"
                % (n, n_S))

        D = mu.dims[0][0]
        K = B.dims[0][-1]
        M = n #N.get_moments()[0]

        # Check mu
        if mu.dims != ( (D,), (D,D) ):
            raise ValueError("First parent has wrong dimensionality")
        # Check Lambda
        if Lambda.dims != ( (D,D), () ):
            raise ValueError("Second parent has wrong dimensionality")
        # Check B
        if B.dims != ( (D,K), (D,K,D,K) ):
            raise ValueError("Third parent has wrong dimensionality {0}. Should be {1}.".format(B.dims[0], (D,K)))
        if len(B.plates) == 0 or B.plates[-1] != D:
            raise ValueError("Third parent should have a last plate "
                             "equal to the dimensionality of the "
                             "system.")
        if S.dims != ( (K,), (K,K) ):
            raise ValueError("Fourth parent has wrong dimensionality %s, "
                             "should be %s"
                             % (S.dims, ( (K,), (K,K) )))
        if (len(S.plates) >= 1
            and S.plates[-1] != 1
            and S.plates[-1] != M-1):
            raise ValueError("The last plate of the fourth "
                             "parent should have length equal to one or "
                             "N-1, where N is the number of time "
                             "instances.")
        # Check v
        if v.dims != ( (), () ):
            raise Exception("Fifth parent has wrong dimensionality")
        if len(v.plates) == 0 or v.plates[-1] != D:
            raise Exception("Fifth parent should have a last plate "
                            "equal to the dimensionality of the "
                            "system.")
        if (len(v.plates) >= 2
            and v.plates[-2] != 1
            and v.plates[-2] != M-1):
            raise ValueError("The second last plate of the fifth "
                             "parent should have length equal to one or "
                             "N-1 where N is the number of time "
                             "instances.")

        distribution = VaryingGaussianMarkovChainDistribution(M, D)
        moments = GaussianMarkovChainMoments(M, D)

        parents = [mu, Lambda, B, S, v]

        dims = ( (M,D), (M,D,D), (M-1,D,D) )

        return (parents,
                kwargs,
                dims,
                cls._total_plates(kwargs.get('plates'),
                                  distribution.plates_from_parent(0, mu.plates),
                                  distribution.plates_from_parent(1, Lambda.plates),
                                  distribution.plates_from_parent(2, B.plates),
                                  distribution.plates_from_parent(3, S.plates),
                                  distribution.plates_from_parent(4, v.plates)),
                distribution,
                moments,
                parent_moments)



class SwitchingGaussianMarkovChainDistribution(TemplateGaussianMarkovChainDistribution):
    """
    Sub-classes implement distribution specific computations.
    """


    def __init__(self, N, D, K):
        self.K = K
        super().__init__(N, D)

    def compute_message_to_parent(self, parent, index, u, u_mu, u_Lambda, u_B,
                                   u_Z, u_v):
        """
        Compute a message to a parent.

        Parameters
        ----------
        index : int
            Index of the parent requesting the message.
        u : list of ndarrays
            Moments of this node.
        u_mu : list of ndarrays
            Moments of parent `mu`.
        u_Lambda : list of ndarrays
            Moments of parent `Lambda`.
        u_B : list of ndarrays
            Moments of parent `B`.
        u_Z : list of ndarrays
            Moments of parent `Z`.
        u_v : list of ndarrays
            Moments of parent `v`.
        """

        if index == 0:   # mu
            raise NotImplementedError()
        elif index == 1: # Lambda
            raise NotImplementedError()

        elif index == 2: # B, (...,K,D)x(D)

            XnXn = u[1]                   # (...,N,D,D)
            XpXn = u[2]                   # (...,N-1,D,D)
            Z = u_Z[0]                    # (...,N-1,K)
            v = misc.atleast_nd(u_v[0], 2)  # (...,N-1,D)

            # Check that there is no time-dependency in v and remove the axis
            if np.ndim(v) >= 2 and np.shape(v)[-2] > 1:
                raise ValueError("Innovation noise is time dependent")
            v = np.squeeze(v, axis=-2)

            # m0: (...,K,D,D)
            m0 = np.einsum('...nji,...nk,...i->...kij',
                           XpXn,
                           Z,
                           v)

            # m1: (...,K,D,D,D)

            m1 = np.einsum('...nij,...nk->...kij',
                           XnXn[...,:-1,:,:],
                           Z)
            m1 = -0.5 * np.einsum('...kij,...d->...kdij',
                                  m1,
                                  v)

            return [m0, m1]

        elif index == 3: # Z, (...,N-1)x(K)

            XnXn = u[1]                     # (...,N,D,D)
            XpXn = u[2]                     # (...,N-1,D,D)
            B = u_B[0]                      # (...,K,D,D)
            BB = u_B[1]                     # (...,K,D,D,D)
            v = misc.atleast_nd(u_v[0], 2)    # (...,N-1,D)
            logv = misc.atleast_nd(u_v[1], 2) # (...,N-1,D)

            # Check that there is no time-dependency in v and remove the axis
            if np.ndim(v) >= 2 and np.shape(v)[-2] > 1:
                raise ValueError("Innovation noise is time dependent")
            v = np.squeeze(v, axis=-2)
            if np.ndim(logv) >= 2 and np.shape(logv)[-2] > 1:
                raise ValueError("Innovation noise is time dependent")
            logv = np.squeeze(logv, axis=-2)

            XnXn_v = np.einsum('...nii,...i->...n',
                               XnXn[...,1:,:,:],
                               v)
            XpXn_v_B = np.einsum('...nil,...l,...kli->...nk',
                                 XpXn,
                                 v,
                                 B)
            BvB = np.einsum('...kdij,...d->...kij',
                            BB,
                            v)
            XpXp_BvB = np.einsum('...nij,...kij->...nk',
                                 XnXn[...,:-1,:,:],
                                 BvB)

            m0 = ( -0.5 * XnXn_v[...,None]
                   + XpXn_v_B
                   -0.5 * XpXp_BvB
                   +0.5 * np.sum(logv, axis=-1)[...,None,None]
                   -0.5 * self.D * np.log(2*np.pi) )

            return [m0]

        elif index == 4: # v
            raise NotImplementedError()
        elif index == 5: # N
            raise NotImplementedError()



    def compute_weights_to_parent(self, index, weights):

        if index == 0: # mu: (...)x(N,D) -> (...)x(D)
            return weights
        elif index == 1: # Lambda: (...)x(N,D) -> (...)x(D,D)
            return weights
        elif index == 2: # B: (...)x(N,D) -> (...,K,D)x(D)
            return weights[...,None,None]
        elif index == 3: # Z: (...)x(N,D) -> (...,N-1)x(K)
            return weights[...,None]
        elif index == 4: # v: (...)x(N,D) -> (...,N-1,D)x()
            return weights[...,None,None]
        else:
            raise ValueError("Invalid index")


    def compute_phi_from_parents(self, u_mu, u_Lambda, u_B, u_Z, u_v,
                                 mask=True):
        """
        Compute the natural parameters using parents' moments.

        Parameters
        ----------
        u_parents : list of list of arrays
           List of parents' lists of moments.

        Returns
        -------
        phi : list of arrays
           Natural parameters.
        dims : tuple
           Shape of the variable part of phi.

        """

        # Dimensionality of the Gaussian states
        D = np.shape(u_mu[0])[-1]

        # Number of time instances in the process
        N = self.N

        # Helpful variables (show shapes in comments)
        mu = u_mu[0]                    # (..., D)
        Lambda = u_Lambda[0]            # (..., D, D)
        B = u_B[0]                      # (..., K, D, D)
        BB = u_B[1]                     # (..., K, D, D, D)
        Z = u_Z[0]                      # (..., N-1, K)
        v = misc.atleast_nd(u_v[0], 2) # (..., N-1, D) or (..., 1, D)

        # TODO/FIXME: Take into account plates!
        plates_phi0 = misc.broadcasted_shape(np.shape(mu)[:-1],
                                             np.shape(Lambda)[:-2])
        plates_phi1 = misc.broadcasted_shape(np.shape(Lambda)[:-2],
                                             np.shape(v)[:-2],
                                             np.shape(BB)[:-4],
                                             np.shape(Z)[:-2])
        plates_phi2 = misc.broadcasted_shape(np.shape(B)[:-3],
                                             np.shape(Z)[:-2],
                                             np.shape(v)[:-2])
        phi0 = np.zeros(plates_phi0 + (N,D))
        phi1 = np.zeros(plates_phi1 + (N,D,D))
        phi2 = np.zeros(plates_phi2 + (N-1,D,D))

        # Parameters for x0
        phi0[...,0,:] = np.einsum('...ik,...k->...i', Lambda, mu)
        phi1[...,0,:,:] = Lambda


        # Diagonal blocks: -0.5 * (V_i + A_{i+1}' * V_{i+1} * A_{i+1})
        phi1[..., 1:, :, :] = v[...,None]*np.identity(D)
        if np.shape(v)[-2] > 1:
            raise Exception("This implementation is not efficient if "
                            "innovation noise is time-dependent.")
            phi1[..., :-1, :, :] += np.einsum('...kdij,...nk,...nd->...nij',
                                              BB[...,:,:,:,:],
                                              Z,
                                              v)
        else:
            # We know that S does not have the D plate so we can sum that plate
            # axis out
            v_BB = np.einsum('...kdij,...nd->...nkij',
                             BB[...,:,:,:,:],
                             v)
            phi1[..., :-1, :, :] += np.einsum('...nkij,...nk->...nij',
                                              v_BB,
                                              Z)

        phi1 *= -0.5

        # Super-diagonal blocks: 0.5 * A.T * V
        # However, don't multiply by 0.5 because there are both super- and
        # sub-diagonal blocks (sum them together)
        phi2[..., :, :, :] = np.einsum('...kji,...nk,...nj->...nij',
                                       B[...,:,:,:],
                                       Z,
                                       v)

        return (phi0, phi1, phi2)

    def compute_cgf_from_parents(self, u_mu, u_Lambda, u_B, u_Z, u_v):
        """
        Compute CGF using the moments of the parents.
        """

        u_mumu_Lambda = linalg.inner(u_Lambda[0], u_mu[1], ndim=2)
        return _compute_cgf_for_gaussian_markov_chain(u_mumu_Lambda,
                                                      u_Lambda[1],
                                                      u_v[1],
                                                      self.N)

    def plates_to_parent(self, index, plates):
        """
        Computes the plates of this node with respect to a parent.

        If this node has plates (...), the latent dimensionality is D
        and the number of time instances is N, the plates with respect
        to the parents are:
          mu:     (...)
          Lambda: (...)
          A:      (...,N-1,D)
          v:      (...,N-1,D)

        Parameters
        ----------
        index : int
            The index of the parent node to use.
        """

        if index == 0:   # mu: (...)x(N,D) -> (...)x(D)
            return plates
        elif index == 1: # Lambda: (...)x(N,D) -> (...)x(D,D)
            return plates
        elif index == 2: # B: (...)x(N,D) -> (...,K,D)x(D)
            return plates + (self.K,self.D)
        elif index == 3: # Z: (...)x(N,D) -> (...,N-1)x(K)
            return plates + (self.N-1,)
        elif index == 4: # v: (...)x(N,D) -> (...,N-1,D)x()
            return plates + (self.N-1,self.D)
        else:
            raise ValueError("Invalid parent index.")


    def plates_from_parent(self, index, plates):
        """
        Compute the plates using information of a parent node.

        If the plates of the parents are:
          mu:     (...)
          Lambda: (...)
          B:      (...,D)
          S:      (...,N-1)
          v:      (...,N-1,D)
          N:      ()
        the resulting plates of this node are (...)

        Parameters
        ----------
        index : int
            Index of the parent to use.
        """
        if index == 0:   # mu: (...)x(D) -> (...)x(N,D)
            return plates
        elif index == 1: # Lambda: (...)x(D,D) -> (...)x(N,D)
            return plates
        elif index == 2: # B: (...,K,D)x(D) -> (...)x(N,D)
            return plates[:-2]
        elif index == 3: # Z: (...,N-1)x(K) -> (...)x(N,D)
            return plates[:-1]
        elif index == 4: # v: (...,N-1,D)x() -> (...)x(N,D)
            return plates[:-2]
        else:
            raise ValueError("Invalid parent index.")




class SwitchingGaussianMarkovChain(_TemplateGaussianMarkovChain):
    r"""
    Node for Gaussian Markov chain random variables with switching dynamics.

    The node models a sequence of Gaussian variables
    :math:`\mathbf{x}_0,\ldots,\mathbf{x}_{N-1}$ with linear Markovian dynamics.
    The dynamics may change in time, which is obtained by having a set of
    matrices and at each time selecting one of them as the state dynamics
    matrix.  The graphical model can be presented as:

    .. bayesnet::

       \tikzstyle{latent} += [minimum size=40pt];

       \node[latent] (x0) {$\mathbf{x}_0$};
       \node[latent, right=of x0] (x1) {$\mathbf{x}_1$};
       \node[right=of x1] (dots) {$\cdots$};
       \node[latent, right=of dots] (xn) {$\mathbf{x}_{N-1}$};
       \edge {x0}{x1};
       \edge {x1}{dots};
       \edge {dots}{xn};

       \node[latent, above left=1 and 0.1 of x0] (mu) {$\boldsymbol{\mu}$};
       \node[latent, above right=1 and 0.1 of x0] (Lambda) {$\mathbf{\Lambda}$};
       \node[det, below=of x1] (A0) {$\mathbf{A}_0$};
       \node[right=of A0] (Adots) {$\cdots$};
       \node[det, right=of Adots] (An) {$\mathbf{A}_{N-2}$};
       \node[latent, above=of dots] (nu) {$\boldsymbol{\nu}$};
       \edge {mu,Lambda} {x0};
       \edge {nu} {x1,dots,xn};
       \edge {A0} {x1};
       \edge {Adots} {dots};
       \edge {An} {xn};

       \node[latent, below=of A0] (z0) {$z_0$};
       \node[right=of z0] (zdots) {$\cdots$};
       \node[latent, right=of zdots] (zn) {$z_{N-2}$};
       \node[latent, left=of z0] (B) {$\mathbf{B}_k$};
       \edge {B} {A0, Adots, An};
       \edge {z0} {A0};
       \edge {zdots} {Adots};
       \edge {zn} {An};

       \plate {K} {(B)} {$k=0,\ldots,K-1$};

    where :math:`\boldsymbol{\mu}` and :math:`\mathbf{\Lambda}` are the mean and
    the precision matrix of the initial state, :math:`\boldsymbol{\nu}` is the
    precision of the innovation noise, and :math:`\mathbf{A}_n` are the state
    dynamics matrix obtained by selecting one of the matrices
    :math:`\{\mathbf{B}_k\}^{K-1}_{k=0}` at each time.  The selections are
    provided by :math:`z_n\in\{0,\ldots,K-1\}`.  The probability distribution is

    .. math::

       p(\mathbf{x}_0, \ldots, \mathbf{x}_{N-1}) = p(\mathbf{x}_0)
       \prod^{N-1}_{n=1} p(\mathbf{x}_n | \mathbf{x}_{n-1})

    where

    .. math::

       p(\mathbf{x}_0) &= \mathcal{N}(\mathbf{x}_0 | \boldsymbol{\mu}, \mathbf{\Lambda})
       \\
       p(\mathbf{x}_n|\mathbf{x}_{n-1}) &= \mathcal{N}(\mathbf{x}_n |
       \mathbf{A}_{n-1}\mathbf{x}_{n-1}, \mathrm{diag}(\boldsymbol{\nu})),
       \quad \text{for } n=1,\ldots,N-1,
       \\
       \mathbf{A}_n &= \mathbf{B}_{z_n}, \quad \text{for }
       n=0,\ldots,N-2.


    Parameters
    ----------

    mu : Gaussian-like node or (...,D)-array
        :math:`\boldsymbol{\mu}`, mean of :math:`x_0`, :math:`D`-dimensional
        with plates (...)

    Lambda : Wishart-like node or (...,D,D)-array
        :math:`\mathbf{\Lambda}`, precision matrix of :math:`x_0`,
        :math:`D\times D` -dimensional with plates (...)

    B : Gaussian-like node or (...,D,D,K)-array
        :math:`\{\mathbf{B}_k\}_{k=0}^{K-1}`, a set of state dynamics matrix,
        :math:`D \times K`-dimensional with plates (...,D)

    Z : categorical-like node or (...,N-1)-array
        :math:`\{z_0,\ldots,z_{N-2}\}`, time-dependent selection,
        :math:`K`-categorical with plates (...,N-1)

    nu : gamma-like node or (...,D)-array
        :math:`\boldsymbol{\nu}`, diagonal elements of the precision of the
        innovation process, plates (...,D)

    n : int, optional
        :math:`N`, the length of the chain. Must be given if :math:`\mathbf{Z}`
        does not have plates over the time domain (which would not make sense).

    See also
    --------

    Gaussian, GaussianARD, Wishart, Gamma, GaussianMarkovChain,
    VaryingGaussianMarkovChain, Categorical, CategoricalMarkovChain

    Notes
    -----

    Equivalent model block can be constructed with :class:`GaussianMarkovChain`
    by explicitly using :class:`Gate` to select the state dynamics matrix.
    However, that approach is not very efficient for large datasets because it
    does not utilize the structure of :math:`\mathbf{A}_n`, thus it explicitly
    computes huge moment arrays.
    """


    def __init__(self, mu, Lambda, B, Z, nu, n=None, **kwargs):
        """
        Create SwitchingGaussianMarkovChain node.
        """
        super().__init__(mu, Lambda, B, Z, nu, n=n, **kwargs)


    @classmethod
    def _constructor(cls, mu, Lambda, B, Z, v, n=None, **kwargs):
        """
        Constructs distribution and moments objects.

        Compute the dimensions of phi and u.

        The plates and dimensions of the parents should be:
        mu:     (...)                    and D-dimensional
        Lambda: (...)                    and D-dimensional
        B:      (...,K,D)                and D-dimensional
        Z:      (...,N-1)                and K-dimensional
        v:      (...,1,D) or (...,N-1,D) and 0-dimensional

        Check that the dimensionalities of the parents are proper.
        """

        # Infer the number of dynamic matrices
        B = cls._ensure_moments(B, GaussianMoments, ndim=1)
        K = B.plates[-2]

        mu = cls._ensure_moments(mu, GaussianMoments, ndim=1)
        Lambda = cls._ensure_moments(Lambda, WishartMoments, ndim=1)
        Z = cls._ensure_moments(Z, CategoricalMoments, categories=K)
        v = cls._ensure_moments(v, GammaMoments)

        parent_moments = (
            mu._moments,
            Lambda._moments,
            B._moments,
            Z._moments,
            v._moments
        )

        # Infer the length of the chain
        n_Z = 1
        if len(Z.plates) == 0:
            raise ValueError("Z must have temporal axis on plates")
        n_Z = Z.plates[-1]
        n_v = 1
        if len(v.plates) >= 2:
            n_v = v.plates[-2]
        if n_v != n_Z and n_v != 1 and n_Z != 1:
            raise Exception(
                "Plates of Z and v are giving different number of time "
                "instances")
        n_Z = max(n_v, n_Z)
        if n is None:
            if n_Z == 1:
                raise Exception(
                    "The number of time instances could not be determined "
                    "automatically. Give the number of time instances.")

            n = n_Z + 1
        elif n_Z != 1 and n_Z+1 != n:
            raise Exception(
                "The number of time instances must match the number of last "
                "plates of parents:" "%d != %d+1"
                % (n, n_Z))


        D = mu.dims[0][0]
        K = Z.dims[0][0]
        M = n #N.get_moments()[0]

        # Check mu
        if mu.dims != ( (D,), (D,D) ):
            raise ValueError("First parent has wrong dimensionality")
        # Check Lambda
        if Lambda.dims != ( (D,D), () ):
            raise ValueError("Second parent has wrong dimensionality")
        # Check B
        if B.dims != ( (D,), (D,D) ):
            raise ValueError("Third parent has wrong dimensionality")
        if len(B.plates) < 2 or B.plates[-2:] != (K,D):
            raise ValueError("Third parent should have a last plate "
                             "equal to the dimensionality of the "
                             "system.")
        if Z.dims != ( (K,), ):
            raise ValueError("Fourth parent has wrong dimensionality %s, "
                             "should be %s"
                             % (Z.dims, ( (K,), )))
        if Z.plates[-1] != M-1:
            raise ValueError("The last plate of the fourth "
                             "parent should have length equal to one or "
                             "N-1, where N is the number of time "
                             "instances.")
        # Check v
        if v.dims != ( (), () ):
            raise Exception("Fifth parent has wrong dimensionality")
        if len(v.plates) == 0 or v.plates[-1] != D:
            raise Exception("Fifth parent should have a last plate "
                            "equal to the dimensionality of the "
                            "system.")
        if (len(v.plates) >= 2
            and v.plates[-2] != 1
            and v.plates[-2] != M-1):
            raise ValueError("The second last plate of the fifth "
                             "parent should have length equal to one or "
                             "N-1 where N is the number of time "
                             "instances.")


        dims = ( (M,D), (M,D,D), (M-1,D,D) )
        distribution = SwitchingGaussianMarkovChainDistribution(M, D, K)
        moments = GaussianMarkovChainMoments(M, D)

        parents = [mu, Lambda, B, Z, v]

        return (parents,
                kwargs,
                dims,
                cls._total_plates(kwargs.get('plates'),
                                  distribution.plates_from_parent(0, mu.plates),
                                  distribution.plates_from_parent(1, Lambda.plates),
                                  distribution.plates_from_parent(2, B.plates),
                                  distribution.plates_from_parent(3, Z.plates),
                                  distribution.plates_from_parent(4, v.plates)),
                distribution,
                moments,
                parent_moments)


class _MarkovChainToGaussian(Deterministic):
    """
    Transform a Gaussian Markov chain node into a Gaussian node.

    This node is deterministic.
    """

    def __init__(self, X, **kwargs):

        X = self._ensure_moments(X, GaussianMarkovChainMoments)

        D = X.dims[0][-1]

        self._moments = GaussianMoments((D,))
        self._parent_moments = (X._moments,)

        super().__init__(X, dims=self._moments.dims, **kwargs)


    def _plates_to_parent(self, index):
        """
        Return the number of plates to the parent node.

        Normally, the parent sees the same number of plates as the
        node itself.  However, now that one of the variable dimensions
        of the parents corresponds to a plate in this node, it is
        necessary to fix it here: the last plate is ignored when
        calculating plates with respect to the parent.

        Parent:
        Plates = (...)
        Dims = (N, ...)
        This node:
        Plates = (..., N)
        Dims = (...)
        """
        return self.plates[:-1]

    def _plates_from_parent(self, index):
        # Sub-classes may want to overwrite this if they manipulate plates
        if index != 0:
            raise ValueError("Invalid parent index.")

        parent = self.parents[0]
        plates = parent.plates + (parent.dims[0][0],)
        return plates

    def _compute_moments(self, u):
        """
        Transform the moments of a GMC to moments of a Gaussian.

        There is no need to worry about the plates and variable
        dimensions because the child node is free to interpret the
        axes as it pleases.  However, the Gaussian moments contain
        only <X(n)> and <X(n)*X(n)> but not <X(n-1)X(n)>, thus the
        last moment is discarded.
        """

        # Get the moments from the parent Gaussian Markov Chain
        #u = self.parents[0].get_moments() #message_to_child()

        # Send only moments <X(n)> and <X(n)X(n)> but not <X(n-1)X(n)>
        return u[:2]


    def _compute_weights_to_parent(self, index, weights):
        # Remove the last axis of the mask
        if np.ndim(weights) >= 1:
            weights = np.sum(weights, axis=-1)
        return weights


    @staticmethod
    def _compute_message_to_parent(index, m_children, *u_parents):
        """
        Transform a message to a Gaussian into a message to a GMC.

        The messages to a Gaussian are almost correct, there are only
        two minor things to be done:

        1) The last plate is changed into a variable/time dimension.
        Because a message mask is applied for plates only, the last
        axis of the mask must be applied to the message because the
        last plate is changed to a variable/time dimension.

        2) Because the message does not contain <X(n-1)X(n)> part,
        we'll put the last/third message to None meaning that it is
        empty.

        Parameters
        ----------
        index : int
            Index of the parent requesting the message.
        u_parents : list of list of ndarrays
            List of parents' moments.

        Returns
        -------
        m : list of ndarrays
            Message as a list of arrays.
        mask : boolean ndarray
            Mask telling which plates should be taken into account.
        """

        # Add the third empty message
        return [m_children[0], m_children[1], None]


# Make use of the converter
GaussianMarkovChainMoments.add_converter(GaussianMoments,
                                         _MarkovChainToGaussian)