コード例 #1
0
    def setUp(self):
        reader = XMLBIFReader(string=TEST_FILE)
        self.expected_model = reader.get_model()
        self.writer = XMLBIFWriter(self.expected_model)

        self.model_stateless = BayesianModel([('D', 'G'), ('I', 'G'), ('G', 'L'), ('I', 'S')])
        self.cpd_d = TabularCPD(variable='D', variable_card=2, values=[[0.6, 0.4]])
        self.cpd_i = TabularCPD(variable='I', variable_card=2, values=[[0.7, 0.3]])

        self.cpd_g = TabularCPD(variable='G', variable_card=3,
                                values=[[0.3, 0.05, 0.9,  0.5],
                                        [0.4, 0.25, 0.08, 0.3],
                                        [0.3, 0.7,  0.02, 0.2]],
                                evidence=['I', 'D'],
                                evidence_card=[2, 2])

        self.cpd_l = TabularCPD(variable='L', variable_card=2,
                                values=[[0.1, 0.4, 0.99],
                                        [0.9, 0.6, 0.01]],
                                evidence=['G'],
                                evidence_card=[3])

        self.cpd_s = TabularCPD(variable='S', variable_card=2,
                                values=[[0.95, 0.2],
                                        [0.05, 0.8]],
                                evidence=['I'],
                                evidence_card=[2])

        self.model_stateless.add_cpds(self.cpd_d, self.cpd_i, self.cpd_g, self.cpd_l, self.cpd_s)
        self.writer_stateless = XMLBIFWriter(self.model_stateless)
コード例 #2
0
ファイル: test_XMLBIF.py プロジェクト: studosi-fer/STRUCE
 def test_write_xmlbif_statefull(self):
     self.writer.write_xmlbif("dog_problem_output.xbif")
     with open("dog_problem_output.xbif", "r") as f:
         file_text = f.read()
     reader = XMLBIFReader(string=file_text)
     model = reader.get_model()
     self.assert_models_equivelent(self.expected_model, model)
     os.remove("dog_problem_output.xbif")
コード例 #3
0
ファイル: optimize_bif.py プロジェクト: sadana1og/NH3
def loadXMLBIF(path):
	reader = XMLBIFReader(path)
	model = reader.get_model()
	print("LOADMODEL: "+str(path))
	"""
	for cpd in model.get_cpds():
		#if(cpd.variable == "SENSOR1"):
		print("CPD of {variable}:".format(variable=cpd.variable))
		print(cpd)
	"""
	return model
コード例 #4
0
 def test_write_xmlbif_stateless(self):
     self.writer_stateless.write_xmlbif("grade_problem_output.xbif")
     with open("grade_problem_output.xbif", 'r') as f:
         reader = XMLBIFReader(f)
     model = reader.get_model()
     self.assert_models_equivelent(self.model_stateless, model)
     self.assertDictEqual({'G': ['state0', 'state1', 'state2'],
                           'I': ['state0', 'state1'],
                           'D': ['state0', 'state1'],
                           'S': ['state0', 'state1'],
                           'L': ['state0', 'state1']},
                          model.get_cpds('D').state_names)
     os.remove("grade_problem_output.xbif")
コード例 #5
0
 def test_write_xmlbif_stateless(self):
     self.writer_stateless.write_xmlbif("grade_problem_output.xbif")
     with open("grade_problem_output.xbif", "r") as f:
         reader = XMLBIFReader(f)
     model = reader.get_model()
     self.assert_models_equivelent(self.model_stateless, model)
     self.assertDictEqual(
         {
             "G": ["state0", "state1", "state2"],
             "I": ["state0", "state1"],
             "D": ["state0", "state1"],
             "S": ["state0", "state1"],
             "L": ["state0", "state1"],
         },
         model.get_cpds("D").state_names,
     )
     os.remove("grade_problem_output.xbif")
