Example #1
0
    def generate_BayesNet(root):
        '''
        Generate a BayesNet from a XMLBIF.

        This method is used internally. Do not call it outside this class.
        '''
        network = BayesNet()
        bif_nodes = root.getElementsByTagName("BIF")
        if len(bif_nodes) != 1:
            raise Exception("More than one or none <BIF>-tag in document.")
        network_nodes = bif_nodes[0].getElementsByTagName("NETWORK")
        if len(network_nodes) != 1:
            raise Exception("More than one or none <NETWORK>-tag in document.")
        variable_nodes = network_nodes[0].getElementsByTagName("VARIABLE")
        for variable_node in variable_nodes:
            name = "Unnamed node"
            value_range = []
            position = (0, 0)
            for name_node in variable_node.getElementsByTagName("NAME"):
                name = XMLBIF.get_node_text(name_node.childNodes)
                break
            for output_node in variable_node.getElementsByTagName("OUTCOME"):
                value_range.append(XMLBIF.get_node_text(output_node.childNodes))
            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.position = position
            network.add_node(new_node)
        definition_nodes = network_nodes[0].getElementsByTagName("DEFINITION")
        for definition_node in definition_nodes:
            node = None
            for for_node in definition_node.getElementsByTagName("FOR"):
                name = XMLBIF.get_node_text(for_node.childNodes)
                node = network.get_node(name)
                break
            if node == None:
                continue
            for given_node in definition_node.getElementsByTagName("GIVEN"):
                parent_name = XMLBIF.get_node_text(given_node.childNodes)
                parent_node = network.get_node(parent_name)
                node.announce_parent(parent_node)
            for table_node in definition_node.getElementsByTagName("TABLE"):
                table = XMLBIF.get_node_table_from_text(table_node.childNodes)
                node.get_cpd().get_table().T.flat = table
                break

        return network
 def test_complicated_multi(self):
     n1 = DiscreteNode("Some Node", [True, False])
     n2 = DiscreteNode("Second Node" , [True, False,"noIdea"])
     
     cpt1 = numpy.array([2,3])
     cpt2 = numpy.array([5,7,9])
     
     n1.set_probability_table(cpt1,[n1])
     n2.set_probability_table(cpt2,[n2])
     
     c3 = n1.get_cpd().multiplication(n2.get_cpd())
     c3 = n1.get_cpd().multiplication(c3)
     
     cptN = numpy.array([[20, 28, 36],[45, 63, 81]])        
     numpy.testing.assert_array_equal(c3.table,cptN)
 def test_easy_values(self):
     n1 = DiscreteNode("Some Node", [True, False])
     n2 = DiscreteNode("Second Node" , [True, False])
     
     cpt1 = numpy.array([2,3])
     cpt2 = numpy.array([5,7])
     
     n1.set_probability_table(cpt1,[n1])
     n2.set_probability_table(cpt2,[n2])
     
     s = n1.get_cpd().multiplication(n2.get_cpd())
     
     cptN = numpy.array([[10,14],[15,21]])
     
     numpy.testing.assert_array_equal(s.table,cptN)
     self.assertEqual(s.variables[0],n1)
    def test_easy_shape(self):
        n1 = DiscreteNode("Some Node", [True, False])
        n2 = DiscreteNode("Second Node" , [True, False])

        s = n1.get_cpd().multiplication(n2.get_cpd())

        self.assertEqual(s.table.shape, (2,2));

        s = n1.get_cpd().multiplication(n1.get_cpd())
        self.assertEqual(s.table.shape,(2,))
 def test_easy_marginalize(self):
     n1 = DiscreteNode("Some Node", [True, False])
     n2 = DiscreteNode("Second Node" , [True, False, "other"])
     
     cpt1 = numpy.array([2,3])
     cpt2 = numpy.array([5,7,3])
     
     n1.set_probability_table(cpt1,[n1])
     n2.set_probability_table(cpt2,[n2])
     
     s = n1.get_cpd().multiplication(n2.get_cpd())
     s =s.marginalization(n2)
     
     print s.table
     
     cptN = numpy.array([30,45])        
     
     numpy.testing.assert_array_equal(s.table,cptN)
     self.assertEqual(s.variables[0],n1)
from primo.decision import UtilityNode
from primo.reasoning import DiscreteNode
from primo.decision.make_decision import MakeDecision

import numpy

'''Example of a Bayesian Decision Network found in 
Barber, David - Bayesian Reasoning and Machine Learning
Page 111ff
'''

bdn = BayesianDecisionNetwork()

education = DecisionNode("education", ["do Phd", "no Phd"])
cost = UtilityNode("cost")
prize = DiscreteNode("prize", ["prize", "no prize"])
income = DiscreteNode("income", ["low", "average", "high"])
benefit = UtilityNode("benefit")
startup = DecisionNode("startUp", ["do startUp", "no startUp"])
costStartup = UtilityNode("costStartup")

#bdn.add_node(startup)
bdn.add_node(education)
bdn.add_node(cost)
bdn.add_node(prize)
bdn.add_node(income)
bdn.add_node(benefit)
bdn.add_node(startup)
bdn.add_node(costStartup)

bdn.add_edge(education, cost)
Example #7
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from primo.core import BayesNet
from primo.reasoning import DiscreteNode
import numpy

