Commit 09cdacfa authored by Hendrik Buschmeier's avatar Hendrik Buschmeier
Browse files

Made examples and tests work again.

parent 4843b81d
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from primo.core import BayesNet
from primo.reasoning import DiscreteNode
from primo.networks import BayesianNetwork
from primo.nodes import DiscreteNode
import numpy
bn = BayesNet()
bn = BayesianNetwork()
burglary = DiscreteNode("Burglary", ["Intruder","Safe"])
alarm = DiscreteNode("Alarm", ["Ringing", "Silent","Kaputt"])
earthquake = DiscreteNode("Earthquake", ["Shaking", "Calm"])
......
from primo.core import BayesianDecisionNetwork
from primo.decision import DecisionNode
from primo.decision import UtilityNode
from primo.reasoning import DiscreteNode
from primo.decision.make_decision import MakeDecision
from primo.networks import BayesianDecisionNetwork
from primo.nodes import DecisionNode
from primo.nodes import UtilityNode
from primo.nodes import DiscreteNode
from primo.inference.decision import MakeDecision
import numpy
......
......@@ -6,15 +6,15 @@ the probability of evidence.
@author: djohn
"""
from primo.core import BayesNet
from primo.reasoning import DiscreteNode
from primo.reasoning.factorelemination import EasiestFactorElimination
from primo.reasoning.factorelemination import FactorTreeFactory
from primo.networks import BayesianNetwork
from primo.nodes import DiscreteNode
from primo.inference.factor import EasiestFactorElimination
from primo.inference.factor import FactorTreeFactory
import numpy
#==============================================================================
#Builds the example BayesNet
bn = BayesNet()
bn = BayesianNetwork()
burglary = DiscreteNode("Burglary", ["Intruder","Safe"])
alarm = DiscreteNode("Alarm", ["Ringing", "Silent"])
earthquake = DiscreteNode("Earthquake", ["Shaking", "Calm"])
......
......@@ -6,18 +6,17 @@ the probability of evidence.
@author: djohn, mbaum
"""
from primo.core import BayesNet
from primo.reasoning import DiscreteNode
from primo.reasoning.density import ProbabilityTable
#from primo.reasoning.factorelemination import EasiestFactorElimination
from primo.reasoning.factorelemination import FactorTreeFactory
from primo.reasoning import MCMC
from primo.reasoning import EvidenceEqual as EvEq
from primo.networks import BayesianNetwork
from primo.nodes import DiscreteNode
from primo.densities import ProbabilityTable
from primo.inference.factor import FactorTreeFactory
from primo.inference.mcmc import MCMC
from primo.evidence import EvidenceEqual as EvEq
import numpy
#==============================================================================
#Builds the example BayesNet
bn = BayesNet()
bn = BayesianNetwork()
burglary = DiscreteNode("Burglary", ["Intruder","Safe"])
alarm = DiscreteNode("Alarm", ["Ringing", "Silent"])
earthquake = DiscreteNode("Earthquake", ["Shaking", "Calm"])
......@@ -119,7 +118,7 @@ print "EarthquakeFT: " + str(factorTree.calculate_marginal([earthquake]))
mcmc_ask=MCMC(bn)
mcmc_ask=MCMC(bn,1000)
print "====MCMC===="
......
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from primo.core import BayesNet
from primo.core import DynamicBayesNet
from primo.core import TwoTBN
from primo.reasoning import DiscreteNode
import primo.reasoning.particlebased.ParticleFilterDBN as pf
import numpy
from primo.utils import XMLBIF
import random
import numpy
from primo.networks import BayesianNetwork
from primo.networks import DynamicBayesianNetwork
from primo.networks import TwoTBN
from primo.nodes import DiscreteNode
import primo.inference.particlefilter as pf
from primo.io import XMLBIF
# Construct a DynmaicBayesianNetwork
dbn = DynamicBayesNet()
B0 = BayesNet()
dbn = DynamicBayesianNetwork()
B0 = BayesianNetwork()
twoTBN = TwoTBN(XMLBIF.read("Robot_Localization.xmlbif"))
# Configure TwoTBN
......
......@@ -6,12 +6,14 @@ This example shows how to create a BayesNet
@author: djohn
"""
from primo.core import BayesNet
from primo.reasoning import DiscreteNode
import numpy
from primo.networks import BayesianNetwork
from primo.nodes import DiscreteNode
#initialize a new BayesNet
bn = BayesNet()
bn = BayesianNetwork()
#create Nodes with Name and the possible values
burglary = DiscreteNode("Burglary", ["Intruder","Safe"])
......@@ -61,6 +63,6 @@ john_calls.set_probability(0.01,[(alarm,"Silent"),(john_calls,"Calling")])
john_calls.set_probability(0.99,[(alarm,"Silent"),(john_calls,"Not Calling")])
#draws the BayesNet
#bn.draw()
bn.draw()
import numpy
from primo.core import BayesNet
from primo.reasoning import GaussNode
from primo.networks import BayesianNetwork
from primo.nodes import ContinuousNodeFactory
age = GaussNode("Plant_age")
cnf = ContinuousNodeFactory()
age = cnf.createGaussNode("Plant_age")
#parameterization
age_b0=numpy.array([4])
......
from primo.core import BayesNet
from primo.reasoning import ContinuousNodeFactory
from primo.reasoning.density import ExponentialParameters
from primo.reasoning.density import BetaParameters
from primo.reasoning.density import GaussParameters
from primo.reasoning.density import NDGauss
from primo.reasoning import MCMC
from primo.reasoning.convergence_test import ConvergenceTestSimpleCounting
from primo.reasoning import EvidenceEqual as EvEqual
from primo.reasoning import EvidenceLower as EvLower
from primo.networks import BayesianNetwork
from primo.nodes import ContinuousNode
from primo.nodes import ContinuousNodeFactory
from primo.densities import ExponentialParameters
from primo.densities import BetaParameters
from primo.densities import GaussParameters
from primo.densities import NDGauss
from primo.inference.mcmc import MCMC
from primo.inference.mcmc import ConvergenceTestSimpleCounting
from primo.evidence import EvidenceEqual as EvEqual
from primo.evidence import EvidenceLower as EvLower
import numpy
......@@ -26,7 +27,7 @@ import numpy
#Construct some simple BayesianNetwork.
#topology
bn = BayesNet()
bn = BayesianNetwork()
cnf=ContinuousNodeFactory()
age = cnf.createExponentialNode("Plant_age")
height = cnf.createGaussNode("Plant_height")
......
from primo.core import BayesNet
from primo.reasoning import ContinuousNodeFactory
from primo.reasoning.density import ExponentialParameters
from primo.reasoning.density import BetaParameters
from primo.reasoning.density import GaussParameters
from primo.reasoning.density import NDGauss
from primo.reasoning import MCMC
from primo.networks import BayesianNetwork
from primo.nodes import ContinuousNodeFactory
from primo.densities import ExponentialParameters
from primo.densities import BetaParameters
from primo.densities import GaussParameters
from primo.densities import NDGauss
from primo.inference.mcmc import MCMC
from primo.reasoning import EvidenceEqual as EvEqual
from primo.reasoning import EvidenceInterval as EvInterval
from primo.evidence import EvidenceEqual as EvEqual
from primo.evidence import EvidenceInterval as EvInterval
import numpy
......@@ -16,7 +16,7 @@ import numpy
#it has grown up to (+noise)
bn = BayesNet()
bn = BayesianNetwork()
cnf=ContinuousNodeFactory()
#create the nodes
......
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from primo.core import BayesNet
from primo.reasoning import DiscreteNode
from primo.reasoning.density import ProbabilityTable
from primo.reasoning import MCMC
from primo.reasoning import EvidenceEqual as EvEq
from primo.reasoning import GibbsTransitionModel
from primo.networks import BayesianNetwork
from primo.nodes import DiscreteNode
from primo.densities import ProbabilityTable
from primo.inference.mcmc import MCMC
from primo.evidence import EvidenceEqual as EvEq
from primo.inference.mcmc import GibbsTransitionModel
import numpy
import pdb
......@@ -19,7 +19,7 @@ import pdb
#-Maximum a-posteriori hypothesis
#Construct some simple BayesianNetwork
bn = BayesNet()
bn = BayesianNetwork()
burglary = DiscreteNode("Burglary", ["Intruder","Safe"])
alarm = DiscreteNode("Alarm", ["Ringing", "Silent","Destroyed"])
......
<?xml version="1.0" encoding="US-ASCII"?>
<!--
Bayesian network in XMLBIF v0.3 (BayesNet Interchange Format)
Produced by SamIam http://reasoning.cs.ucla.edu/samiam
Output created May 13, 2013 12:09:30 PM
-->
<BIF VERSION="0.3">
<NETWORK>
<NAME>bayesiannetwork</NAME>
<VARIABLE TYPE="nature">
<NAME>x</NAME>
<OUTCOME>p0</OUTCOME>
<OUTCOME>p1</OUTCOME>
<OUTCOME>p2</OUTCOME>
<OUTCOME>p3</OUTCOME>
<OUTCOME>p4</OUTCOME>
<OUTCOME>p5</OUTCOME>
<OUTCOME>p6</OUTCOME>
<OUTCOME>p7</OUTCOME>
<OUTCOME>p8</OUTCOME>
<OUTCOME>p9</OUTCOME>
<PROPERTY>position = (477, -200)</PROPERTY>
</VARIABLE>
<VARIABLE TYPE="nature">
<NAME>door</NAME>
<OUTCOME>True</OUTCOME>
<OUTCOME>False</OUTCOME>
<PROPERTY>position = (479, -65)</PROPERTY>
</VARIABLE>
<VARIABLE TYPE="nature">
<NAME>x0</NAME>
<OUTCOME>p0</OUTCOME>
<OUTCOME>p1</OUTCOME>
<OUTCOME>p2</OUTCOME>
<OUTCOME>p3</OUTCOME>
<OUTCOME>p4</OUTCOME>
<OUTCOME>p5</OUTCOME>
<OUTCOME>p6</OUTCOME>
<OUTCOME>p7</OUTCOME>
<OUTCOME>p8</OUTCOME>
<OUTCOME>p9</OUTCOME>
<PROPERTY>position = (260, -200)</PROPERTY>
</VARIABLE>
<DEFINITION>
<FOR>x</FOR>
<GIVEN>x0</GIVEN>
<TABLE>
0.05 0.9 0.05 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.05 0.9 0.05 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.05 0.9 0.05 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.05 0.9 0.05 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.05 0.9 0.05 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.05 0.9 0.05 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.05 0.9 0.05 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.05 0.9 0.05
0.05 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.05 0.9
0.9 0.05 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.05
</TABLE>
</DEFINITION>
<DEFINITION>
<FOR>door</FOR>
<GIVEN>x</GIVEN>
<TABLE>0.01 0.99 0.99 0.01 0.01 0.99 0.99 0.01 0.01 0.99 0.01 0.99 0.01 0.99 0.99 0.01 0.01 0.99 0.01 0.99 </TABLE>
</DEFINITION>
<DEFINITION>
<FOR>x0</FOR>
<TABLE>0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 </TABLE>
</DEFINITION>
</NETWORK>
</BIF>
<?xml version="1.0" encoding="US-ASCII"?>
<!--
Bayesian network in XMLBIF v0.3 (BayesNet Interchange Format)
Produced by SamIam http://reasoning.cs.ucla.edu/samiam
Output created May 13, 2013 12:09:30 PM
-->
<BIF VERSION="0.3">
<NETWORK>
<NAME>bayesiannetwork</NAME>
<VARIABLE TYPE="nature">
<NAME>x</NAME>
<OUTCOME>p0</OUTCOME>
<OUTCOME>p1</OUTCOME>
<OUTCOME>p2</OUTCOME>
<OUTCOME>p3</OUTCOME>
<OUTCOME>p4</OUTCOME>
<OUTCOME>p5</OUTCOME>
<OUTCOME>p6</OUTCOME>
<OUTCOME>p7</OUTCOME>
<OUTCOME>p8</OUTCOME>
<OUTCOME>p9</OUTCOME>
<PROPERTY>position = (477, -200)</PROPERTY>
</VARIABLE>
<VARIABLE TYPE="nature">
<NAME>door</NAME>
<OUTCOME>True</OUTCOME>
<OUTCOME>False</OUTCOME>
<PROPERTY>position = (479, -65)</PROPERTY>
</VARIABLE>
<VARIABLE TYPE="nature">
<NAME>x0</NAME>
<OUTCOME>p0</OUTCOME>
<OUTCOME>p1</OUTCOME>
<OUTCOME>p2</OUTCOME>
<OUTCOME>p3</OUTCOME>
<OUTCOME>p4</OUTCOME>
<OUTCOME>p5</OUTCOME>
<OUTCOME>p6</OUTCOME>
<OUTCOME>p7</OUTCOME>
<OUTCOME>p8</OUTCOME>
<OUTCOME>p9</OUTCOME>
<PROPERTY>position = (260, -200)</PROPERTY>
</VARIABLE>
<DEFINITION>
<FOR>x</FOR>
<GIVEN>x0</GIVEN>
<TABLE>
0.1 0.73 0.1 0.01 0.01 0.01 0.01 0.01 0.01 0.01
0.01 0.1 0.73 0.1 0.01 0.01 0.01 0.01 0.01 0.01
0.01 0.01 0.1 0.73 0.1 0.01 0.01 0.01 0.01 0.01
0.01 0.01 0.01 0.1 0.73 0.1 0.01 0.01 0.01 0.01
0.01 0.01 0.01 0.01 0.1 0.73 0.1 0.01 0.01 0.01
0.01 0.01 0.01 0.01 0.01 0.1 0.73 0.1 0.01 0.01
0.01 0.01 0.01 0.01 0.01 0.01 0.1 0.73 0.1 0.01
0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.1 0.73 0.1
0.1 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.1 0.73
0.73 0.1 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.1
</TABLE>
</DEFINITION>
<DEFINITION>
<FOR>door</FOR>
<GIVEN>x</GIVEN>
<TABLE>0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.1 0.9 0.9 0.1 0.1 0.9 0.1 0.9 </TABLE>
</DEFINITION>
<DEFINITION>
<FOR>x0</FOR>
<TABLE>0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 0.10000000000000002 </TABLE>
</DEFINITION>
</NETWORK>
</BIF>
This diff is collapsed.
# -*- coding: utf-8 -*-
import copy
import math
import random
import numpy
from scipy.stats
import scipy.stats
from primo.nodes
import primo.nodes
from primo.util import weighted_random
class Density(object):
'''TODO: write doc'''
......@@ -116,7 +116,7 @@ class Beta(Density):
self.q=parameters.q
def add_variable(self, variable):
if( not isinstance(variable,ContinuousNode.ContinuousNode)):
if( not isinstance(variable,primo.nodes.ContinuousNode)):
raise Exception("Tried to add Variable as parent, but is not a ContinuousNode")
self.p[variable]=0.0
self.q[variable]=0.0
......@@ -223,7 +223,7 @@ class Exponential(Density):
to be parents because of their value range. Instead it should be evaluated
if they can yield parameters for this distribution that are permitted. This
can in any case happen under bad influence coefficients'''
if( not isinstance(variable,ContinuousNode.ContinuousNode)):
if( not isinstance(variable,primo.nodes.ContinuousNode)):
raise Exception("Tried to add Variable as parent, but is not a ContinuousNode")
self.b[variable]=0.0
......
import copy
import operator
import networkx as nx
import primo.densities
......@@ -177,7 +180,7 @@ class FactorTreeFactory(object):
for n in allNodes:
sortNodeList.append((len(n.get_cpd().get_variables()),n))
#sort node list
sortNodeList = sorted(sortNodeList,key=itemgetter(0),reverse=True)
sortNodeList = sorted(sortNodeList,key=operator.itemgetter(0),reverse=True)
sortNodeList = zip(*sortNodeList)
sortNodeList = list(sortNodeList[1])
#root node with the most variables
......
import copy
import random
from primo.reasoning.convergence_test import ConvergenceTestSimpleCounting
from primo.util import weighted_random
class MCMC(object):
......@@ -123,19 +121,6 @@ class MCMC(object):
state[var]=var.sample_global(state, evidence)
return state
def weighted_random(weights):
'''
Implements roulette-wheel-sampling.
@param weights: A List of float-values.
@returns: Index of the selected entity
'''
counter = random.random() * sum(weights)
for i,w in enumerate(weights):
counter -= w
if counter <=0:
return i
class GibbsTransitionModel(object):
'''
Implements Gibbs-sampling. Can be used to constuct a Markov Chain and is
......
......@@ -5,6 +5,7 @@ import random
import time
import primo.networks
from primo.util import weighted_random
class Particle(object):
'''
......@@ -38,13 +39,6 @@ class Particle(object):
'''
pass
def weighted_random(weights):
counter = random.random() * sum(weights)
for i, w in enumerate(weights):
counter -= w
if counter <= 0:
return i
def wighted_sample_with_replacement(samples = [], weights = [], N = 0):
'''
The population is resampled to generate a new population of N samples.
......@@ -90,7 +84,7 @@ def weighted_sample(network, evidence = {}):
'''
w = 1.0
state = {}
if not isinstance(network, primo.network.BayesianNetwork):
if not isinstance(network, primo.networks.BayesianNetwork):
raise Exception("The given network is not an instance of BayesNet.")
nodes = network.get_nodes_in_topological_sort()
......
# -*- coding: utf-8 -*-
import xml.dom.minidom as minidom
from primo.core import BayesNet
from primo.core import Node
from primo.reasoning import DiscreteNode
import re
import xml.dom.minidom as minidom
import primo.networks
import primo.nodes
class XMLBIF(object):
......@@ -35,7 +35,7 @@ class XMLBIF(object):
self.newl = newl
self.addindent = addindent
self.root = minidom.Document()
if isinstance(network, BayesNet):
if isinstance(network, primo.networks.BayesianNetwork):
self.network = network
else:
raise Exception("Given network is not a BayesNet.")
......@@ -82,7 +82,7 @@ class XMLBIF(object):
for node_name in self.network.node_lookup:
current_node = self.network.node_lookup[node_name]
if not isinstance(current_node, DiscreteNode):
if not isinstance(current_node, primo.nodes.DiscreteNode):
raise Exception("Node " + str(current_node) + " is not a DiscreteNode.")
node_tag = self.create_node_tag(current_node)
tag_net.appendChild(node_tag)
......@@ -139,7 +139,7 @@ class XMLBIF(object):
Returns a XMLBIF conform "variable" tag
'''
if not isinstance(node, Node):
if not isinstance(node, primo.nodes.Node):
raise Exception("Node " + str(node) + " is not a Node.")
tag_var = minidom.Element("VARIABLE")
tag_own = minidom.Element("NAME")
......@@ -228,7 +228,7 @@ class XMLBIF(object):
This method is used internally. Do not call it outside this class.
'''
network = BayesNet()
network = primo.networks.BayesianNetwork()
bif_nodes = root.getElementsByTagName("BIF")
if len(bif_nodes) != 1:
raise Exception("More than one or none <BIF>-tag in document.")
......@@ -248,7 +248,7 @@ class XMLBIF(object):
for position_node in variable_node.getElementsByTagName("PROPERTY"):
position = XMLBIF.get_node_position_from_text(position_node.childNodes)
break
new_node = DiscreteNode(name, value_range)
new_node = primo.nodes.DiscreteNode(name, value_range)
new_node.position = position
network.add_node(new_node)
definition_nodes = network_nodes[0].getElementsByTagName("DEFINITION")
......
import networkx as nx
import primo.densities
import primo.nodes
class BayesianNetwork(object):
......@@ -152,20 +153,20 @@ class BayesianDecisionNetwork(BayesianNetwork):
return False
decisionNodeList = []
for node in self.get_all_nodes():
if isinstance(node, DecisionNode):
if isinstance(node, primo.nodes.DecisionNode):
decisionNodeList.append(node)
return all([nx.has_path(self.graph, x, y) == True for x in decisionNodeList for y in decisionNodeList])
def add_node(self, node):
if isinstance(node, Node):
if isinstance(node, primo.nodes.Node):
if node.name in self.node_lookup.keys():
raise Exception("Node name already exists in Bayesnet: "+node.name)
if isinstance(node, DiscreteNode):
if isinstance(node, primo.nodes.DiscreteNode):
self.random_nodes.append(node)
elif isinstance(node, UtilityNode):
elif isinstance(node, primo.nodes.UtilityNode):
self.utility_nodes.append(node)
elif isinstance(node, DecisionNode):
elif isinstance(node, primo.nodes.DecisionNode):
self.decision_nodes.append(node)
else:
raise Exception("Tried to add a node which the Bayesian Decision Network can not work with")
......@@ -193,9 +194,9 @@ class BayesianDecisionNetwork(BayesianNetwork):
node_from -- Node from where the edge shall begin
node_to -- Node where the edge shall end
"""