Пример #1
0
    def _create_prob_distribution(self, head_var, factor):
        """
        Creates the probability distribution for the given variable, as described by
        the factor. The distribution is normalised, and encoded as a table.

        :param head_var: the variable
        :param factor: the double factor
        :return: the resulting probability distribution
        """
        variables = factor.get_variables()

        if len(variables) == 1:
            factor.normalize()
            builder = CategoricalTableBuilder(head_var)
            for assignment in factor.get_assignments():
                builder.add_row(assignment.get_value(head_var),
                                factor.get_prob_entry(assignment))

            return builder.build()
        else:
            dependent_variables = set(variables)
            if head_var in dependent_variables:
                dependent_variables.remove(head_var)

            factor.normalize(dependent_variables)
            builder = ConditionalTableBuilder(head_var)
            for assignment in factor.get_assignments():
                condition = assignment.get_trimmed(dependent_variables)
                builder.add_row(condition, assignment.get_value(head_var),
                                factor.get_prob_entry(assignment))

            return builder.build()
Пример #2
0
    def test_rule_and_params(self):
        domain = XMLDomainReader.extract_domain(TestRuleAndParams.domain_file)
        system = DialogueSystem(domain)

        system.get_settings().show_gui = False

        system.start_system()
        assert system.get_content("theta_moves").to_continuous().get_function().get_mean()[0] == pytest.approx(0.2, abs=0.02)
        assert system.get_content("a_u^p").get_prob("I want left") == pytest.approx(0.12, abs=0.03)
        assert len(system.get_state().get_chance_node("theta_moves").get_output_node_ids()) == 1
        assert system.get_state().has_chance_node("movements")
        assert isinstance(system.get_state().get_chance_node("movements").get_distrib(), AnchoredRule)

        t = CategoricalTableBuilder("a_u")
        t.add_row("I want left", 0.8)
        t.add_row("I want forward", 0.1)
        system.add_content(t.build())

        assert len(system.get_state().get_chance_node("theta_moves").get_output_node_ids()) == 0
        assert not system.get_state().has_chance_node("movements")
        assert system.get_content("theta_moves").to_continuous().get_function().get_mean()[0] == pytest.approx(2.0 / 6.0, abs=0.07)

        system.add_content("a_m", "turning left")

        assert system.get_content("a_u^p").get_prob("I want left") == pytest.approx(0.23, abs=0.04)
        assert len(system.get_state().get_chance_node("theta_moves").get_output_node_ids()) == 1
Пример #3
0
    def test_3(self):
        system = DialogueSystem(TestRule2.domain)
        system.get_settings().show_gui = False
        system.detach_module(ForwardPlanner)
        eq_factor = EquivalenceDistribution.none_prob
        EquivalenceDistribution.none_prob = 0.1
        old_prune_threshold = StatePruner.value_pruning_threshold
        StatePruner.value_pruning_threshold = 0.0
        system.start_system()

        TestRule2.inference.check_util(system.get_state(), "a_m'", "Do(A)",
                                       0.6)
        TestRule2.inference.check_util(system.get_state(), "a_m'", "Do(B)",
                                       -2.6)

        builder = CategoricalTableBuilder("a_u")
        builder.add_row("Ask(B)", 0.8)
        builder.add_row("None", 0.2)
        system.get_state().remove_nodes(
            system.get_state().get_action_node_ids())
        system.get_state().remove_nodes(
            system.get_state().get_utility_node_ids())
        system.add_content(builder.build())

        TestRule2.inference.check_util(system.get_state(), "a_m'", "Do(A)",
                                       -4.35)
        TestRule2.inference.check_util(system.get_state(), "a_m'", "Do(B)",
                                       2.357)

        EquivalenceDistribution.none_prob = eq_factor
        StatePruner.value_pruning_threshold = old_prune_threshold
