Пример #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
    def setUp(self):
        edges = [['family-out', 'dog-out'], ['bowel-problem', 'dog-out'],
                 ['family-out', 'light-on'], ['dog-out', 'hear-bark']]
        cpds = {
            '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]])
        }
        states = {
            'bowel-problem': ['true', 'false'],
            'dog-out': ['true', 'false'],
            'family-out': ['true', 'false'],
            'hear-bark': ['true', 'false'],
            'light-on': ['true', 'false']
        }
        parents = {
            'bowel-problem': [],
            'dog-out': ['family-out', 'bowel-problem'],
            'family-out': [],
            'hear-bark': ['dog-out'],
            'light-on': ['family-out']
        }
        properties = {
            '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)']
        }

        self.model = BayesianModel(edges)

        tabular_cpds = []
        for var, values in cpds.items():
            cpd = TabularCPD(var,
                             len(states[var]),
                             values,
                             evidence=parents[var],
                             evidence_card=[
                                 len(states[evidence_var])
                                 for evidence_var in parents[var]
                             ])
            tabular_cpds.append(cpd)
        self.model.add_cpds(*tabular_cpds)

        for node, properties in properties.items():
            for prop in properties:
                prop_name, prop_value = map(lambda t: t.strip(),
                                            prop.split('='))
                self.model.node[node][prop_name] = prop_value

        self.writer = XMLBIFWriter(model=self.model)
    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)
Пример #4
0
    def setUp(self):
        edges = [
            ["family-out", "dog-out"],
            ["bowel-problem", "dog-out"],
            ["family-out", "light-on"],
            ["dog-out", "hear-bark"],
        ]
        cpds = {
            "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]]),
        }
        states = {
            "bowel-problem": ["true", "false"],
            "dog-out": ["true", "false"],
            "family-out": ["true", "false"],
            "hear-bark": ["true", "false"],
            "light-on": ["true", "false"],
        }
        parents = {
            "bowel-problem": [],
            "dog-out": ["family-out", "bowel-problem"],
            "family-out": [],
            "hear-bark": ["dog-out"],
            "light-on": ["family-out"],
        }
        properties = {
            "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)"],
        }

        self.model = BayesianModel(edges)

        tabular_cpds = []
        for var, values in cpds.items():
            cpd = TabularCPD(
                var,
                len(states[var]),
                values,
                evidence=parents[var],
                evidence_card=[len(states[evidence_var]) for evidence_var in parents[var]],
            )
            tabular_cpds.append(cpd)
        self.model.add_cpds(*tabular_cpds)

        for node, properties in properties.items():
            for prop in properties:
                prop_name, prop_value = map(lambda t: t.strip(), prop.split("="))
                self.model.node[node][prop_name] = prop_value

        self.writer = XMLBIFWriter(model=self.model)
Пример #5
0
    def setUp(self):
        edges = [['family-out', 'dog-out'],
                 ['bowel-problem', 'dog-out'],
                 ['family-out', 'light-on'],
                 ['dog-out', 'hear-bark']]
        cpds = {'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]])}
        states = {'bowel-problem': ['true', 'false'],
                  'dog-out': ['true', 'false'],
                  'family-out': ['true', 'false'],
                  'hear-bark': ['true', 'false'],
                  'light-on': ['true', 'false']}
        parents = {'bowel-problem': [],
                   'dog-out': ['family-out', 'bowel-problem'],
                   'family-out': [],
                   'hear-bark': ['dog-out'],
                   'light-on': ['family-out']}
        properties = {'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)']}

        self.model = BayesianModel(edges)

        tabular_cpds = []
        for var, values in cpds.items():
            cpd = TabularCPD(var, len(states[var]), values,
                             evidence=parents[var],
                             evidence_card=[len(states[evidence_var])
                                            for evidence_var in parents[var]])
            tabular_cpds.append(cpd)
        self.model.add_cpds(*tabular_cpds)

        for node, properties in properties.items():
            for prop in properties:
                prop_name, prop_value = map(lambda t: t.strip(), prop.split('='))
                self.model.node[node][prop_name] = prop_value

        self.writer = XMLBIFWriter(model=self.model)