コード例 #6
0
    def setUp(self):
        reader = XMLBIFReader(string=TEST_FILE)
        self.expected_model = reader.get_model()
        self.writer = XMLBIFWriter(self.expected_model)

        self.model_stateless = BayesianModel([("D", "G"), ("I", "G"),
                                              ("G", "L"), ("I", "S")])
        self.cpd_d = TabularCPD(variable="D",
                                variable_card=2,
                                values=[[0.6, 0.4]])
        self.cpd_i = TabularCPD(variable="I",
                                variable_card=2,
                                values=[[0.7, 0.3]])

        self.cpd_g = TabularCPD(
            variable="G",
            variable_card=3,
            values=[
                [0.3, 0.05, 0.9, 0.5],
                [0.4, 0.25, 0.08, 0.3],
                [0.3, 0.7, 0.02, 0.2],
            ],
            evidence=["I", "D"],
            evidence_card=[2, 2],
        )

        self.cpd_l = TabularCPD(
            variable="L",
            variable_card=2,
            values=[[0.1, 0.4, 0.99], [0.9, 0.6, 0.01]],
            evidence=["G"],
            evidence_card=[3],
        )

        self.cpd_s = TabularCPD(
            variable="S",
            variable_card=2,
            values=[[0.95, 0.2], [0.05, 0.8]],
            evidence=["I"],
            evidence_card=[2],
        )

        self.model_stateless.add_cpds(self.cpd_d, self.cpd_i, self.cpd_g,
                                      self.cpd_l, self.cpd_s)
        self.writer_stateless = XMLBIFWriter(self.model_stateless)
コード例 #7
0
ファイル: test_XMLBIF.py プロジェクト: studosi-fer/STRUCE
 def setUp(self):
     with open("dog_problem.xml", 'w') as fout:
         fout.write(TEST_FILE)
     self.reader = XMLBIFReader("dog_problem.xml")
コード例 #8
0
ファイル: test_XMLBIF.py プロジェクト: studosi-fer/STRUCE
class TestXMLBIFReaderMethodsFile(unittest.TestCase):
    def setUp(self):
        with open("dog_problem.xml", 'w') as fout:
            fout.write(TEST_FILE)
        self.reader = XMLBIFReader("dog_problem.xml")

    def test_get_variables(self):
        var_expected = [
            'light_on', 'bowel_problem', 'dog_out', 'hear_bark', 'family_out'
        ]
        self.assertListEqual(self.reader.variables, var_expected)

    def test_get_states(self):
        states_expected = {
            'bowel_problem': ['true', 'false'],
            'dog_out': ['true', 'false'],
            'family_out': ['true', 'false'],
            'hear_bark': ['true', 'false'],
            'light_on': ['true', 'false']
        }
        states = self.reader.variable_states
        for variable in states_expected:
            self.assertListEqual(states_expected[variable], states[variable])

    def test_get_parents(self):
        parents_expected = {
            'bowel_problem': [],
            'dog_out': ['bowel_problem', 'family_out'],
            'family_out': [],
            'hear_bark': ['dog_out'],
            'light_on': ['family_out']
        }
        parents = self.reader.variable_parents
        for variable in parents_expected:
            self.assertListEqual(parents_expected[variable], parents[variable])

    def test_get_edges(self):
        edges_expected = [['family_out', 'dog_out'],
                          ['bowel_problem', 'dog_out'],
                          ['family_out', 'light_on'], ['dog_out', 'hear_bark']]
        self.assertListEqual(sorted(self.reader.edge_list),
                             sorted(edges_expected))

    def test_get_cpd(self):
        cpd_expected = {
            'bowel_problem': np.array([[0.01], [0.99]]),
            'dog_out': np.array([[0.99, 0.97, 0.9, 0.3],
                                 [0.01, 0.03, 0.1, 0.7]]),
            'family_out': np.array([[0.15], [0.85]]),
            'hear_bark': np.array([[0.7, 0.01], [0.3, 0.99]]),
            'light_on': np.array([[0.6, 0.05], [0.4, 0.95]])
        }
        cpd = self.reader.variable_CPD
        for variable in cpd_expected:
            np_test.assert_array_equal(cpd_expected[variable], cpd[variable])

    def test_get_property(self):
        property_expected = {
            'bowel_problem': ['position = (190, 69)'],
            'dog_out': ['position = (155, 165)'],
            'family_out': ['position = (112, 69)'],
            'hear_bark': ['position = (154, 241)'],
            'light_on': ['position = (73, 165)']
        }
        prop = self.reader.variable_property
        for variable in property_expected:
            self.assertListEqual(property_expected[variable], prop[variable])

    def test_model(self):
        self.reader.get_model().check_model()

    def tearDown(self):
        del self.reader
        os.remove("dog_problem.xml")