Пример #4
0
    def test_discrete(self):
        builder = CategoricalTableBuilder("A")

        builder.add_row(1.0, 0.6)
        builder.add_row(2.5, 0.3)
        table = builder.build()
        assert table.get_prob(2.5) == pytest.approx(0.3, abs=0.0001)
        assert table.get_prob(1.0) == pytest.approx(0.6, abs=0.0001)

        distrib = table.to_continuous()
        assert distrib.get_prob_density(2.5) == pytest.approx(0.2, abs=0.01)
        assert distrib.get_prob_density(1.0) == pytest.approx(0.4, abs=0.001)
        assert distrib.get_prob_density(-2.0) == pytest.approx(0, abs=0.001)
        assert distrib.get_prob_density(0.9) == pytest.approx(0.4, abs=0.001)
        assert distrib.get_prob_density(1.2) == pytest.approx(0.4, abs=0.0001)
        assert distrib.get_prob_density(2.2) == pytest.approx(0.2, abs=0.001)
        assert distrib.get_prob_density(2.7) == pytest.approx(0.2, abs=0.001)
        assert distrib.get_prob_density(5.0) == pytest.approx(0, abs=0.0001)
        assert distrib.get_cumulative_prob(0.5) == pytest.approx(0, abs=0.0001)
        assert distrib.get_cumulative_prob(1.1) == pytest.approx(0.6,
                                                                 abs=0.0001)
        assert distrib.get_cumulative_prob(2.4) == pytest.approx(0.6,
                                                                 abs=0.0001)
        assert distrib.get_cumulative_prob(2.5) == pytest.approx(0.9,
                                                                 abs=0.0001)
        assert distrib.get_cumulative_prob(2.6) == pytest.approx(0.9,
                                                                 abs=0.0001)

        assert distrib.get_function().get_mean()[0] == pytest.approx(1.35,
                                                                     abs=0.01)
        assert distrib.get_function().get_variance()[0] == pytest.approx(
            0.47, abs=0.01)
Пример #5
0
    def test_dep_empirical_distrib_continuous(self):
        bn = BNetwork()
        builder = CategoricalTableBuilder("var1")
        builder.add_row(ValueFactory.create("one"), 0.7)
        builder.add_row(ValueFactory.create("two"), 0.3)
        var1 = ChanceNode("var1", builder.build())
        bn.add_node(var1)

        continuous = ContinuousDistribution("var2",
                                            UniformDensityFunction(-1.0, 3.0))
        continuous2 = ContinuousDistribution(
            "var2", GaussianDensityFunction(3.0, 10.0))

        table = ConditionalTable("var2")
        table.add_distrib(Assignment("var1", "one"), continuous)
        table.add_distrib(Assignment("var1", "two"), continuous2)
        var2 = ChanceNode("var2", table)
        var2.add_input_node(var1)
        bn.add_node(var2)

        inference = InferenceChecks()
        inference.check_cdf(bn, "var2", -1.5, 0.021)
        inference.check_cdf(bn, "var2", 0., 0.22)
        inference.check_cdf(bn, "var2", 2., 0.632)
        inference.check_cdf(bn, "var2", 8., 0.98)
Пример #6
0
    def test_empirical_distrib(self):
        st = CategoricalTableBuilder("var1")

        st.add_row("val1", 0.6)
        st.add_row("val2", 0.4)

        builder = ConditionalTableBuilder("var2")
        builder.add_row(Assignment("var1", "val1"), "val1", 0.9)
        builder.add_row(Assignment("var1", "val1"), "val2", 0.1)
        builder.add_row(Assignment("var1", "val2"), "val1", 0.2)
        builder.add_row(Assignment("var1", "val2"), "val2", 0.8)

        bn = BNetwork()
        var1 = ChanceNode("var1", st.build())
        bn.add_node(var1)

        var2 = ChanceNode("var2", builder.build())
        var2.add_input_node(var1)
        bn.add_node(var2)

        sampling = SamplingAlgorithm(2000, 500)

        distrib = sampling.query_prob(bn, "var2", Assignment("var1", "val1"))
        assert distrib.get_prob("val1") == pytest.approx(0.9, abs=0.05)
        assert distrib.get_prob("val2") == pytest.approx(0.1, abs=0.05)

        distrib2 = sampling.query_prob(bn, "var2")
        assert distrib2.get_prob("val1") == pytest.approx(0.62, abs=0.05)
        assert distrib2.get_prob("val2") == pytest.approx(0.38, abs=0.05)
