コード例 #1
0
ファイル: node.py プロジェクト: ChangDarren/bayesian-network
class Node:
    def __init__(self, id, variable, dependencies):
        """
            variable - dictionary containing the variable name to its
            possible values

            dependencies - dictionary containing the dependencies to its
            possible values
        """
        self.id = id
        self.varName = list(variable.keys())[0]
        self.table = Table(variable, dependencies)

    def getVarName(self):
        return self.var_name

    def fillTable(self, cptMapping):
        """
            cptMapping - dictionary mapping the probability query to
            the probability value
        """
        for mapping in cptMapping:
            query, evidence = self._unpackMap(mapping)
            self.setProb(query, evidence, cptMapping[mapping])

    def _unpackMap(self, mapping):
        """
            mapping - string of the form of a probability query
            e.g. A = True | B = False,
                 A = False
            
            Returns:
                query - dictionary mapping the variable and its value
                evidence - dictionary mapping the evidence and its value
        """
        if mapping.find('|') != -1:
            queryStr, evidenceStr = mapping.split('|')

            query = dict()
            queryVar, queryVal = [x.strip() for x in queryStr.split('=')]
            query[queryVar] = queryVal

            evidence = dict()
            eviStrs = [x.strip() for x in evidenceStr.split(',')]
            for eviStr in eviStrs:
                eviVar, eviVal = [x.strip() for x in eviStr.split('=')]
                evidence[eviVar] = eviVal

            return (query, evidence)
        else:
            query = dict()
            queryVar, queryVal = [x.strip() for x in mapping.split('=')]
            query[queryVar] = queryVal

            return (query, None)

    def getProb(self, query, evidence):
        return self.table.getProb(query, evidence)

    def setProb(self, query, evidence, prob):
        self.table.setProb(query, evidence, prob)

    def getFactor(self, conditions):
        return self.table.getFactor(conditions)