コード例 #9
0
ファイル: test_XMLBIF.py プロジェクト: studosi-fer/STRUCE
 def setUp(self):
     self.reader = XMLBIFReader(string=TEST_FILE)
コード例 #10
0
ファイル: test_XMLBIF.py プロジェクト: cfm25/pgmpy
    def setUp(self):
        self.reader = XMLBIFReader(string="""
        <BIF VERSION="0.3">
        <NETWORK>
        <NAME>Dog-Problem</NAME>

        <VARIABLE TYPE="nature">
            <NAME>light-on</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (73, 165)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>bowel-problem</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (190, 69)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>dog-out</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (155, 165)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>hear-bark</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (154, 241)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>family-out</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (112, 69)</PROPERTY>
        </VARIABLE>


        <DEFINITION>
            <FOR>light-on</FOR>
            <GIVEN>family-out</GIVEN>
            <TABLE>0.6 0.4 0.05 0.95 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>bowel-problem</FOR>
            <TABLE>0.01 0.99 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>dog-out</FOR>
            <GIVEN>bowel-problem</GIVEN>
            <GIVEN>family-out</GIVEN>
            <TABLE>0.99 0.01 0.97 0.03 0.9 0.1 0.3  0.7 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>hear-bark</FOR>
            <GIVEN>dog-out</GIVEN>
            <TABLE>0.7 0.3 0.01 0.99 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>family-out</FOR>
            <TABLE>0.15 0.85 </TABLE>
        </DEFINITION>


        </NETWORK>
        </BIF>
        """)
コード例 #11
0
    network_output = Path(network).with_suffix(
        ".xml")  # change extension from bif to xml

    experiment = {
        'network': str(network_output),
        'query': ','.join(query),
        'evidences': evidences_string
    }

    return experiment


if __name__ == "__main__":
    np.random.seed(1620)

    reader = BIFReader(network_file)
    nodes = reader.get_variables()
    states = reader.get_states()

    experiments = {}

    sampled = rnd.choice(nodes,
                         size=(N_RUNS, N_QUERY + N_EVIDENCES),
                         replace=False)

    for i, run in enumerate(sampled):  # for each run
        query = run[0:N_QUERY]
        evidences = run[N_QUERY:]

        evidences = [(va, rnd.choice(states[va]))
                     for va in evidences]  # sample random state for a give va