Пример #6
0
class TestXMLBIFWriterMethodsString(unittest.TestCase):
    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)

    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")

    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")

    def assert_models_equivelent(self, expected, got):
        self.assertSetEqual(set(expected.nodes()), set(got.nodes()))
        for node in expected.nodes():
            self.assertListEqual(expected.get_parents(node),
                                 got.get_parents(node))
            cpds_expected = expected.get_cpds(node=node)
            cpds_got = got.get_cpds(node=node)
            np_test.assert_array_equal(cpds_expected.values, cpds_got.values)
Пример #7
0
class TestXMLBIFWriterMethodsString(unittest.TestCase):
    def setUp(self):
        edges = [
            ["family-out", "dog-out"],
            ["bowel-problem", "dog-out"],
            ["family-out", "light-on"],
            ["dog-out", "hear-bark"],
        ]
        cpds = {
            "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]]),
        }
        states = {
            "bowel-problem": ["true", "false"],
            "dog-out": ["true", "false"],
            "family-out": ["true", "false"],
            "hear-bark": ["true", "false"],
            "light-on": ["true", "false"],
        }
        parents = {
            "bowel-problem": [],
            "dog-out": ["family-out", "bowel-problem"],
            "family-out": [],
            "hear-bark": ["dog-out"],
            "light-on": ["family-out"],
        }
        properties = {
            "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)"],
        }

        self.model = BayesianModel(edges)

        tabular_cpds = []
        for var, values in cpds.items():
            cpd = TabularCPD(
                var,
                len(states[var]),
                values,
                evidence=parents[var],
                evidence_card=[len(states[evidence_var]) for evidence_var in parents[var]],
            )
            tabular_cpds.append(cpd)
        self.model.add_cpds(*tabular_cpds)

        for node, properties in properties.items():
            for prop in properties:
                prop_name, prop_value = map(lambda t: t.strip(), prop.split("="))
                self.model.node[node][prop_name] = prop_value

        self.writer = XMLBIFWriter(model=self.model)

    def test_file(self):
        self.expected_xml = etree.XML(
            """<BIF version="0.3">
  <NETWORK>
    <VARIABLE TYPE="nature">
      <NAME>bowel-problem</NAME>
      <OUTCOME>0</OUTCOME>
      <OUTCOME>1</OUTCOME>
      <PROPERTY>position = (190, 69)</PROPERTY>
    </VARIABLE>
    <VARIABLE TYPE="nature">
      <NAME>dog-out</NAME>
      <OUTCOME>0</OUTCOME>
      <OUTCOME>1</OUTCOME>
      <PROPERTY>position = (155, 165)</PROPERTY>
    </VARIABLE>
    <VARIABLE TYPE="nature">
      <NAME>family-out</NAME>
      <OUTCOME>0</OUTCOME>
      <OUTCOME>1</OUTCOME>
      <PROPERTY>position = (112, 69)</PROPERTY>
    </VARIABLE>
    <VARIABLE TYPE="nature">
      <NAME>hear-bark</NAME>
      <OUTCOME>0</OUTCOME>
      <OUTCOME>1</OUTCOME>
      <PROPERTY>position = (154, 241)</PROPERTY>
    </VARIABLE>
    <VARIABLE TYPE="nature">
      <NAME>light-on</NAME>
      <OUTCOME>0</OUTCOME>
      <OUTCOME>1</OUTCOME>
      <PROPERTY>position = (73, 165)</PROPERTY>
    </VARIABLE>
    <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>family-out</FOR>
      <TABLE>0.15 0.85 </TABLE>
    </DEFINITION>
    <DEFINITION>
      <FOR>hear-bark</FOR>
      <GIVEN>dog-out</GIVEN>
      <TABLE>0.7 0.3 0.01 0.99 </TABLE>
    </DEFINITION>
    <DEFINITION>
      <FOR>light-on</FOR>
      <GIVEN>family-out</GIVEN>
      <TABLE>0.6 0.4 0.05 0.95 </TABLE>
    </DEFINITION>
  </NETWORK>
</BIF>"""
        )
        self.maxDiff = None
        self.writer.write_xmlbif("test_bif.xml")
        with open("test_bif.xml", "r") as myfile:
            data = myfile.read()
        self.assertEqual(str(self.writer.__str__()[:-1]), str(etree.tostring(self.expected_xml)))
        self.assertEqual(str(data), str(etree.tostring(self.expected_xml).decode("utf-8")))
