Newer
Older
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from primo.core import BayesNet
from primo.reasoning import DiscreteNode
import numpy
class EasiestFactorElimination(object):
'''This is the easiest way for factor elimination.It's has the worst runtime because:
3. The redundant variables are summed out
Literature: Modeling and Reasoning with Bayesian Networks - Adnan Darwiche
Chapter 6-7
'''
def __init__(self,bayesNet):
self.bn= bayesNet
def calculate_PriorMarginal(self,variables):
'''Calculates the prior marignal for the given variables. The resulting
CPD is returned.'''
nodes = self.bn.get_all_nodes()
finCpd = nodes.pop().get_cpd()
for n in nodes:
finCpd = finCpd.multiplication(n.get_cpd())
if v not in variables:
finCpd = finCpd.marginalization(v)
return finCpd
def calculate_PosteriorMarginal(self,variables,evidence):
'''Calculates the posterior marginal for given variables and evidence.
It returns the resulting cpd.'''
if node1 in ev_list[0]:
ind = ev_list[0].index(node1)
finCpd = node1.get_cpd().set_evidence(evidence[ind])
else:
finCpd = node1.get_cpd()
if v not in variables:
finCpd = finCpd.marginalization(v)
finCpd = finCpd.normalize_as_jpt()
''' Calculates the probabilty of evidence for the given evidence and returns the result.'''
nodes = self.bn.get_all_nodes()
unzipped_list = zip(*evidence)
node1 = nodes.pop()
if node1 in unzipped_list[0]:
ind = unzipped_list[0].index(node1)
finCpd = node1.get_cpd().set_evidence(evidence[ind])
else:
finCpd = node1.get_cpd()
for n in nodes:
if n in unzipped_list[0]:
ind = unzipped_list[0].index(n)
nCPD = n.get_cpd().set_evidence(evidence[ind])
finCpd = finCpd.multiplication(nCPD)
else:
finCpd = finCpd.multiplication(n.get_cpd())
finCpd = finCpd.marginalization(v)
return finCpd