def _init_network(self, name, nodes_def):
        """
        This responsible for the initilisation of the network
        """
        nodes = {}
        connections = []
        network = BNet(name)   
        for (nodename, isdiscrete, numstates, leafnode)  in nodes_def:
            nodes[nodename] = network.add_v(BVertex(nodename, isdiscrete, 
                                                 numstates))

        # TODO: Find a way to improve this and avoid to have to loop a
        # second time 
        # reason is because BNnodes[leafnode] is not sure to be there when
        # going through the first loop

        for (nodename, isdiscrete, numstates, leafnode) in nodes_def:
            if type(leafnode) == type([]):
                for r in leafnode:
                    if r != None:
                        connections.append((nodes[nodename], nodes[r]))
            elif leafnode != None:
                connections.append((nodes[nodename], nodes[leafnode]))
            else:
                #do nothing 
                pass

        for ep in connections:
            network.add_e(ep)
        self._network = network
        # Let's not forget to initialize the distribution
        self._network.finalize()
Example #2
0
def main():
    """
    The main function
    """
    # create the network
    graph = BNet( 'Water Sprinkler Bayesian Network' )
    b,c = [graph.add_v( BVertex( nm, False, 1 ) ) for nm in 'b c'.split()]
    a = graph.add_v(BVertex('a',True,2))
    
    for start, end in [( a, b ), ( b, c )]:
        graph.add_e( DirEdge( len( graph.e ), start, end ) )
    
    print graph
    
    # finalize the bayesian network once all edges have been added   
    graph.init_distributions()
    
    # fill in the parameters
    a.distribution.set_parameters([0.7,0.3])
    b.distribution.set_parameters(mu=[2.0,0.0], sigma=[1.0,1.0])
    c.distribution.set_parameters(mu=2.0, sigma=1.0, wi=1.0)
    
    case = graph.sample(1)        #---TODO: correct this bug...
    print case
    
    # NOTE : for the moment only MCMCEngine can work for continuous networks
    engine = MCMCEngine(graph)
    
    res = engine.marginalise_all()
    
    for res in res.values(): 
        print res
def main():
    """
    Simply the main function. We watn to be clean
    """
    # create the network
    graph = BNet( 'Water Sprinkler Bayesian Network' )
    node_a, node_b, node_c = [graph.add_v(BVertex(nm, False, 1)) 
                              for nm in 'a b c'.split()]
    for start, end in [(node_a, node_b), (node_b, node_c)]:
        graph.add_e(DirEdge(len(graph.e), start, end ))
    print graph
    # finalize the bayesian network once all edges have been added   
    graph.init_distributions()
    # fill in the parameters
    node_a.distribution.set_parameters(mu=1.0, sigma=0.5)
    node_b.distribution.set_parameters(mu=2.0, sigma=1.0, wi=2.0)
    node_c.distribution.set_parameters(mu=2.0, sigma=1.0, wi=1.0)
    # NOTE : for the moment only MCMCEngine can work for continuous networks
    engine = MCMCEngine(graph)
    res = engine.marginalise_all()
    for res in res.values(): 
        print res,'\n'
def main():
    """
    The main function
    """
# create the network
    graph = BNet('A Simple Bayesian Network')
    node_a, node_b = [graph.add_v(BVertex(nm, True, 2)) 
                      for nm in 'a b'.split()]
    graph.add_e(DirEdge(len(graph.e), node_a, node_b))


    graph_copy = deepcopy(graph)
    print graph


# finalize the bayesian network once all edges have been added   
    graph.init_distributions()

    print node_a.distribution.cpt, node_b.distribution.cpt
    print '+' * 20, '\n'
    graph_copy.init_distributions()
    print graph_copy.all_v[0].distribution.cpt

    engine = learning.MLLearningEngine(graph)
    try:
        cases = engine.read_file('test.xls')
    except ImportError:
        print "No support for excel. Install the xlrd module"
        print "This test does not continue"
        return
    print 'cases:', cases
    start_time = time()
    engine.learn_ml_params(cases, 0)
    print 'Learned from 4 cases in %1.3f secs' % ((time() - start_time))
    # print the parameters
    for vertex in graph.all_v: 
        print vertex.distribution,'\n'
def main():
    """
    This is the main function. It simply create a baysian network and
    return it.
    """
    # We start by creating the network
    graph = BNet( 'Water Sprinkler Bayesian Network' )
    cloudy, sprinkler, rainy, wet = [graph.add_v(BVertex(nm, True, 2)) 
                                     for nm in 'c s r w'.split()]
    for edge_pair in [(cloudy, rainy), (cloudy, sprinkler), 
                      (rainy, wet), (sprinkler, wet)]:
        graph.add_e(DirEdge(len(graph.e), edge_pair[0], edge_pair[1]))
    print graph
    # finalize the bayesian network once all edges have been added   
    graph.init_distributions()
    # c | Pr(c)
    #---+------
    # 0 |  0.5
    # 1 |  0.5
    cloudy.set_distribution_parameters([0.5, 0.5])
    # c s | Pr(s|c)
    #-----+--------
    # 0 0 |   0.5
    # 1 0 |   0.9
    # 0 1 |   0.5
    # 1 1 |   0.1
    sprinkler.set_distribution_parameters([0.5, 0.9, 0.5, 0.1])
    # c r | Pr(r|c)
    #-----+--------
    # 0 0 |   0.8
    # 1 0 |   0.2
    # 0 1 |   0.2
    # 1 1 |   0.8
    rainy.set_distribution_parameters([0.8, 0.2, 0.2, 0.8])
    # s r w | Pr(w|c,s)
    #-------+------------
    # 0 0 0 |   1.0
    # 1 0 0 |   0.1
    # 0 1 0 |   0.1
    # 1 1 0 |   0.01
    # 0 0 1 |   0.0
    # 1 0 1 |   0.9
    # 0 1 1 |   0.9
    # 1 1 1 |   0.99
    # to verify the order of variables use :
    #>>> w.distribution.names_list
    #['w','s','r']
    
    # we can also set up the variables of a cpt with the following way
    # again the order is w.distribution.names_list
    wet.distribution[:, 0, 0] = [0.99, 0.01]
    wet.distribution[:, 0, 1] = [0.1, 0.9]
    wet.distribution[:, 1, 0] = [0.1, 0.9]
    wet.distribution[:, 1, 1] = [0.0, 1.0]
    
    # or even this way , using a dict:
    #w.distribution[{'s':0,'r':0}]=[0.99, 0.01]
    #w.distribution[{'s':0,'r':1}]=[0.1, 0.9]
    #w.distribution[{'s':1,'r':0}]=[0.1, 0.9]
    #w.distribution[{'s':1,'r':1}]=[0.0, 1.0]
    return graph