コード例 #12
0
class TestXMLBIFReaderMethodsFile(unittest.TestCase):
    def setUp(self):
        with open("dog_problem.xml", "w") as fout:
            fout.write(TEST_FILE)
        self.reader = XMLBIFReader("dog_problem.xml")

    def test_get_variables(self):
        var_expected = [
            "kid",
            "light_on",
            "bowel_problem",
            "dog_out",
            "hear_bark",
            "family_out",
        ]
        self.assertListEqual(self.reader.variables, var_expected)

    def test_get_states(self):
        states_expected = {
            "bowel_problem": ["true", "false"],
            "dog_out": ["true", "false"],
            "family_out": ["true", "false"],
            "hear_bark": ["true", "false"],
            "kid": ["true", "false"],
            "light_on": ["true", "false"],
        }
        states = self.reader.variable_states
        for variable in states_expected:
            self.assertListEqual(states_expected[variable], states[variable])

    def test_get_parents(self):
        parents_expected = {
            "bowel_problem": [],
            "dog_out": ["bowel_problem", "family_out"],
            "family_out": [],
            "hear_bark": ["dog_out"],
            "kid": [],
            "light_on": ["family_out"],
        }
        parents = self.reader.variable_parents
        for variable in parents_expected:
            self.assertListEqual(parents_expected[variable], parents[variable])

    def test_get_edges(self):
        edges_expected = [
            ["family_out", "dog_out"],
            ["bowel_problem", "dog_out"],
            ["family_out", "light_on"],
            ["dog_out", "hear_bark"],
        ]
        self.assertListEqual(sorted(self.reader.edge_list),
                             sorted(edges_expected))

    def test_get_values(self):
        cpd_expected = {
            "bowel_problem": np.array([[0.01], [0.99]]),
            "dog_out": np.array([[0.99, 0.97, 0.9, 0.3],
                                 [0.01, 0.03, 0.1, 0.7]]),
            "family_out": np.array([[0.15], [0.85]]),
            "hear_bark": np.array([[0.7, 0.01], [0.3, 0.99]]),
            "kid": np.array([[0.3], [0.7]]),
            "light_on": np.array([[0.6, 0.05], [0.4, 0.95]]),
        }
        cpd = self.reader.variable_CPD
        for variable in cpd_expected:
            np_test.assert_array_equal(cpd_expected[variable], cpd[variable])

    def test_get_property(self):
        property_expected = {
            "bowel_problem": ["position = (190, 69)"],
            "dog_out": ["position = (155, 165)"],
            "family_out": ["position = (112, 69)"],
            "hear_bark": ["position = (154, 241)"],
            "kid": ["position = (100, 165)"],
            "light_on": ["position = (73, 165)"],
        }
        prop = self.reader.variable_property
        for variable in property_expected:
            self.assertListEqual(property_expected[variable], prop[variable])

    def test_model(self):
        self.reader.get_model().check_model()

    def tearDown(self):
        del self.reader
        os.remove("dog_problem.xml")
コード例 #13
0
ファイル: test_XMLBIF.py プロジェクト: infoburp/pgmpy
    def setUp(self):
        self.reader = XMLBIFReader(string="""
        <BIF VERSION="0.3">
        <NETWORK>
        <NAME>Dog-Problem</NAME>

        <VARIABLE TYPE="nature">
            <NAME>light-on</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (73, 165)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>bowel-problem</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (190, 69)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>dog-out</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (155, 165)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>hear-bark</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (154, 241)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>family-out</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (112, 69)</PROPERTY>
        </VARIABLE>


        <DEFINITION>
            <FOR>light-on</FOR>
            <GIVEN>family-out</GIVEN>
            <TABLE>0.6 0.4 0.05 0.95 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>bowel-problem</FOR>
            <TABLE>0.01 0.99 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>dog-out</FOR>
            <GIVEN>bowel-problem</GIVEN>
            <GIVEN>family-out</GIVEN>
            <TABLE>0.99 0.01 0.97 0.03 0.9 0.1 0.3  0.7 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>hear-bark</FOR>
            <GIVEN>dog-out</GIVEN>
            <TABLE>0.7 0.3 0.01 0.99 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>family-out</FOR>
            <TABLE>0.15 0.85 </TABLE>
        </DEFINITION>


        </NETWORK>
        </BIF>
        """)
