Graph

Variable

Variable.

class pybbn.graph.variable.Variable(id, name, values)

Bases: object

A variable.

__init__(id, name, values)

Ctor.

Parameters:
  • id – Numeric identifier. e.g. 0

  • name – Name. e.g. ‘a’

  • values – Array of values. e.g. [‘on’, ‘off’]

to_dict()

Gets a JSON serializable dictionary representation.

Returns:

Dictionary.

Node

Nodes. There are many types: nodes, cliques, belief network nodes and separation sets.

class pybbn.graph.node.BbnNode(variable, probs)

Bases: Node

A BBN node.

get_weight()

Gets the weight, which is the number of values.

Returns:

Weight.

to_dict()

Gets a JSON serializable dictionary representation.

Returns:

Dictionary.

class pybbn.graph.node.Clique(nodes)

Bases: Node

A clique.

contains(id)

Checks if this clique contains the specified ID.

Parameters:

id – Numeric id.

Returns:

A boolean indicating if the specified id exists in this clique.

get_node_ids()

Gets the node IDs in this clique.

Returns:

An array of numeric ids of the nodes in this clique.

get_sep_set(that)

Creates a separation-set from this node and the one passed in. The separation-set is composed of the intersection of the two cliques. If this node has [0, 1, 2] and the node passed in has [1, 2, 3], then the separation set will be [1, 2].

Parameters:

that – Clique.

Returns:

Separation-set.

get_sid()

Gets the string ID of this clique.

Returns:

String ID composed of the sorted corresponding variables in each node.

get_weight()

Gets the weight of this clique; the weight is product of the weights of the nodes in this clique.

Returns:

Weight.

intersects(that)

Gets intersection information.

Parameters:

that – Clique.

Returns:

Tuple where first item is a boolean indicating if there is any intersection, second item are the IDs in this clique, third item are the IDs of that clique and last item are IDs common to both Cliques.

is_marked()

Checks if this clique is marked.

Returns:

A boolean indicating if the clique is marked.

is_superset(that)

Checks if this clique is a superset of that clique.

Parameters:

that – Clique.

Returns:

A boolean indicating if this clique is a superset of the clique passed in.

mark()

Marks this clique.

unmark()

Unmarks this clique.

class pybbn.graph.node.Node(id)

Bases: object

A node.

add_metadata(k, v)

Adds metadata.

Parameters:
  • k – Key. Typically a string value.

  • v – Value. Any object.

class pybbn.graph.node.SepSet(left, right, lhs=None, rhs=None, intersection=None)

Bases: Clique

Separation-set.

property cost

Gets the cost.

Returns:

The cost.

get_cost()

The cost is the sum of the weights of the cliques connected to this separation-set.

Returns:

Cost.

get_mass()

The mass is the number of nodes in this separation-set.

Returns:

Mass.

property is_empty

Checks if the cliques in this separation set have an empty intersection.

Returns:

A boolean indicating if there is no intersection.

property mass

Gets the mass.

Returns:

The mass.

Edge

Edges. There are two main types: undirected and directed. However, many other types exists as well.

class pybbn.graph.edge.Edge(i, j, type)

Bases: object

Edge.

__init__(i, j, type)

Ctor.

Parameters:
  • i – Node.

  • j – Node.

  • type – Edge type.

property key

Key used for map.

Returns:

Key.

