How to copy CPTs

Posted on Wed 21 February 2024 in notebooks

In [1]:
import pyAgrum as gum
import pyAgrum.lib.notebook as gnb

Let say you have 2 Bayesian networks:

In [2]:
bn1=gum.fastBN("A->B<-C;D->E<-F",2)
bn2=gum.fastBN("C->B<-A;G->H<-I",2)
gnb.sideBySide(bn1,bn2,captions=["BN1","BN2"])
G C C B B C->B F F E E F->E D D D->E A A A->B
BN1
G C C B B C->B G G H H G->H I I I->H A A A->B
BN2

And you would like the CPTs of $E$ in BN1; and $H$ and $B$ in BN2 to be the same as $B$ in BN1. For now, they are (randomly) different :

In [3]:
gnb.sideBySide(bn1.cpt("B"),bn1.cpt("E"),bn2.cpt("H"),bn2.cpt("B"),
               captions=["bn1.cpt(B)","bn1.cpt(E)","bn2.cpt(H)","bn2.cpt(B)"])
B
C
A
0
1
0
0
0.56850.4315
1
0.04650.9535
1
0
0.51250.4875
1
0.83240.1676

bn1.cpt(B)
E
F
D
0
1
0
0
0.66830.3317
1
0.03630.9637
1
0
0.20090.7991
1
0.15160.8484

bn1.cpt(E)
H
I
G
0
1
0
0
0.69730.3027
1
0.43370.5663
1
0
0.97400.0260
1
0.59430.4057

bn2.cpt(H)
B
A
C
0
1
0
0
0.47000.5300
1
0.33840.6616
1
0
0.10200.8980
1
0.56970.4303

bn2.cpt(B)

Even for $B$ in BN2, this is not trivial :

  • the variables are not the same even if they have the same names : they belong to 2 different BNs.
  • Note also that the order of the CPT is not the same : the column C and A are reversed in bn1.cpt(B) and bn2.cpt(B).
In [4]:
# using the names to map variables
bn2.cpt("B").fillWith(bn1.cpt("B"))

# using the order in "E" to organize the mapping of variables (E<->B,D<->A,F<->C)
#print(bn1.cpt("E").names)
#('E', 'D', 'F')
bn1.cpt("E").fillWith(bn2.cpt("B"),["B","A","C"])

# being explicit about the mapping (I<->C,G<->A,H<->B)
bn2.cpt("H").fillWith(bn2.cpt("B"),{"I":"C",
                                    "G":"A",
                                    "H":"B"})

gnb.sideBySide(bn1.cpt("B"),bn1.cpt("E"),bn2.cpt("H"),bn2.cpt("B"),
               captions=["bn1.cpt(B)","bn1.cpt(E)","bn2.cpt(H)","bn2.cpt(B)"])
B
C
A
0
1
0
0
0.56850.4315
1
0.04650.9535
1
0
0.51250.4875
1
0.83240.1676

bn1.cpt(B)
E
F
D
0
1
0
0
0.56850.4315
1
0.04650.9535
1
0
0.51250.4875
1
0.83240.1676

bn1.cpt(E)
H
I
G
0
1
0
0
0.56850.4315
1
0.04650.9535
1
0
0.51250.4875
1
0.83240.1676

bn2.cpt(H)
B
A
C
0
1
0
0
0.56850.4315
1
0.51250.4875
1
0
0.04650.9535
1
0.83240.1676

bn2.cpt(B)