Пример #7
0
    def concatenate(self, other):
        """
        Concatenate the values for the two tables (assuming the two tables share the same variable).

        :param other: the table to concatenate
        :return: the table resulting from the concatenation
        """
        if self._variable != other.get_variable():
            self.log.warning("can only concatenate tables with same variable")
            raise ValueError()

        from bn.distribs.distribution_builder import CategoricalTableBuilder
        builder = CategoricalTableBuilder(self._variable)
        for s_value in self.get_values():
            for o_value in other.get_values():
                try:
                    value = s_value.concatenate(o_value)
                    builder.add_row(
                        value,
                        self.get_prob(s_value) * other.get_prob(o_value))
                except:
                    self.log.warning("could not concatenated the tables ",
                                     self, " and ", other)

        return builder.build()
Пример #8
0
    def test_conversion1_distrib(self):
        builder = CategoricalTableBuilder("var1")

        builder.add_row(1.5, 0.7)
        builder.add_row(2.0, 0.1)
        builder.add_row(-3.0, 0.2)
        assert builder.is_well_formed()
        table = builder.build()
        assert table.get_prob("2.0") == pytest.approx(0.1, abs=0.001)

        continuous = table.to_continuous()
        assert continuous.get_prob_density(2.0) == pytest.approx(0.2,
                                                                 abs=0.001)
        assert continuous.get_prob_density(2.1) == pytest.approx(0.2,
                                                                 abs=0.001)
        assert continuous.get_cumulative_prob(-3.1) == pytest.approx(0.0,
                                                                     abs=0.001)
        assert continuous.get_cumulative_prob(1.6) == pytest.approx(0.9,
                                                                    abs=0.001)

        table2 = continuous.to_discrete()
        assert len(table2.get_values()) == 3
        assert table2.get_prob(2.0) == pytest.approx(0.1, abs=0.05)

        sum = 0
        for _ in range(10000):
            sum += continuous.sample().get_double()

        assert sum / 10000.0 == pytest.approx(0.65, abs=0.1)
Пример #9
0
 def test_closest(self):
     builder = CategoricalTableBuilder('v')
     builder.add_row(np.array([0.2, 0.2]), 0.3)
     builder.add_row(np.array([0.6, 0.6]), 0.4)
     table = builder.build()
     assert table.get_prob(np.array([0.25, 0.3])) == pytest.approx(0.3,
                                                                   abs=0.01)
     assert table.get_prob(np.array([0.5, 0.4])) == pytest.approx(0.4,
                                                                  abs=0.01)
Пример #10
0
    def create_chance_node(node):
        """
        Creates a new chance node corresponding to the XML specification

        :param node: the XML node
        :return: the resulting chance node encoded
        """
        if len(node.attrib) == 0:
            raise ValueError()

        try:
            label = node.attrib['id'].strip()
        except:
            raise ValueError()

        if len(label) == 0:
            raise ValueError()

        builder = CategoricalTableBuilder(label)
        distrib = None

        for child_node in node:
            if child_node.tag == 'value':
                # first case: the chance node is described as a categorical table.
                # extracting the value
                prob = XMLStateReader._get_probability(child_node)
                value = ValueFactory.create(child_node.text.strip())
                builder.add_row(value, prob)
            elif child_node.tag == 'distrib':
                # second case: the chance node is described by a parametric continuous distribution.
                try:
                    distrib_type = child_node.attrib['type'].lower()

                    if distrib_type == 'gaussian':
                        distrib = ContinuousDistribution(
                            label, XMLStateReader._get_gaussian(child_node))
                    elif distrib_type == 'uniform':
                        distrib = ContinuousDistribution(
                            label, XMLStateReader._get_uniform(child_node))
                    elif distrib_type == 'dirichlet':
                        distrib = ContinuousDistribution(
                            label, XMLStateReader._get_dirichlet(child_node))
                except:
                    raise ValueError()

        if distrib is not None:
            return ChanceNode(label, distrib)

        total_prob = builder.get_total_prob()
        # TODO: check eps
        eps = 1e-8
        if total_prob > 1.0 + eps:
            raise ValueError()

        return ChanceNode(label, builder.build())
