Skip to content
Snippets Groups Projects
Commit efa8a757 authored by Denis John PC's avatar Denis John PC
Browse files

working on factor graph

parent 6d113726
No related branches found
No related tags found
No related merge requests found
......@@ -3,6 +3,7 @@
from primo.core import BayesNet
from primo.reasoning import DiscreteNode
from primo.reasoning.factorelemination import EasiestFactorElimination
from primo.reasoning.factorelemination import FactorTreeFactory
import numpy
bn = BayesNet()
......@@ -16,14 +17,14 @@ baum_calls = DiscreteNode("Baum calls", ["Calling", "Not Calling"])
bn.add_node(burglary)
bn.add_node(alarm)
bn.add_node(earthquake)
#bn.add_node(john_calls)
#bn.add_node(baum_calls)
bn.add_node(john_calls)
bn.add_node(baum_calls)
bn.add_edge(burglary,alarm)
bn.add_edge(earthquake, alarm)
#bn.add_edge(alarm, john_calls)
#bn.add_edge(alarm, baum_calls)
bn.add_edge(alarm, john_calls)
bn.add_edge(alarm, baum_calls)
cpt_burglary = numpy.array([0.001,0.999])
......@@ -64,7 +65,11 @@ fe.set_BayesNet(bn)
#print "PoE Earthquake: " + str(fe.calculate_PoE([(earthquake, "Calm")]))
#print "PoE BaumCalls is Calling: " + str(fe.calculate_PoE([(baum_calls, "Calling")]))
print "Posterior of earthquake : " + str(fe.calculate_PosteriorMarginal([burglary],[(alarm, "Ringing"),(earthquake, "Calm")]))
#print "Posterior of earthquake : " + str(fe.calculate_PosteriorMarginal([burglary],[(alarm, "Ringing"),(earthquake, "Calm")]))
factorTreeFactory = FactorTreeFactory()
factorTree = factorTreeFactory.create_random_factortree(bn)
#factorTree.draw()
......@@ -10,5 +10,8 @@ class Factor(object):
self.node = node
self.calPT = node.get_cpd()
def __str__(self):
return self.node.name
......@@ -2,3 +2,8 @@
class FactorEdge(object):
def __init__(self,graph,rootNode):
self.graph = graph
self.rootNode = rootNode
......@@ -10,6 +10,11 @@ class FactorTree(object):
self.graph = graph
self.rootNode = rootNode
def draw(self):
import matplotlib.pyplot as plt
nx.draw_circular(self.graph)
plt.show()
......
import networkx as nx
from primo.core import Node
from primo.reasoning.factorelemination import Factor
from primo.reasoning.factorelemination import FactorTree
from random import choice
class FactorTreeFactory(object):
def create_random_factortree(self,bayesNet):
allNodes = bayesNet.get_all_nodes()
if len(allNodes) == 0:
raise Exception("createRandomFactorTree: No nodes in given bayesNet")
tn = allNodes.pop()
rootFactor = Factor(tn)
graph = nx.DiGraph()
graph.add_node(rootFactor)
usedNodes = [rootFactor]
for n in allNodes[:]:
parentNode = choice(usedNodes[:])
newFactor = Factor(n)
graph.add_edge(parentNode,newFactor)
usedNodes.append(newFactor)
return FactorTree(graph,rootFactor)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment