Functions from pyAgrum

Useful functions in pyAgrum

pyAgrum.about()

about() for pyAgrum

pyAgrum.randomBN(*, n=5, names=None, ratio_arc=1.2, domain_size=2)

Creates a random BN using the (forced) keyword parameters. This function use pyAgrum.BNGenerator but the random variables will be named w.r.t. a topological order.

Examples

>>> bn=gum.randomBN()
>>> bn=gum.randomBN(n=10)
>>> bn=gum.randomBN(names="ABCDEF")
>>> bn=gum.randomBN(names=["Asia","Tuberculosis","Smoking"],ratio_arc=1.5,domain_size=3)

Warning

This function has only keyword parameters (no positional).

Parameters
  • n (int) – number of nodes

  • names (List[str]) – list of names

  • ratio_arc (float) – number of arcs = n * ratio_arc

  • domain_size (int) – the domain size for the variables.

Return type

BayesNet

Returns

pyAgrum.BayesNet

pyAgrum.getPosterior(model, *, target, evs=None)

Compute the posterior of a single target (variable) in a BN given evidence

getPosterior uses a VariableElimination inference. If more than one target is needed with the same set of evidence or if the same target is needed with more than one set of evidence, this function is not relevant since it creates a new inference engine every time it is called.

Parameters
  • bn (pyAgrum.BayesNet or pyAgrum.MarkovRandomField) – The probabilistic Graphical Model

  • target (string or int) – variable name or id (forced keyword argument)

  • evs (Dict[name|id:val, name|id : List[ val1, val2 ], ...]. (optional forced keyword argument)) – the (hard and soft) evidence

Returns

posterior (pyAgrum.Potential or other)

pyAgrum.generateSample(bn, n=1, name_out=None, show_progress=False, with_labels=True, random_order=True)

generate a CSV file of samples from a bn.

Parameters
  • bn (pyAgrum.BayesNet) – the Bayes Net from which the sample is generated

  • n (int) – the number of samples

  • name_out (str) – the name for the output csv filename. If name_out is None, a pandas.DataFrame is generated

  • show_progress (bool) – if True, show a progress bar. Default is False

  • with_labels (bool) – if True, use the labels of the modalities of variables in the csv. If False, use their ids. Default is True

  • random_order (bool) – if True, the columns in the csv are randomized sorted. Default is True

Returns

the log2-likelihood of the generated base or if name_out is None, the couple (generated pandas.DataFrame,log2-likelihood)

Return type

float|Tuple[pandas.DataFrame,float]

Quick specification of (randomly parameterized) graphical models

aGrUM/pyAgrum offers a so-called “fast” syntax that allows to quickly and compactly specify prototypes of graphical models. These fastPrototype aGrUM’s methods have also been wrapped in functions of pyAgrum.

gum.fastBN("A[10]->B<-C{top|middle|bottom};B->D")

The type of the random variables can be specifiy with different syntaxes:

Note

  • If the dot-like string contains such a specification more than once for a variable, the first specification will be used.

  • the CPTs are randomly generated.

pyAgrum.fastBN(structure, domain_size=2)
Create a Bayesian network with a dot-like syntax which specifies:
  • the structure ‘a->b->c;b->d<-e;’,

  • the type of the variables with different syntax (cf documentation).

Examples

>>> import pyAgrum as gum
>>> bn=gum.fastBN('A->B[1,3]<-C{yes|No}->D[2,4]<-E[1,2.5,3.9]',6)
Parameters
  • structure (str) – the string containing the specification

  • domain_size (int) – the default domain size for variables

Returns

the resulting bayesian network

Return type

pyAgrum.BayesNet

pyAgrum.fastMRF(structure, domain_size=2)
Create a Markov random field with a modified dot-like syntax which specifies:
  • the structure ‘a-b-c;b-d;c-e;’ where each chain ‘a-b-c’ specifies a factor,

  • the type of the variables with different syntax (cf documentation).

Examples

>>> import pyAgrum as gum
>>> bn=gum.fastMRF('A--B[1,3]--C{yes|No};C--D[2,4]--E[1,2.5,3.9]',6)
Parameters
  • structure (str) – the string containing the specification

  • domain_size (int) – the default domain size for variables

Returns

the resulting Markov random field

Return type

pyAgrum.MarkovRandomField

pyAgrum.fastID(structure, domain_size=2)
Create an Influence Diagram with a modified dot-like syntax which specifies:
  • the structure and the type of the variables following fast syntax,

  • a prefix for the type of node (chance/decision/utiliy nodes):

    • a : a chance node named ‘a’ (by default)

    • $a : a utility node named ‘a’

    • *a : a decision node named ‘a’