Пример #11
0
    def _add_special_input(self, text):
        special_input = text.split('=')[0].strip()
        text = text.split('=')[1].strip()

        table = StringUtils.get_table_from_input(text)

        builder = CategoricalTableBuilder(special_input)
        for key, value in table.items():
            builder.add_row(key, value)

        self._system.add_content(builder.build())
Пример #12
0
    def test_pruning6(self):
        initial_state = copy(TestPruning.system.get_state())

        builder = CategoricalTableBuilder("var1")
        builder.add_row("value2", 0.9)
        TestPruning.system.get_state().add_to_state(builder.build())

        TestPruning.inference.check_prob(TestPruning.system.get_state(), "o", "and we have var1=value2", 0.3)
        TestPruning.inference.check_prob(TestPruning.system.get_state(), "o", "and we have localvar=value1", 0.2)
        TestPruning.inference.check_prob(TestPruning.system.get_state(), "o", "and we have localvar=value3", 0.31)

        TestPruning.system.get_state().reset(initial_state)
    def get_prob_distrib(self, condition):
        """
        Returns the categorical table associated with the conditional assignment.

        :param condition: condition the conditional assignment
        :return: the corresponding categorical table on the true and false values
                if the table could not be extracted for the condition
        """
        positive_prob = self.get_prob(condition)
        builder = CategoricalTableBuilder(self.get_variable())
        builder.add_row(True, positive_prob)
        builder.add_row(False, 1. - positive_prob)
        return builder.build()
 def test_default_value(self):
     builder = CategoricalTableBuilder("Burglary")
     builder.add_row(ValueFactory.create(False), 0.8)
     assert builder.build().get_prob(ValueFactory.none()) == pytest.approx(
         0.199, abs=0.01)
     builder.remove_row(ValueFactory.create(False))
     assert builder.build().get_prob(ValueFactory.none()) == pytest.approx(
         0.999, abs=0.01)
     # assert node.hasProb(Assignment(), ValueFactory.none())
     builder = CategoricalTableBuilder("Burglary")
     builder.add_row(ValueFactory.create(False), 0.999)
     assert builder.build().get_prob(ValueFactory.none()) == pytest.approx(
         0.0, abs=0.01)
Пример #15
0
    def test_planning4(self):
        system = DialogueSystem(TestPlanning.domain3)

        system.get_settings().show_gui = False

        system.get_settings().horizon = 3
        system.start_system()

        t1 = CategoricalTableBuilder("a_u")
        t1.add_row("Ask(Coffee)", 0.95)
        t1.add_row("Ask(Tea)", 0.02)
        system.add_content(t1.build())
        TestPlanning.inference.check_prob(system.get_state(), "a_m",
                                          "Do(Coffee)", 1.0)
