pyAgrum Code samples

Create a Bayesian Network

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
"""
How to create a BN with pyAgrum
"""

import pyAgrum as gum

bn = gum.BayesNet()

for nom in ["x","y","z"]:
  bn.add(gum.LabelizedVariable(nom, "", 2))

bn.addArc("x", "y")
bn.addArc("y", "z")

#this should create an impossible arc (since a bn is a DAG)
#bn.addArc("z", "x")

Details of a Bayesian Network

 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
def showBN(bn):
  print('---------------------------------')
  print(bn.property("name"))

  print('---------------------------------')
  print(bn)

  print('---------------------------------')

  l = [len(bn.variable(i)) for i in bn.nodes()]
  print('variables domainSize : min={0} max={1}'.format(min(l), max(l)))

  print('parents : max={0}'.format(max([len(bn.parents(i)) for i in bn.nodes()])))
  print('---------------------------------')

  for i in bn.nodes():
    print('{0} : {1}'.format(i, str(bn.variable(i))))
  print('---------------------------------')

  for (i,j) in bn.arcs():
    print('{0}->{1}'.format(bn.variable(i).name(), bn.variable(j).name()))
  print('---------------------------------')

#Load the file alarm.dsl
bn = gum.loadBN("alarm.dsl")

showBN(bn)

Access a Bayesian Network parameters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import pyAgrum as gum

bn = gum.BayesNet()
bn.loadBIF("bn.bif")

print(bn.variable(0).name())
# a

print(bn.cpt(0))
#[[[ 0.48319     0.51681   ]
#  [ 0.108427    0.89157301]
#  [ 0.43582699  0.56417298]]
#
# [[ 0.0250064   0.974994  ]
#  [ 0.677037    0.322963  ]
#  [ 0.78677201  0.213228  ]]]

print(bn.cpt(0)[{'e':0,'f':1}])
# [ 0.0250064  0.974994 ]

Instantiation loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import pyAgrum as gum

bn = gum.BayesNet()
bn.loadBIF("bn.bif")

p_a = bn.cpt(0)
i = gum.Instantiation(p_a)
i.setFirst()
s = 0.0;
while (not i.end()):
  print(i)
  s += p_a.get(i)
  i.inc()
  print(s)

loadBN with listener

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os
import pyAgrum as gum

from pyAgrum.lib.utils.progress_bar import ProgressBar

def doLoadBN(s):
  # you could simply do that
  # bn = gum.loadBN(s)
  # but listeners are fun !!

  title = os.path.basename(s) + " (" + '{0:,d}'.format(os.path.getsize(s)/1024).replace(',',' ') + " Ko)"
  progressbar = ProgressBar(title, 0, 100, mode='dynamic', char='-')

  def local_update(percent):
    progressbar.update_amount(percent)
    progressbar.display()
    if percent == 100:
      print()

  return gum.loadBN(s,local_update)

bn=doLoadBN("asia.bif")

Save a Bayesian Network

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
bn = gum.BayesNet('exo1')

#sexe = 0(H)/1(F)
#daltonisme = 0(D) / 1 (nonD)

sexe, daltonisme = [bn.add(gum.LabelizedVar(nom,'',2)) for nom in 'sexe daltonisme'.split()]
bn.addArc(sexe, daltonisme)

bn.cpt(sexe)[:] = [0.5, 0.5]

bn.cpt(daltonisme)[0,:] = [0.08, 0.92]
bn.cpt(daltonisme)[1,:] = [0.005,0.995]

bn.saveBIF("exo1.bif")

for line in open("exo1.bif"):
  print line,

print("for gum.loadBN or gum.saveBN, possible files ext are ="+gum.availableBNExts())
gum.saveBN(bn,"exo1.dsl")
for line in open("exo1.dsl"):
  print line,

Noisy OR

 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
The real QMR-DT model is copyright, but we can create a random QMR-like model as follows.
"""

import pyAgrum as gum
import random

def create_qmr(nD,nF,density):
  """
  create qmr BN using

  nD = number of disease
  nF = number of findings
  density = proba for disease i to be linked to finding j
  """
  name = "qmr%d-%d-%f"%(nD, nF, density)
  bn = gum.BayesNet(name)

  lDis = [bn.add(gum.LabelizedVariable("D%4d"%i,"D%4d"%i,2)) for i in range(nD)]

  # create noiyOR nodes with random leaks
  lFind = [bn.addNoisyOR(gum.LabelizedVariable("F%d"%i,"F%d"%i,2),random.uniform(0.1,0.9)) for i in range(nF)]

  for node in lDis:
    prior = random.uniform(0.01, 0.99)
    bn.cpt(node)[:] = [prior, 1 - prior]

  for i in lDis:
    for j in lFind:
      if random.random() < density:
        # add new cause i to noisyOR node j with random weight
        bn.addWeightedArc(i, j, random.uniform(0.1, 0.9))
  return bn

  if __name__ == "__main__":
    from gumLib.bn2graph import pdfize
    print("building qmr")
    bn1 = create_qmr(60, 60, 0.1)
    print("generating pdf")
    pdfize(bn, bn.property('name'))