def _init_BN(self, BNnodesdef): BNnodes = {} BNconnections = [] BN = BNet() # Save the nodesdef for future use (saving) self._BNDef = BNnodesdef for node in BNnodesdef: (nodename , isdiscrete, numstates, leafnode) = node BNnodes[nodename] = BN.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 node in BNnodesdef: (nodename , isdiscrete, numstates, leafnode) = node if type(leafnode)==type([]): for r in leafnode: if r!=None: BNconnections.append( (BNnodes[nodename], BNnodes[r]) ) elif leafnode!=None: BNconnections.append( (BNnodes[nodename], BNnodes[leafnode]) ) else: #do nothing pass for ep in BNconnections: BN.add_e( DirEdge( len( BN.e ), *ep ) ) # Ok our Bnet has been created, let's save it in the controller self._BN = BN # Let's not forget to initialize the distribution self._BN.InitDistributions()
def CreateOpenBayesNetwork(network): G = BNet( network.name ) node_dict = {} for node in network.nodes.all(): pynode = BVertex( node.name, True, node.states.count() ) node_dict[node.id] = pynode G.add_v(pynode) for edge in network.edges.all(): pyedge = DirEdge( len( G.e ),node_dict[edge.parent_node.id] , node_dict[edge.child_node.id]) G.add_e( pyedge ) G.InitDistributions() for node in network.nodes.all(): if not node.is_root(): result = node.get_indexed_value_sets()[0] index = node.get_indexed_value_sets()[1] for i in range(len(index)): index_dict = {} check_dict = {} result_i_parents = result[i][0] values_i = result[i][1] index_i_parents = index[i][0] for j in range(len(index_i_parents)): index_dict[result_i_parents[j].node.name] = index_i_parents[j] check_dict[result_i_parents[j].node.name] = result_i_parents[j].name node_dict[node.id].distribution[index_dict] = [v.value for v in values_i] print "\n" else: node_dict[node.id].setDistributionParameters([state.probability for state in node.states.all()]) return (G,node_dict)
def _init_BN(self, BNName, BNnodesdef): BNnodes = {} BNconnections = [] BN = BNet(BNName) # Save the nodesdef for future use (saving) self._BNDef = BNnodesdef for node in BNnodesdef: (nodename, isdiscrete, numstates, leafnode) = node BNnodes[nodename] = BN.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 node in BNnodesdef: (nodename, isdiscrete, numstates, leafnode) = node if type(leafnode) == type([]): for r in leafnode: if r != None: BNconnections.append((BNnodes[nodename], BNnodes[r])) elif leafnode != None: BNconnections.append((BNnodes[nodename], BNnodes[leafnode])) else: #do nothing pass for ep in BNconnections: BN.add_e(DirEdge(len(BN.e), *ep)) # Ok our Bnet has been created, let's save it in the controller self._BN = BN # Let's not forget to initialize the distribution self._BN.InitDistributions()
import site import sys from OpenBayes import BNet, BVertex, DirEdge, JoinTree # @UnresolvedImport dir = r'W:\ilmb\vic\geobc\bier\p14\p14_0053_BBN_CumEffects\wrk\scripts\deps\Lib\site-packages' site.addsitedir(dir) # @UndefinedVariable network = BNet('Asia Bayesian Network') # Create a discrete node for all nodes with 2 states visit_to_asia = network.add_v(BVertex('Visit to Asia', True, 2)) # TRUE used to indicate the data is discrete as oppose to continuous smoking = network.add_v(BVertex('Smoking', True, 2)) tuberculosis = network.add_v(BVertex('Tuberculosis', True, 2)) lung_cancer = network.add_v(BVertex('Lung Cancer', True, 2)) bronchitis = network.add_v(BVertex('Bronchitis', True, 2)) tub_or_cancer = network.add_v(BVertex('Tuberculosis or Cancer', True, 2)) xray_result = network.add_v(BVertex('X-Ray Result', True, 2)) dyspnea = network.add_v(BVertex('Dyspnea', True, 2)) # Connect the nodes # V -> T network.add_e(DirEdge(len(network.e), visit_to_asia, tuberculosis)) # T -> TC network.add_e(DirEdge(len(network.e), tuberculosis, tub_or_cancer))
""" this examples creates a continuous bayesian network A / B \ C all edges point downwards A,B and C are univariate gaussian distributions """ from OpenBayes import BNet, BVertex, DirEdge, MCMCEngine # create the network G = BNet( 'Water Sprinkler Bayesian Network' ) a,b,c = [G.add_v( BVertex( nm, False, 1 ) ) for nm in 'a b c'.split()] for ep in [( a, b ), ( b, c )]: G.add_e( DirEdge( len( G.e ), *ep ) ) print G # finalize the bayesian network once all edges have been added G.InitDistributions() # fill in the parameters a.distribution.setParameters(mu=1.0, sigma=0.5) b.distribution.setParameters(mu=2.0, sigma=1.0, wi=2.0) c.distribution.setParameters(mu=2.0, sigma=1.0, wi=1.0) # NOTE : for the moment only MCMCEngine can work for continuous networks ie = MCMCEngine(G)
""" this examples creates a hybrid bayesian network A / B \ C all edges point downwards B and C are univariate gaussian distributions A is a boolean discrete distribution """ from OpenBayes import BNet, BVertex, DirEdge, MCMCEngine # create the network G = BNet( 'Water Sprinkler Bayesian Network' ) b,c = [G.add_v( BVertex( nm, False, 1 ) ) for nm in 'b c'.split()] a = G.add_v(BVertex('a',True,2)) for ep in [( a, b ), ( b, c )]: G.add_e( DirEdge( len( G.e ), *ep ) ) print G # finalize the bayesian network once all edges have been added G.InitDistributions() # fill in the parameters a.distribution.setParameters([0.7,0.3]) b.distribution.setParameters(mu=[2.0,0.0], sigma=[1.0,1.0]) c.distribution.setParameters(mu=2.0, sigma=1.0, wi=1.0)
from OpenBayes import BNet, BVertex, DirEdge, JoinTree network = BNet('Asia Bayesian Network') # Create a discrete node for all nodes with 2 states visit_to_asia = network.add_v(BVertex('Visit to Asia', True, 2)) smoking = network.add_v(BVertex('Smoking', True, 2)) tuberculosis = network.add_v(BVertex('Tuberculosis', True, 2)) lung_cancer = network.add_v(BVertex('Lung Cancer', True, 2)) bronchitis = network.add_v(BVertex('Bronchitis', True, 2)) tub_or_cancer = network.add_v(BVertex('Tuberculosis or Cancer', True, 2)) xray_result = network.add_v(BVertex('X-Ray Result', True, 2)) dyspnea = network.add_v(BVertex('Dyspnea', True, 2)) # Connect the nodes # V -> T network.add_e(DirEdge(len(network.e), visit_to_asia, tuberculosis)) # T -> TC network.add_e(DirEdge(len(network.e), tuberculosis, tub_or_cancer)) # TC -> X network.add_e(DirEdge(len(network.e), tub_or_cancer, xray_result)) # TC -> D network.add_e(DirEdge(len(network.e), tub_or_cancer, dyspnea)) # S -> LC network.add_e(DirEdge(len(network.e), smoking, lung_cancer))
from OpenBayes import BNet, BVertex, DirEdge from OpenBayes import learning from copy import deepcopy from time import time # create the network G = BNet( 'A Simple Bayesian Network' ) a, b = [G.add_v( BVertex( nm, True, 2 ) ) for nm in 'a b'.split()] for ep in [( a, b )]: G.add_e( DirEdge( len( G.e ), *ep ) ) G2 = deepcopy(G) print G # finalize the bayesian network once all edges have been added G.InitDistributions() print a.distribution.cpt, b.distribution.cpt print '+++++++++++++++++++++++++++++++++\n' G2.InitDistributions() print G2.all_v[0].distribution.cpt engine = learning.MLLearningEngine(G) cases = engine.ReadFile('test.xls') print 'cases:', cases ##cases = [] t = time()
# This is an attempt to figure out how to model the mule # deer model using the openbayes module. # import site import sys from OpenBayes import BNet, BVertex, DirEdge, JoinTree # @UnresolvedImport dir = r'W:\ilmb\vic\geobc\bier\p14\p14_0053_BBN_CumEffects\wrk\scripts\deps\Lib\site-packages' site.addsitedir(dir) # @UndefinedVariable network = BNet('Mule Deer Hazard') # @UndefinedVariable # create discrete node for all nodes with 2 states?? road_Density = network.add_v(BVertex('Road Density', True, 3)) unregulated_Hunting_Rate = network.add_v(BVertex('Unregulated Hunting Rate', True, 3)) cougar_risk_level = network.add_v(BVertex('Cougar Risk Level', True, 3)) wolfPresence = network.add_v(BVertex('Wolf Presence', True, 2)) predation_risk = network.add_v(BVertex('Predation Risk', True, 3)) population_hazard = network.add_v(BVertex('Population Hazard', True, 5)) proportion_of_lu_in_UWR = network.add_v(BVertex('Proportion of LU in UWR', True, 4)) uwr_hazard_rating = network.add_v(BVertex('UWR Hazard Rating', True, 5)) habitat_hazard_rating = network.add_v(BVertex('Habitat Hazard Rating', True, 5)) muleDeerHazardRating = network.add_v(BVertex('Mule Deer Hazard Rating', True, 5)) regulated_Hunting_Rate = network.add_v(BVertex('Regulated Hunting Rate', True, 3)) # now describe the connections # population side of model network.add_e(DirEdge(len(network.e), road_Density, unregulated_Hunting_Rate)) network.add_e(DirEdge(len(network.e), road_Density, predation_risk)) network.add_e(DirEdge(len(network.e), cougar_risk_level, predation_risk))
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.""" import OpenBayes from OpenBayes import BNet, BVertex, DirEdge, JoinTree import logging logging.getLogger(__name__).setLevel(logging.CRITICAL) logging.getLogger("").setLevel(logging.CRITICAL) import numpy network = BNet('Number Guessing') # Create a discrete node for all nodes with 2 states numbers = network.add_v(BVertex('numbers', True, 10)) bigger_3 = network.add_v(BVertex('Is your number bigger than 3?', True, 2)) bigger_5 = network.add_v(BVertex('bigger_5', True, 2)) IsTheNumberBiggerThan7 = network.add_v(BVertex('IsTheNumberBiggerThan7', True, 2)) prime = network.add_v(BVertex('prime', True, 2)) even = network.add_v(BVertex('even', True, 2)) odd = network.add_v(BVertex('odd', True, 2)) network.add_e(DirEdge(len(network.e), numbers, bigger_3)) network.add_e(DirEdge(len(network.e), numbers, bigger_5)) network.add_e(DirEdge(len(network.e), numbers, IsTheNumberBiggerThan7)) network.add_e(DirEdge(len(network.e), numbers, even)) network.add_e(DirEdge(len(network.e), numbers, prime)) network.add_e(DirEdge(len(network.e), even, odd))
/ \ / \ Sprinkler Rainy \ / \ / \ / Wet grass all edges are pointing downwards """ from OpenBayes import BNet, BVertex, DirEdge # create the network G = BNet( 'Water Sprinkler Bayesian Network' ) c, s, r, w = [G.add_v( BVertex( nm, True, 2 ) ) for nm in 'c s r w'.split()] for ep in [( c, r ), ( c, s ), ( r, w ), ( s, w )]: G.add_e( DirEdge( len( G.e ), *ep ) ) print G # finalize the bayesian network once all edges have been added G.InitDistributions() # c | Pr(c) #---+------ # 0 | 0.5 # 1 | 0.5 c.setDistributionParameters([0.5, 0.5]) # c s | Pr(s|c) #-----+--------
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.""" import OpenBayes from OpenBayes import BNet, BVertex, DirEdge, JoinTree import logging logging.getLogger(__name__).setLevel(logging.CRITICAL) logging.getLogger("").setLevel(logging.CRITICAL) import numpy network = BNet('Number Guessing') # Create a discrete node for all nodes with 2 states numbers = network.add_v(BVertex('numbers', True, 10)) bigger_3 = network.add_v(BVertex('Is your number bigger than 3?', True, 2)) bigger_5 = network.add_v(BVertex('bigger_5', True, 2)) IsTheNumberBiggerThan7 = network.add_v( BVertex('IsTheNumberBiggerThan7', True, 2)) prime = network.add_v(BVertex('prime', True, 2)) even = network.add_v(BVertex('even', True, 2)) odd = network.add_v(BVertex('odd', True, 2)) network.add_e(DirEdge(len(network.e), numbers, bigger_3)) network.add_e(DirEdge(len(network.e), numbers, bigger_5)) network.add_e(DirEdge(len(network.e), numbers, IsTheNumberBiggerThan7)) network.add_e(DirEdge(len(network.e), numbers, even)) network.add_e(DirEdge(len(network.e), numbers, prime)) network.add_e(DirEdge(len(network.e), even, odd))