Пример #16
0
    def get_n_best(self, n_best):
        """
        Returns a subset of the N values in the table with the highest probability.

        :param n_best: the number of values to select
        :return: the distribution with the subset of values
        """
        n_table = InferenceUtils.get_n_best(self._table, n_best)

        from bn.distribs.distribution_builder import CategoricalTableBuilder
        builder = CategoricalTableBuilder(self._variable)
        for v in n_table.keys():
            builder.add_row(v, n_table[v])

        return builder.build().to_discrete()
    def test_copy(self):
        bn = NetworkExamples.construct_basic_network()

        bn2 = copy(bn)
        b = bn.get_chance_node("Burglary")

        builder = CategoricalTableBuilder("Burglary")
        builder.add_row(ValueFactory.create(True), 0.2)
        builder.add_row(ValueFactory.create(False), 0.8)
        b.set_distrib(builder.build())

        value = bn.get_utility_node("Util1")
        value.add_utility(
            Assignment(Assignment("Burglary", True), "Action",
                       ValueFactory.create("DoNothing")), -20.0)

        assert len(bn.get_node("Burglary").get_output_nodes()) == 3
        assert len(bn2.get_node("Burglary").get_output_nodes()) == 3

        assert len(bn.get_node("Alarm").get_output_nodes()) == 2
        assert len(bn2.get_node("Alarm").get_output_nodes()) == 2
        assert len(bn.get_node("Alarm").get_input_nodes()) == 2
        assert len(bn2.get_node("Alarm").get_input_nodes()) == 2

        assert len(bn.get_node("Util1").get_input_nodes()) == 2
        assert len(bn2.get_node("Util1").get_input_nodes()) == 2

        assert len(bn2.get_node("Burglary").get_values()) == 2
        assert len(bn2.get_node("Alarm").get_values()) == 2
        assert len(bn2.get_node("MaryCalls").get_values()) == 2

        assert ValueFactory.create(True) in bn2.get_node(
            "Burglary").get_values()

        assert bn2.get_chance_node("Burglary").get_prob(
            ValueFactory.create(True)) == pytest.approx(0.001, abs=0.0001)
        assert bn2.get_chance_node("Alarm").get_prob(
            Assignment(["Burglary", "Earthquake"]),
            ValueFactory.create(True)) == pytest.approx(0.95, abs=0.0001)
        assert bn2.get_chance_node("JohnCalls").get_prob(
            Assignment("Alarm"),
            ValueFactory.create(True)) == pytest.approx(0.9, abs=0.0001)

        assert len(bn2.get_action_node("Action").get_values()) == 3
        assert bn2.get_utility_node("Util2").get_utility(
            Assignment(Assignment("Burglary"), "Action",
                       ValueFactory.create("DoNothing"))) == pytest.approx(
                           -10, abs=0.0001)
Пример #18
0
    def test_1(self):
        system = DialogueSystem(TestRule2.domain)
        eq_factor = EquivalenceDistribution.none_prob
        EquivalenceDistribution.none_prob = 0.1
        old_prune_threshold = StatePruner.value_pruning_threshold
        StatePruner.value_pruning_threshold = 0.0

        system.get_settings().show_gui = False
        system.detach_module(ForwardPlanner)
        system.start_system()

        TestRule2.inference.check_prob(system.get_state(), "a_u^p", "Ask(A)",
                                       0.63)
        TestRule2.inference.check_prob(system.get_state(), "a_u^p", "Ask(B)",
                                       0.27)
        TestRule2.inference.check_prob(system.get_state(), "a_u^p", "None",
                                       0.1)

        builder = CategoricalTableBuilder("a_u")
        builder.add_row("Ask(B)", 0.8)
        builder.add_row("None", 0.2)

        system.get_state().remove_nodes(
            system.get_state().get_action_node_ids())
        system.get_state().remove_nodes(
            system.get_state().get_utility_node_ids())

        system.add_content(builder.build())

        TestRule2.inference.check_prob(system.get_state(), "i_u", "Want(A)",
                                       0.090)
        TestRule2.inference.check_prob(system.get_state(), "i_u", "Want(B)",
                                       0.91)

        TestRule2.inference.check_prob(system.get_state(), "a_u^p", "Ask(B)",
                                       0.91 * 0.9)
        TestRule2.inference.check_prob(system.get_state(), "a_u^p", "Ask(A)",
                                       0.09 * 0.9)
        TestRule2.inference.check_prob(system.get_state(), "a_u^p", "None",
                                       0.1)

        TestRule2.inference.check_prob(system.get_state(), "a_u", "Ask(B)",
                                       0.918)
        TestRule2.inference.check_prob(system.get_state(), "a_u", "None",
                                       0.081)

        EquivalenceDistribution.none_prob = eq_factor
        StatePruner.value_pruning_threshold = old_prune_threshold