bn = BayesNet()
burglary = DiscreteNode("Burglary", ["Intruder", "Safe"])
alarm = DiscreteNode("Alarm", ["Ringing", "Silent", "Kaputt"])
earthquake = DiscreteNode("Earthquake", ["Shaking", "Calm"])
john_calls = DiscreteNode("John calls", ["Calling", "Not Calling"])
mary_calls = DiscreteNode("Mary calls", ["Calling", "Not Calling"])


bn.add_node(burglary)
bn.add_node(alarm)
bn.add_node(earthquake)
bn.add_node(john_calls)
bn.add_node(mary_calls)


bn.add_edge(burglary, alarm)
bn.add_edge(earthquake, alarm)
bn.add_edge(alarm, john_calls)
bn.add_edge(alarm, mary_calls)


burglary.set_probability(0.2, [(burglary, "Intruder")])

alarm.set_probability(0.1, [(alarm, "Ringing"), (burglary, "Safe"), (earthquake, "Calm")])
Example #8
0
 def setUp(self):
     # Create BayesNet
     self.bn = BayesNet();
     # Create Nodes
     weather0 = DiscreteNode("Weather0", ["Sun", "Rain"])
     weather = DiscreteNode("Weather", ["Sun", "Rain"])
     ice_cream_eaten = DiscreteNode("Ice Cream Eaten", [True, False])
     # Add nodes
     self.bn.add_node(weather0)
     self.bn.add_node(weather)
     self.bn.add_node(ice_cream_eaten)
     # Add edges
     self.bn.add_edge(weather, ice_cream_eaten)
     self.bn.add_edge(weather0, weather);
     # Set probabilities
     cpt_weather0 = numpy.array([.6, .4])
     weather0.set_probability_table(cpt_weather0, [weather0])
     cpt_weather = numpy.array([[.7, .5],
                                [.3, .5]])
     weather.set_probability_table(cpt_weather, [weather0, weather])
     ice_cream_eaten.set_probability(.9, [(ice_cream_eaten, True), (weather, "Sun")])
     ice_cream_eaten.set_probability(.1, [(ice_cream_eaten, False), (weather, "Sun")])
     ice_cream_eaten.set_probability(.2, [(ice_cream_eaten, True), (weather, "Rain")])
     ice_cream_eaten.set_probability(.8, [(ice_cream_eaten, False), (weather, "Rain")])
Example #9
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from primo.core import BayesNet
from primo.reasoning import DiscreteNode
from primo.reasoning import MarkovChainSampler
from primo.reasoning import GibbsTransitionModel
from primo.reasoning.density import ProbabilityTable
import numpy

#Construct some simple BayesianNetwork
bn = BayesNet()
burglary = DiscreteNode("Burglary", ["Intruder","Safe"])
alarm = DiscreteNode("Alarm", ["Ringing", "Silent","Kaputt"])

bn.add_node(burglary)


bn.add_node(alarm)

bn.add_edge(burglary,alarm)

burglary_cpt=numpy.array([0.2,0.8])
burglary.set_probability_table(burglary_cpt, [burglary])

alarm_cpt=numpy.array([[0.8,0.15,0.05],[0.05,0.9,0.05]])
alarm.set_probability_table(alarm_cpt, [burglary,alarm])

#Construct a Markov Chain by sampling states from this Network

transition_model = GibbsTransitionModel()
Example #10
0
# -*- coding: utf-8 -*-
"""
This example shows how to create a BayesNet

@author: djohn
"""

from primo.core import BayesNet
from primo.reasoning import DiscreteNode
import numpy

# initialize a new BayesNet
bn = BayesNet()

# create Nodes with Name and the possible values
burglary = DiscreteNode("Burglary", ["Intruder", "Safe"])
alarm = DiscreteNode("Alarm", ["Ringing", "Silent"])
earthquake = DiscreteNode("Earthquake", ["Shaking", "Calm"])
john_calls = DiscreteNode("John calls", ["Calling", "Not Calling"])
baum_calls = DiscreteNode("Baum calls", ["Calling", "Not Calling"])

# add Nodes to BayesNet
bn.add_node(burglary)
bn.add_node(alarm)
bn.add_node(earthquake)
bn.add_node(john_calls)
bn.add_node(baum_calls)

# Add edges to show dependencies
bn.add_edge(burglary, alarm)
bn.add_edge(earthquake, alarm)
Example #11
0
#!/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


#Construct some simple DynmaicBayesianNetwork
B0 = BayesNet()
dbn = DynamicBayesNet()
twoTBN = TwoTBN()

weather0_init = DiscreteNode("Weather0", ["Sun", "Rain"])
weather0 = DiscreteNode("Weather0", ["Sun", "Rain"])
weather = DiscreteNode("Weather", ["Sun", "Rain"])
ice_cream_eaten = DiscreteNode("Ice Cream Eaten", [True, False])

B0.add_node(weather0_init)
twoTBN.add_node(weather0, True)
twoTBN.add_node(weather)
twoTBN.add_node(ice_cream_eaten)

twoTBN.add_edge(weather, ice_cream_eaten)
twoTBN.add_edge(weather0, weather);

cpt_weather0_init = numpy.array([.6, .4])
weather0_init.set_probability_table(cpt_weather0_init, [weather0_init])