pyAgrum Code samples

Create a Bayesian Network

  """
  How to create a BN with pyAgrum
  """

  import pyAgrum as gum

  bn = gum.BayesNet()

  x, y, z = ([bn.add(gum.LabelizedVar(nom, "", 2)) for nom in "x y z".split()])
  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

  """
  description of a BN
  """
  import pyAgrum as gum

  def showBN(bn):
    print('---------------------------------')
    print(bn.property("name"))

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

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

    l = [len(bn.variable(i)) for i in bn.ids()]
    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.ids()])))
    print('---------------------------------')

    for i in bn.ids():
      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

  """
  How to access the parameters of a BN
  """

  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

  """
  How to use Instantiation to iterate in a cpt
  """

  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

  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

  import pyAgrum as gum

  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

  """
  see http://www.ncbi.nlm.nih.gov/pubmed/1762578
  or
  http://www.cs.cmu.edu/afs/cs/project/jair/pub/volume10/jaakkola99a-html/node2.html

  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'))