Пример #19
0
    def test_nbest(self):
        builder = CategoricalTableBuilder("test")

        builder.add_row("bla", 0.5)
        builder.add_row("blo", 0.1)
        table = builder.build()
        for _ in range(10):
            assert str(table.get_best()) == "bla"

        builder2 = MultivariateTableBuilder()
        builder2.add_row(Assignment("test", "bla"), 0.5)
        builder2.add_row(Assignment("test", "blo"), 0.1)

        table2 = builder2.build()
        for _ in range(10):
            assert str(table2.get_best().get_value("test")) == "bla"
Пример #20
0
    def get_marginal(self, variable):
        """
        Returns the marginal distribution P(Xi) for a random variable Xi in X1,...Xn.

        :param variable: the variable Xi
        :return: the distribution P(Xi).
        """
        from bn.distribs.distribution_builder import CategoricalTableBuilder
        marginal = CategoricalTableBuilder(variable)

        for row in self.get_values():
            prob = self._table.get(row)
            if prob > 0.:
                marginal.add_row(row.get_value(variable), prob)

        return marginal.build()
Пример #21
0
    def get_prob_distrib(self, assignment):
        output = self.get_cached_output(assignment)

        builder = CategoricalTableBuilder(self._id)
        for effect in output.get_effects():
            param = output.get_parameter(effect)
            param_value = param.get_value(assignment)
            if param_value > 0:
                builder.add_row(effect, param_value)

        if builder.is_empty():
            self.log.warning(
                "probability table is empty (no effects) for input %s and rule %s"
                % (assignment, str(self)))
            # raise ValueError()

        return builder.build()
Пример #22
0
    def add_user_input(self, user_input):
        """
        Adds the user input (as a N-best list, where each hypothesis is associated
        with a probability) to the dialogue state and subsequently updates it.

        :param user_input: the user input as an N-best list
        :return: the variables that were updated in the process not be updated
        """
        # user_input: N-best list, where each hypothesis is associated with a probability
        var = self._settings.user_input if not self._settings.inverted_role else self._settings.system_output

        builder = CategoricalTableBuilder(var)

        for input in user_input.keys():
            builder.add_row(input, user_input.get(input))

        return self.add_content(builder.build())
Пример #23
0
    def add_incremental_user_input(self, user_input, follow_previous):
        """
        Adds the incremental user input (expressed as an N-best list) to the current
        dialogue state, and subsequently updates it. If followPrevious is set to true,
        the content is concatenated with the current distribution for the variable.
        This allows (for instance) to perform incremental updates of user utterances.

        :param user_input: the user input to add / concatenate
        :param follow_previous: whether the results should be concatenated to the previous values,
                                or reset the content (e.g. when starting a new
                                utterance)
        :return: the set of variables that have been updated update failed
        """
        builder = CategoricalTableBuilder(self._settings.user_input)

        for input in user_input.key_set():
            builder.add_row(input, user_input.get(input))

        return self.add_incremental_content(builder.build(), follow_previous)
Пример #24
0
    def construct_basic_network2():
        network = NetworkExamples.construct_basic_network()
        builder = CategoricalTableBuilder("Burglary")
        builder.add_row(ValueFactory.create(True), 0.1)
        builder.add_row(ValueFactory.create(False), 0.9)
        network.get_chance_node("Burglary").set_distrib(builder.build())
        builder = CategoricalTableBuilder("Earthquake")
        builder.add_row(ValueFactory.create(True), 0.2)
        builder.add_row(ValueFactory.create(False), 0.8)
        network.get_chance_node("Earthquake").set_distrib(builder.build())

        return network