コード例 #14
0
ファイル: test_XMLBIF.py プロジェクト: infoburp/pgmpy
class TestXMLBIFReaderMethodsString(unittest.TestCase):
    def setUp(self):
        self.reader = XMLBIFReader(string="""
        <BIF VERSION="0.3">
        <NETWORK>
        <NAME>Dog-Problem</NAME>

        <VARIABLE TYPE="nature">
            <NAME>light-on</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (73, 165)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>bowel-problem</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (190, 69)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>dog-out</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (155, 165)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>hear-bark</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (154, 241)</PROPERTY>
        </VARIABLE>

        <VARIABLE TYPE="nature">
            <NAME>family-out</NAME>
            <OUTCOME>true</OUTCOME>
            <OUTCOME>false</OUTCOME>
            <PROPERTY>position = (112, 69)</PROPERTY>
        </VARIABLE>


        <DEFINITION>
            <FOR>light-on</FOR>
            <GIVEN>family-out</GIVEN>
            <TABLE>0.6 0.4 0.05 0.95 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>bowel-problem</FOR>
            <TABLE>0.01 0.99 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>dog-out</FOR>
            <GIVEN>bowel-problem</GIVEN>
            <GIVEN>family-out</GIVEN>
            <TABLE>0.99 0.01 0.97 0.03 0.9 0.1 0.3  0.7 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>hear-bark</FOR>
            <GIVEN>dog-out</GIVEN>
            <TABLE>0.7 0.3 0.01 0.99 </TABLE>
        </DEFINITION>

        <DEFINITION>
            <FOR>family-out</FOR>
            <TABLE>0.15 0.85 </TABLE>
        </DEFINITION>


        </NETWORK>
        </BIF>
        """)

    def test_get_variables(self):
        var_expected = ['light-on', 'bowel-problem', 'dog-out',
                        'hear-bark', 'family-out']
        self.assertListEqual(self.reader.get_variables(), var_expected)

    def test_get_states(self):
        states_expected = {'bowel-problem': ['true', 'false'],
                           'dog-out': ['true', 'false'],
                           'family-out': ['true', 'false'],
                           'hear-bark': ['true', 'false'],
                           'light-on': ['true', 'false']}
        states = self.reader.get_states()
        for variable in states_expected:
            self.assertListEqual(states_expected[variable],
                                 states[variable])

    def test_get_parents(self):
        parents_expected = {'bowel-problem': [],
                            'dog-out': ['family-out', 'bowel-problem'],
                            'family-out': [],
                            'hear-bark': ['dog-out'],
                            'light-on': ['family-out']}
        parents = self.reader.get_parents()
        for variable in parents_expected:
            self.assertListEqual(parents_expected[variable],
                                 parents[variable])

    def test_get_edges(self):
        edges_expected = [['family-out', 'dog-out'],
                          ['bowel-problem', 'dog-out'],
                          ['family-out', 'light-on'],
                          ['dog-out', 'hear-bark']]
        self.assertListEqual(sorted(self.reader.get_edges()),
                             sorted(edges_expected))

    def test_get_cpd(self):
        cpd_expected = {'bowel-problem': np.array([[0.01],
                                                   [0.99]]),
                        'dog-out': np.array([[0.99, 0.01, 0.97, 0.03],
                                             [0.9, 0.1, 0.3, 0.7]]),
                        'family-out': np.array([[0.15],
                                                [0.85]]),
                        'hear-bark': np.array([[0.7, 0.3],
                                               [0.01, 0.99]]),
                        'light-on': np.array([[0.6, 0.4],
                                              [0.05, 0.95]])}
        cpd = self.reader.get_cpd()
        for variable in cpd_expected:
            np_test.assert_array_equal(cpd_expected[variable],
                                       cpd[variable])

    def test_get_property(self):
        property_expected = {'bowel-problem': ['position = (190, 69)'],
                             'dog-out': ['position = (155, 165)'],
                             'family-out': ['position = (112, 69)'],
                             'hear-bark': ['position = (154, 241)'],
                             'light-on': ['position = (73, 165)']}
        property = self.reader.get_property()
        for variable in property_expected:
            self.assertListEqual(property_expected[variable],
                                 property[variable])

    def tearDown(self):
        del self.reader
コード例 #15
0
#!/usr/bin/env python

import sys
sys.path.insert(0, 'lib')  # this line is necessary for the rest
import os  # of the imports to work!

import web
import sqlitedb
from jinja2 import Environment, FileSystemLoader
import json

from pgmpy.models import BayesianModel
from pgmpy.inference import VariableElimination
from pgmpy.readwrite import XMLBIFReader
MODEL_FILE = 'bayes453.bif.xml'
model = XMLBIFReader(MODEL_FILE).get_model()
infer = VariableElimination(model)
baseline_result = {}
for node in model.nodes():
    baseline_result[node] = infer.query([node])[node].values[1]
###########################################################################################
##########################DO NOT CHANGE ANYTHING ABOVE THIS LINE!##########################
###########################################################################################

######################BEGIN HELPER METHODS######################


# helper method to render a template in the templates/ directory
#
# `template_name': name of template file to render
#