Пример #8
0
class TestXMLBIFWriterMethodsString(unittest.TestCase):
    def setUp(self):
        edges = [['family-out', 'dog-out'], ['bowel-problem', 'dog-out'],
                 ['family-out', 'light-on'], ['dog-out', 'hear-bark']]
        cpds = {
            '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]])
        }
        states = {
            'bowel-problem': ['true', 'false'],
            'dog-out': ['true', 'false'],
            'family-out': ['true', 'false'],
            'hear-bark': ['true', 'false'],
            'light-on': ['true', 'false']
        }
        parents = {
            'bowel-problem': [],
            'dog-out': ['family-out', 'bowel-problem'],
            'family-out': [],
            'hear-bark': ['dog-out'],
            'light-on': ['family-out']
        }
        properties = {
            '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)']
        }

        self.model = BayesianModel(edges)

        tabular_cpds = []
        for var, values in cpds.items():
            cpd = TabularCPD(var,
                             len(states[var]),
                             values,
                             evidence=parents[var],
                             evidence_card=[
                                 len(states[evidence_var])
                                 for evidence_var in parents[var]
                             ])
            tabular_cpds.append(cpd)
        self.model.add_cpds(*tabular_cpds)

        for node, properties in properties.items():
            for prop in properties:
                prop_name, prop_value = map(lambda t: t.strip(),
                                            prop.split('='))
                self.model.node[node][prop_name] = prop_value

        self.writer = XMLBIFWriter(model=self.model)

    def test_file(self):
        self.expected_xml = etree.XML("""<BIF version="0.3">
  <NETWORK>
    <VARIABLE TYPE="nature">
      <NAME>bowel-problem</NAME>
      <OUTCOME>0</OUTCOME>
      <OUTCOME>1</OUTCOME>
      <PROPERTY>position = (190, 69)</PROPERTY>
    </VARIABLE>
    <VARIABLE TYPE="nature">
      <NAME>dog-out</NAME>
      <OUTCOME>0</OUTCOME>
      <OUTCOME>1</OUTCOME>
      <PROPERTY>position = (155, 165)</PROPERTY>
    </VARIABLE>
    <VARIABLE TYPE="nature">
      <NAME>family-out</NAME>
      <OUTCOME>0</OUTCOME>
      <OUTCOME>1</OUTCOME>
      <PROPERTY>position = (112, 69)</PROPERTY>
    </VARIABLE>
    <VARIABLE TYPE="nature">
      <NAME>hear-bark</NAME>
      <OUTCOME>0</OUTCOME>
      <OUTCOME>1</OUTCOME>
      <PROPERTY>position = (154, 241)</PROPERTY>
    </VARIABLE>
    <VARIABLE TYPE="nature">
      <NAME>light-on</NAME>
      <OUTCOME>0</OUTCOME>
      <OUTCOME>1</OUTCOME>
      <PROPERTY>position = (73, 165)</PROPERTY>
    </VARIABLE>
    <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>family-out</FOR>
      <TABLE>0.15 0.85 </TABLE>
    </DEFINITION>
    <DEFINITION>
      <FOR>hear-bark</FOR>
      <GIVEN>dog-out</GIVEN>
      <TABLE>0.7 0.3 0.01 0.99 </TABLE>
    </DEFINITION>
    <DEFINITION>
      <FOR>light-on</FOR>
      <GIVEN>family-out</GIVEN>
      <TABLE>0.6 0.4 0.05 0.95 </TABLE>
    </DEFINITION>
  </NETWORK>
</BIF>""")
        self.maxDiff = None
        self.writer.write_xmlbif("test_bif.xml")
        with open("test_bif.xml", "r") as myfile:
            data = myfile.read()
        self.assertEqual(str(self.writer.__str__()[:-1]),
                         str(etree.tostring(self.expected_xml)))
        self.assertEqual(
            str(data), str(etree.tostring(self.expected_xml).decode('utf-8')))
class TestXMLBIFWriterMethodsString(unittest.TestCase):
    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)

    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")

    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")

    def assert_models_equivelent(self, expected, got):
        self.assertSetEqual(set(expected.nodes()), set(got.nodes()))
        for node in expected.nodes():
            self.assertListEqual(list(expected.get_parents(node)),
                                 list(got.get_parents(node)))
            cpds_expected = expected.get_cpds(node=node)
            cpds_got = got.get_cpds(node=node)
            np_test.assert_array_equal(cpds_expected.values, cpds_got.values)