Пример #25
0
    def test_2(self):
        system = DialogueSystem(TestRule2.domain)
        system.get_settings().show_gui = False
        system.detach_module(ForwardPlanner)
        eq_factor = EquivalenceDistribution.none_prob
        EquivalenceDistribution.none_prob = 0.1
        old_prune_threshold = StatePruner.value_pruning_threshold
        StatePruner.value_pruning_threshold = 0.0
        system.start_system()

        TestRule2.inference.check_prob(system.get_state(), "u_u2^p", "Do A",
                                       0.216)
        TestRule2.inference.check_prob(system.get_state(), "u_u2^p",
                                       "Please do C", 0.027)
        TestRule2.inference.check_prob(system.get_state(), "u_u2^p",
                                       "Could you do B?", 0.054)
        TestRule2.inference.check_prob(system.get_state(), "u_u2^p",
                                       "Could you do A?", 0.162)
        TestRule2.inference.check_prob(system.get_state(), "u_u2^p", "none",
                                       0.19)

        builder = CategoricalTableBuilder("u_u2")
        builder.add_row("Please do B", 0.4)
        builder.add_row("Do B", 0.4)

        system.get_state().remove_nodes(
            system.get_state().get_action_node_ids())
        system.get_state().remove_nodes(
            system.get_state().get_utility_node_ids())
        system.add_content(builder.build())

        TestRule2.inference.check_prob(system.get_state(), "i_u2", "Want(B)",
                                       0.654)
        TestRule2.inference.check_prob(system.get_state(), "i_u2", "Want(A)",
                                       0.1963)
        TestRule2.inference.check_prob(system.get_state(), "i_u2", "Want(C)",
                                       0.0327)
        TestRule2.inference.check_prob(system.get_state(), "i_u2", "none",
                                       0.1168)

        EquivalenceDistribution.none_prob = eq_factor
        StatePruner.value_pruning_threshold = old_prune_threshold
Пример #26
0
    def test_6(self):
        InferenceChecks.exact_threshold = 0.06

        system = DialogueSystem(TestRule1.domain)
        system.detach_module(ForwardPlanner)
        system.get_settings().show_gui = False
        system.start_system()

        builder = CategoricalTableBuilder("var1")
        builder.add_row("value2", 0.9)
        system.add_content(builder.build())

        TestRule1.inference.check_prob(system.get_state(), "o",
                                       "and we have var1=value2", 0.9)
        TestRule1.inference.check_prob(system.get_state(), "o",
                                       "and we have localvar=value1", 0.05)
        TestRule1.inference.check_prob(system.get_state(), "o",
                                       "and we have localvar=value3", 0.04)

        StatePruner.enable_reduction = True
Пример #27
0
    def test_simple_distrib(self):
        builder = CategoricalTableBuilder("var1")
        builder.add_row("val1", 0.7)
        assert not builder.is_well_formed()
        builder.add_row("val2", 0.3)
        assert builder.is_well_formed()
        table = builder.build()

        assert table.get_prob("val1") == pytest.approx(0.7, abs=0.001)
        assert table.get_prob("val1") == pytest.approx(0.7, abs=0.001)
        table2 = MultivariateTableBuilder()
        table2.add_row(Assignment(Assignment("var2", "val3"), "var1", "val2"),
                       0.9)
        # assert not table2.is_well_formed()
        table2.add_row(Assignment(Assignment("var2", "val3"), "var1", "val1"),
                       0.1)
        assert table2.is_well_formed()
        assert table2.build().get_prob(
            Assignment(
                [Assignment("var1", "val1"),
                 Assignment("var2", "val3")])) == pytest.approx(0.1, abs=0.001)