Examples

>>> import pyAgrum as gum
>>> bn=gum.fastID('A->B[1,3]<-*C{yes|No}->$D<-E[1,2.5,3.9]',6)
Parameters
  • structure (str) – the string containing the specification

  • domain_size (int) – the default domain size for variables

Returns

the resulting Influence Diagram

Return type

pyAgrum.InfluenceDiagram

Input/Output for Bayesian networks

pyAgrum.availableBNExts()

Give the list of all formats known by pyAgrum to save a Bayesian network.

Returns

a string which lists all suffixes for supported BN file formats.

pyAgrum.loadBN(filename, listeners=None, verbose=False, **opts)

load a BN from a file with optional listeners and arguments

Parameters
  • filename (str) – the name of the input file

  • listeners (List[object]) – list of functions to execute when listening

  • verbose (bool) – whether to print or not warning messages

  • system (str) – (for O3PRM) name of the system to flatten in a BN

  • classpath (List[str]) – (for O3PRM) list of folders containing classes

Returns

a BN from a file using one of the availableBNExts() suffixes.

Return type

pyAgrum.BayesNet

Notes

Listeners could be added in order to monitor its loading.

Examples

>>> import pyAgrum as gum
>>>
>>> # creating listeners
>>> def foo_listener(progress):
>>>    if progress==200:
>>>        print(' BN loaded ')
>>>        return
>>>    elif progress==100:
>>>        car='%'
>>>    elif progress%10==0:
>>>        car='#'
>>>    else:
>>>        car='.'
>>>    print(car,end='',flush=True)
>>>
>>> def bar_listener(progress):
>>>    if progress==50:
>>>        print('50%')
>>>
>>> # loadBN with list of listeners
>>> gum.loadBN('./bn.bif',listeners=[foo_listener,bar_listener])
>>> # .........#.........#.........#.........#..50%
>>> # .......#.........#.........#.........#.........#.........% | bn loaded
pyAgrum.saveBN(bn, filename, allowModificationWhenSaving=None)

save a BN into a file using the format corresponding to one of the availableWriteBNExts() suffixes.

Parameters
  • bn (pyAgrum.BayesNet) – the BN to save

  • filename (str) – the name of the output file

  • allowModificationWhenSaving (bool) – whether syntax errors in the BN should throw a FatalError or can be corrected. Also controlled by pyAgrum.config[“BN”,”allow_modification_when_saving”].

Input/Output for Markov random fields

pyAgrum.availableMNExts()

Give the list of all formats known by pyAgrum to save a Markov random field.

Returns

a string which lists all suffixes for supported MRF file formats.

Return type

str

pyAgrum.loadMN(filename, listeners=None, verbose=False)

load a MRF from a file with optional listeners and arguments

Parameters
  • filename (str) – the name of the input file

  • listeners (List[Object]) – list of functions to execute

  • verbose (bool) – whether to print or not warning messages

Returns

  • pyAgrum.MarkovRandomField – a MRF from a file using one of the availableMNExts() suffixes.

  • Listeners could be added in order to monitor its loading.

Examples

>>> import pyAgrum as gum
>>>
>>> # creating listeners
>>> def foo_listener(progress):
>>>    if progress==200:
>>>        print(' BN loaded ')
>>>        return
>>>    elif progress==100:
>>>        car='%'
>>>    elif progress%10==0:
>>>        car='#'
>>>    else:
>>>        car='.'
>>>    print(car,end='',flush=True)
>>>
>>> def bar_listener(progress):
>>>    if progress==50:
>>>        print('50%')
>>>
>>> # loadBN with list of listeners
>>> gum.loadMN('./bn.uai',listeners=[foo_listener,bar_listener])
>>> # .........#.........#.........#.........#..50%
>>> # .......#.........#.........#.........#.........#.........% | bn loaded
pyAgrum.saveMN(mn, filename)

save a MRF into a file using the format corresponding to one of the availableWriteMNExts() suffixes.

Parameters

Input for influence diagram

pyAgrum.availableIDExts()

Give the list of all formats known by pyAgrum to save a influence diagram.

Returns

a string which lists all suffixes for supported ID file formats.

Return type

str

pyAgrum.loadID(filename)

read a gum.InfluenceDiagram from a ID file

Parameters

filename (str) – the name of the input file

Returns

the InfluenceDiagram

Return type

pyAgrum.InfluenceDiagram

pyAgrum.saveID(infdiag, filename)

save an ID into a file using the format corresponding to one of the availableWriteIDExts() suffixes.

Parameters