class pybbn.graph.edge.EdgeType(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Edge type.

DIRECTED = 2
UNDIRECTED = 1
class pybbn.graph.edge.JtEdge(sep_set)

Bases: Edge

Junction tree edge. This is basically a hyper-edge.

__init__(sep_set)

Ctor.

Parameters:

sep_set – Separation set.

get_lhs_edge()

Gets a JtEdge. e.g. left – sep_set.

Returns:

JtEdge.

get_rhs_edge()

Gets a JtEdge. e.g. right – sep_set.

Returns:

JtEdge.

class pybbn.graph.edge.SepSetEdge(i, j)

Bases: Edge

Separation set.

__init__(i, j)

Ctor.

Parameters:
  • i – Node.

  • j – Node.

Graph

Basic graphs.

class pybbn.graph.graph.Graph

Bases: object

Graph.

__init__()

Ctor.

add_edge(edge)

Adds an edge.

Parameters:

edge – Edge.

Returns:

This graph.

add_node(node)

Adds a node.

Parameters:

node – Node.

Returns:

This graph.

edge_exists(id1, id2)

Checks if the specified edge id1 – id2 exists.

Parameters:
  • id1 – Node id.

  • id2 – Node id.

Returns:

A boolean indicating if the specified edge exists.

get_edges()

Gets all the edges.

Returns:

List of edges.

get_neighbors(id)

Gets the neighbors of the specified node.

Parameters:

id – Node id.

Returns:

Set of neighbors of the specified node.

get_node(id)

Gets the node associated with the specified id.

Parameters:

id – Node id.

Returns:

Node.

get_nodes()

Gets all the nodes.

Returns:

List of nodes.

remove_node(id)

Removes a node from the graph.

Parameters:

id – Node id.

class pybbn.graph.graph.Ug

Bases: Graph

Undirected graph.

__init__()

Ctor.

Directed Acyclic Graph

Directed acyclic graphs.

class pybbn.graph.dag.Bbn

Bases: Dag

BBN.

__init__()

Ctor.

static from_csv(path)

Converts the BBN in CSV format to a BBN. :param path: Path to CSV file. :return: BBN.

static from_dict(d)

Creates a BBN from a dictionary (deserialized JSON).

Parameters:

d – Dictionary.

Returns:

BBN.

static from_json(path)

Deserializes BBN from JSON.

Parameters:

path – Path.

Returns:

BBN.

get_parents_ordered(id)

Gets the IDs of the specified node ordered.

Parameters:

id – ID of node.

Returns:

List of parent IDs sorted.

static to_csv(bbn, path)

Converts the specified BBN to CSV format.

Parameters:
  • bbn – BBN.

  • path – Path to file.

Returns:

None.

static to_dict(bbn)

Gets a JSON serializable dictionary representation.

Parameters:

bbn – BBN.

Returns:

Dictionary.

static to_dne(bbn, bnet_name='network')
static to_json(bbn, path)

Serializes BBN to JSON.

Parameters:
  • bbn – BBN.

  • path – Path.

Returns:

None.

class pybbn.graph.dag.BbnUtil

Bases: object

BBN utility.

static get_huang_graph()

Gets the Huang reference BBN graph.

Returns:

BBN.

static get_simple()

Gets a simple BBN graph.

Returns:

BBN.

class pybbn.graph.dag.Dag

Bases: Graph

Directed acyclic graph.

__init__()

Ctor.

edge_exists(id1, id2)

Checks if a directed edge exists between the specified id. e.g. id1 -> id2

Parameters:
  • id1 – Node id.

  • id2 – Node id.

Returns:

A boolean indicating if a directed edge id1 -> id2 exists.

get_children(node_id)

Gets the children IDs of the specified node.

Parameters:

node_id – Node id.

Returns:

Array of children ids.

get_i2n()

Gets a map of node identifiers to names.

Returns:

Dictionary.

get_n2i()

Gets a map of node names to identifiers.

Returns:

Dictionary.

get_parents(id)

Gets the parent IDs of the specified node.

Parameters:

id – Node id.

Returns:

Array of parent ids.

to_nx_graph()

Converts this DAG to a NX DiGraph for visualization.

Returns:

A tuple, where the first item is the NX DiGraph and the second items are the node labels.

class pybbn.graph.dag.PathDetector(graph, start, stop)

Bases: object

Detects path between two nodes.

__init__(graph, start, stop)

Ctor.

Parameters:
  • graph – DAG.

  • start – Start node id.

  • stop – Stop node id.

exists()

Checks if a path exists.

Returns:

True if a path exists, otherwise, false.

Partially Directed Acylic Graph

Partially directed acylic graphs.

class pybbn.graph.pdag.PathDetector(graph, start, stop)

Bases: object

Detects path between two nodes.

__init__(graph, start, stop)

Ctor.

Parameters:
  • graph – Pdag.

  • start – Start node id.

  • stop – Stop node id.

exists()

Checks if a path exists.

Returns:

True if a path exists, otherwise, false.

class pybbn.graph.pdag.Pdag

Bases: Graph

Partially directed acyclic graph.

__init__()

Ctor.

directed_edge_exists(id1, id2)

Checks if the specified edge id1 -> id2 exists.

Parameters:
  • id1 – Node id.

  • id2 – Node id.

Returns:

A boolean indicating if the edge exists.

edge_exists(id1, id2)

Checks if the specified edge id1 – id2 exists.

Parameters:
  • id1 – Node id.

  • id2 – Node id.

Returns:

A boolean indicating if the edge exists.

get_out_nodes(id)

Gets all the out nodes for the node with the specified id. Out nodes are all connected nodes that are not parents (do not have a directed arc into the specified node).

Parameters:

id – Node id.

Returns:

Array of out node ids.

get_parents(id)

Gets the parent of the specified node id.

Parameters:

id – Node id.

Returns:

Array of parent ids.

Join Tree

Join trees or junction trees.

class pybbn.graph.jointree.ChangeType(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Change type.

NONE = 1
RETRACTION = 3
UPDATE = 2
class pybbn.graph.jointree.Evidence(node, type)

Bases: object

Evidence.

__init__(node, type)

Ctor.

Parameters:
  • node – BBN node.

  • type – EvidenceType.

add_value(value, likelihood)

Adds a value.

Parameters:
  • value – Value.

  • likelihood – Likelihood.

Returns:

This evidence.

compare(potentials)

Compares this evidence with previous ones.

Parameters:

potentials – Map of potentials.

Returns:

The ChangeType from the comparison.

validate()

Validates this evidence.

  • virtual evidence: each likelihood must be in the range [0, 1].

  • finding evidence: all likelihoods must be exactly 1.0 or 0.0.

  • observation evidence: exactly one likelihood is 1.0 and all others must be 0.0.

class pybbn.graph.jointree.EvidenceBuilder

Bases: object

Evidence builder.

__init__()

Ctor.

build()

Builds an evidence.

Returns:

Evidence.

with_evidence(val, likelihood)

Adds evidence.

Parameters:
  • val – Value.

  • likelihood – Likelihood.

Returns:

Builder.

with_node(node)

Adds a BBN node.

Parameters:

node – BBN node.

Returns:

Builder.

with_type(type)

Adds the EvidenceType.

Parameters:

type – EvidenceType.

Returns:

Builder.

class pybbn.graph.jointree.EvidenceType(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Evidence type.

FINDING = 2
OBSERVATION = 3
UNOBSERVE = 4
VIRTUAL = 1
class pybbn.graph.jointree.JoinTree

Bases: Ug

Join tree.

__init__()

Ctor.

add_edge(edge)

Adds an JtEdge.

Parameters:

edge – JtEdge.

Returns:

This join tree.

add_potential(clique, potential)

Adds a potential associated with the specified clique.

Parameters:
  • clique – Clique.

  • potential – Potential.

Returns:

This join tree.

find_cliques_with_node_and_parents(id)

Finds all cliques in this junction tree having the specified node and its parents.

Parameters:

id – Node id.

Returns:

Array of cliques.

static from_dict(d)

Converts a dictionary to a junction tree.

Parameters:

d – Dictionary.

Returns:

Junction tree.

get_bbn_node(id)

Gets the BBN node associated with the specified id.

Parameters:

id – Node id.

Returns:

BBN node or None if no such node exists.

get_bbn_node_and_parents()

Gets a map of nodes and its parents.

Returns:

Map. Keys are node ID and values are list of nodes.

get_bbn_node_by_name(name)

Gets the BBN node associated with the specified name.

Parameters:

name – Node name.

Returns:

BBN node or None if no such node exists.

get_bbn_nodes()

Gets all the BBN nodes in this junction tree.

Returns:

List of BBN nodes.

get_bbn_potential(node)

Gets the potential associated with the specified BBN node.

Parameters:

node – BBN node.

Returns:

Potential.

get_change_type(evidences)

Gets the change type associated with the specified list of evidences.

Parameters:

evidences – List of evidences.

Returns:

ChangeType.

get_cliques()

Gets all the cliques in this junction tree.

Returns:

Array of cliques.

get_evidence(node, value)

Gets the evidence associated with the specified BBN node and value.

Parameters:
  • node – BBN node.

  • value – Value.

Returns:

Potential (the evidence).

get_flattened_edges()

Gets all the edges “flattened” out. Since separation-sets are really hyper-edges, this method breaks separation-sets into two edges.

Returns:

Array of edges.

get_posteriors()

Gets the posterior for all nodes.

Returns:

Map. Keys are node names; values are map of node values to posterior probabilities.

get_sep_sets()

Gets all the separation sets in this junction tree.

Returns:

Array of separation sets.

get_unobserved_evidence(node)

Gets the unobserved evidences associated with the specified node.

Parameters:

node – BBN node.

Returns:

Evidence.

set_listener(listener)

Sets the listener.

Parameters:

listener – JoinTreeListener.

set_observation(evidence)

Sets a single observation.

Parameters:

evidence – Evidence.

Returns:

This join tree.

static to_dict(jt, bbn)

Converts a junction tree to a serializable dictionary.

Parameters:
  • jt – Junction tree.

  • bbn – BBN.

Returns:

Dictionary.

unmark_cliques()

Unmarks the cliques.

unobserve(nodes)

Unobserves a list of nodes.

Parameters:

nodes – List of nodes.

Returns:

This join tree.

unobserve_all()

Unobserves all BBN nodes.

Returns:

This join tree.

update_bbn_cpts(cpts)

Updates the CPTs of the BBN nodes.

Parameters:

cpts – Dictionary of CPTs. Keys are ids of BBN node and values are new CPTs.

Returns:

None

update_evidences(evidences)

Updates this join tree with the list of specified evidence.

Parameters:

evidences – List of evidences.

Returns:

This join tree.

class pybbn.graph.jointree.JoinTreeListener

Bases: object

Interface like class used for listening to a join tree.

evidence_retracted(join_tree)

Evidence is retracted.

Parameters:

join_tree – Join tree.

evidence_updated(join_tree)

Evidence is updated.

Parameters:

join_tree – Join tree.

class pybbn.graph.jointree.PathDetector(graph, start, stop)

Bases: object

Detects path between two nodes.

__init__(graph, start, stop)

Ctor.

Parameters:
  • graph – Join tree.

  • start – Start node id.

  • stop – Stop node id.

exists()

Checks if a path exists.

Returns:

True if a path exists, otherwise, false.

Factory

Factories.

class pybbn.graph.factory.Factory

Bases: object

Factory to convert other API BBNs into py-bbn.

static from_data(structure, df)

Creates a BBN.

Parameters:
  • structure – A dictionary where keys are names of children and values are list of parent names.

  • df – A dataframe.

Returns:

BBN.

static from_libpgm_discrete_dictionary(d)

Converts a libpgm discrete network as specified by a dictionary into a py-bbn one. Look at https://pythonhosted.org/libpgm/unittestdict.html.

Parameters:

d – A dictionary representing a libpgm discrete network.

Returns:

py-bbn BBN.

static from_libpgm_discrete_json(j)

Converts a libpgm discrete network as specified by a JSON string into a py-bbn one. Look at https://pythonhosted.org/libpgm/unittestdict.html.

Parameters:

j – String representing JSON.

Returns:

py-bbn BBN.

static from_libpgm_discrete_object(bn)

Converts a libpgm discrete network object into a py-bbn one.

Parameters:

bn – libpgm discrete BBN.

Returns:

py-bbn BBN.

Potential

Potentials.

class pybbn.graph.potential.Potential

Bases: object

Potential.

__init__()

Ctor.

add_entry(entry)

Adds a PotentialEntry.

Parameters:

entry – PotentialEntry.

Returns:

This potential.

get_matching_entries(entry)

Gets all potential entries matching the specified entry.

Parameters:

entry – PotentialEntry.

Returns:

Array of matching potential entries.

static to_dict(potentials)

Converts potential to dictionary for easy validation.

Parameters:

potentials – Potential.

Returns:

Dictionary representation. Keys are entries and values are probabilities.

class pybbn.graph.potential.PotentialEntry

Bases: object

Potential entry.

__init__()

Ctor.

add(k, v)

Adds a node id and its value.

Parameters:
  • k – Node id.

  • v – Value.

Returns:

This potential entry.

duplicate()

Duplicates this entry.

Returns:

PotentialEntry.

get_entry_keys()

Gets entry keys sorted.

Returns:

List of tuples. First tuple is id of variable and second tuple is value of variable.

get_kv()

Gets key-value pair that may be used for storage in dictionary.

Returns:

Key-value pair.

matches(that)

Checks if this potential entry matches the specified one. A match is determined with all the keys and their associated values in the potential entry passed in matches this one.

Parameters:

that – PotentialEntry.

Returns:

class pybbn.graph.potential.PotentialUtil

Bases: object

Potential util.

static divide(numerator, denominator)

Divides two potentials.

Parameters:
  • numerator – Potential.

  • denominator – Potential.

Returns:

Potential.

static get_cartesian_product(lists)

Gets the cartesian product of a list of lists of values. For example, if the list is

  • [ [‘on’, ‘off’], [‘on’, ‘off’] ]

then the result will be a list of the following

  • [ ‘on’, ‘on’]

  • [ ‘on’, ‘off’ ]

  • [ ‘off’, ‘on’ ]

  • [ ‘off’, ‘off’ ]

Parameters:

lists – List of list of values.

Returns:

Cartesian product of values.

static get_potential(node, parents)

Gets the potential associated with the specified node and its parents.

Parameters:
  • node – BBN node.

  • parents – Parents of the BBN node (that themselves are also BBN nodes).

Returns:

Potential.

static get_potential_from_nodes(nodes)

Gets a potential from a list of BBN nodes.

Parameters:

nodes – Array of BBN nodes.

Returns:

Potential.

static is_zero(d)

Checks if the specified value is 0.0.

Parameters:

d – Value.

Returns:

A boolean indicating if the value is zero.

static marginalize_for(join_tree, clique, nodes)

Marginalizes the specified clique’s potential over the specified nodes.

Parameters:
  • join_tree – Join tree.

  • clique – Clique.

  • nodes – List of BBN nodes.

Returns:

Potential.

static merge(node, parents)

Merges the nodes into one array.

Parameters:
  • node – BBN node.

  • parents – BBN parent nodes.

Returns:

Array of BBN nodes.

static multiply(bigger, smaller)

Multiplies two potentials. Order matters.

Parameters:
  • bigger – Bigger potential.

  • smaller – Smaller potential.

static normalize(potential)

Normalizes the potential (make sure they sum to 1.0).

Parameters:

potential – Potential.

Returns:

Potential.

static pass_single_message(join_tree, x, s, y)

Single message pass from x – s – y (from x to s to y).

Parameters:
  • join_tree – Join tree.

  • x – Clique.

  • s – Separation-set.

  • y – Clique.

Utilities

Utilities to make life easier.

class pybbn.graph.util.IdUtil

Bases: object

ID util.

static hash_string(s)

Hashes the string.

Parameters:

s – String.

Returns:

Hash value.