Пример #28
0
    def get_prob_distrib(self, condition):
        """
        Fills the cache with the resulting table for the given condition

        :param condition: the condition for which to fill the cache
        """
        builder = CategoricalTableBuilder(self._base_var + self._primes)

        full_effects = list()
        for inputVal in condition.get_values():
            if isinstance(inputVal, Effect):
                full_effects.extend(inputVal.get_sub_effects())

        full_effect = Effect(full_effects)
        values = full_effect.get_values(self._base_var)
        if full_effect.is_non_exclusive(self._base_var):
            add_val = ValueFactory.create(list(values.keys()))
            builder.add_row(add_val, 1.0)
        elif len(values) > 0:
            total = 0.0
            for f in values.values():
                total += float(f)
            for v in values.keys():
                builder.add_row(v, values[v] / total)
        else:
            builder.add_row(ValueFactory.none(), 1.0)

        return builder.build()
Пример #29
0
    def test_IS2013(self):
        domain = XMLDomainReader.extract_domain(TestLearning.domain_file)
        params = XMLStateReader.extract_bayesian_network(TestLearning.parameters_file, "parameters")
        domain.set_parameters(params)
        system = DialogueSystem(domain)
        system.get_settings().show_gui = False
        system.detach_module(ForwardPlanner)
        Settings.nr_samples = Settings.nr_samples * 3
        Settings.max_sampling_time = Settings.max_sampling_time * 10
        system.start_system()

        init_mean = system.get_content("theta_1").to_continuous().get_function().get_mean()

        builder = CategoricalTableBuilder("a_u")
        builder.add_row("Move(Left)", 1.0)
        builder.add_row("Move(Right)", 0.0)
        builder.add_row("None", 0.0)
        system.add_content(builder.build())
        system.get_state().remove_nodes(system.get_state().get_utility_node_ids())
        system.get_state().remove_nodes(system.get_state().get_action_node_ids())

        after_mean = system.get_content("theta_1").to_continuous().get_function().get_mean()

        assert after_mean[0] - init_mean[0] > 0.04
        assert after_mean[1] - init_mean[1] < 0.04
        assert after_mean[2] - init_mean[2] < 0.04
        assert after_mean[3] - init_mean[3] < 0.04
        assert after_mean[4] - init_mean[4] < 0.04
        assert after_mean[5] - init_mean[5] < 0.04
        assert after_mean[6] - init_mean[6] < 0.04
        assert after_mean[7] - init_mean[7] < 0.04

        Settings.nr_samples = int(Settings.nr_samples / 3)
        Settings.max_sampling_time = Settings.max_sampling_time / 10
    def test_table_expansion(self):
        bn = NetworkExamples.construct_basic_network()

        builder = CategoricalTableBuilder("HouseSize")
        builder.add_row(ValueFactory.create("Small"), 0.7)
        builder.add_row(ValueFactory.create("Big"), 0.2)
        builder.add_row(ValueFactory.create("None"), 0.1)

        node = ChanceNode("HouseSize", builder.build())
        bn.add_node(node)
        bn.get_node("Burglary").add_input_node(node)
        assert bn.get_chance_node("Burglary").get_prob(
            Assignment(["HouseSize", "Small"]),
            ValueFactory.create(True)) == pytest.approx(0.001, abs=0.0001)
        assert bn.get_chance_node("Burglary").get_prob(
            Assignment(["HouseSize", "Big"]),
            ValueFactory.create(True)) == pytest.approx(0.001, abs=0.0001)
        bn.get_node("Alarm").add_input_node(node)
        assert bn.get_chance_node("Alarm").get_prob(
            Assignment(["Burglary", "Earthquake"]),
            ValueFactory.create(True)) == pytest.approx(0.95, abs=0.0001)
        assert bn.get_chance_node("Alarm").get_prob(
            Assignment(Assignment(["Burglary", "Earthquake"]), "HouseSize",
                       ValueFactory.create("None")),
            ValueFactory.create(True)) == pytest.approx(0.95, abs=0.0001)