def test_traffic_light_given_risk(self):
        print('Test: Traffic Light and Risk given Risk')

        self.init_traffic_light()

        self.risk.set_value(key_evidence(), PtrValue(0))
        # self.risk.set_value(key_evidence(), Probability(evidence_index=0))
        child_atomspace = self.create_child_atomspace()
        marginalization_divisor = belief_propagation(child_atomspace)

        self.delete_child_atomspace()
        self.assertAlmostEqual(0.51, marginalization_divisor)

        # Marginalization dividend
        # P(TL=Yellow, R=High)
        # TL=Yellow, index=1
        # R=High, index=0

        self.traffic_light.set_value(key_evidence(), PtrValue("yellow"))
        self.risk.set_value(key_evidence(), PtrValue(0))
        child_atomspace = self.create_child_atomspace()
        marginalization_dividend = belief_propagation(child_atomspace)

        self.delete_child_atomspace()
        self.assertAlmostEqual(0.1375, marginalization_dividend)

        probability_risk_given_traffic_light = marginalization_dividend / marginalization_divisor
        self.assertAlmostEqual(0.27, probability_risk_given_traffic_light, 2)
Пример #2
0
    def test_call_grounded_object_predicate(self):
        obj = TestObject("some object")

        value = PtrValue(obj)

        ref = value.value()
        self.assertEqual(ref.name, "some object")
Пример #3
0
def set_value(atom, value, tv=False):
    if tv:
        key = atom.atomspace.add_node(types.PredicateNode, "cogNet-tv")
        assert isinstance(value, TTruthValue) or isinstance(value, CogModule)
    else:
        key = atom.atomspace.add_node(types.PredicateNode, "cogNet")
    atom.set_value(key, PtrValue(value))
Пример #4
0
def set_variable_domain(variable, v, joint_table_atom, index):
    """
    Sets domain to the variable in factor graph.
    The domain of the variable is 1 if the evidence is set to the given v.
    Otherwise the domain of the variable is just dimension in the joint probability table
    where the variable has the given index.

    :param variable: variable in factor graph
    :param v: original variable in the bayesian network
    :param joint_table_atom: atom which contains joint probability table value
    :param index: position of the given variable in the joint probability table
    """
    tensor = get_probability_tensor(joint_table_atom)

    evidence_index_value = get_evidence_index(v)
    if evidence_index_value is None:
        domain = tensor.shape[index]
    else:
        domain = 1

    # print("variable:", variable.name, "domain:", domain)

    current_domain_value = variable.get_value(key_domain())
    if not current_domain_value:
        variable.set_value(key_domain(), PtrValue(domain))
    else:
        assert current_domain_value.value() == domain, "The variable domain should be consistent " \
                                                       "with already present domain"
Пример #5
0
    def test_init_factor_graph_implication_link_product_rule3(self):
        a = ConceptNode("A")
        b = ConceptNode("B")
        c = ConceptNode("C")
        d = ConceptNode("D")

        implication = ImplicationLink(ListLink(a, b, c), d)
        implication_probability = [[[[0.9, 0.1], [0.8, 0.2]],
                                    [[0.7, 0.3], [0.6, 0.4]]],
                                   [[[0.9, 0.1], [0.8, 0.2]],
                                    [[0.7, 0.3], [0.6, 0.4]]]]

        # implication.set_value(key_probability(), PtrValue(Probability(implication_probability)))
        implication.set_value(key_probability(),
                              PtrValue(implication_probability))

        child_atomspace = self.create_child_atomspace()
        execute_atom(child_atomspace,
                     init_factor_graph_implication_link_product_rule())

        # check domain
        self.check_domain_value(ConceptNode("Variable-A"), 2)
        self.check_domain_value(ConceptNode("Variable-B"), 2)
        self.check_domain_value(ConceptNode("Variable-C"), 2)
        self.check_domain_value(ConceptNode("Variable-D"), 2)

        # check probability tensors
        self.check_tensor_value(ConceptNode("Factor-A-B-C-D"),
                                implication_probability)

        self.delete_child_atomspace()
Пример #6
0
def send_message_factor_variable(message, factor, variable):
    # print('send message (f-v):', factor.name, variable.name)
    arguments = factor.get_value(key_arguments()).value()
    tensor = factor.get_value(key_tensor()).value()

    for index, arg_name in reversed(list(enumerate(arguments))):
        if arg_name == variable.name:
            # This is the target variable. It's message is not used for tensor message multiplication.
            if index != 0:
                # Transpose tensor so the target variable axis becomes first
                axes = [index] + list(range(index))
                tensor = np.transpose(tensor, axes)
        else:
            v = ConceptNode(arg_name)
            # Note:
            # Do not create message predicate for the target variable.
            # It breaks send message variable factor rule.
            msg_predicate = get_message_predicate(v, factor)
            msg_value = msg_predicate.get_value(key_message())
            assert msg_value, "Value must be present for message: " + factor.name + "->" + arg_name
            msg = msg_value.value()
            tensor_index = len(tensor.shape) - 1
            tensor = np.tensordot(tensor, msg, axes=(tensor_index, 0))

    message.set_value(key_message(), PtrValue(tensor))
    print('send message (f-v):', factor.name, variable.name,
          message.get_value(key_message()).value())
Пример #7
0
 def __init__(self, atomspace):
     super().__init__()
     self.atomspace = atomspace
     self.mnist = MnistNet(ConceptNode("mnist"))
     self.sum_prob = SumProb(ConceptNode("SumProb"))
     self.digit_prob = ProbOfDigit(ConceptNode("ProbOfDigit"))
     self.torch_sum = TorchSum(ConceptNode("TorchSum"))
     for i in range(10):
         NumberNode(str(i)).set_value(PredicateNode("cogNet"), PtrValue(i))
         InheritanceLink(NumberNode(str(i)), ConceptNode("range"))
Пример #8
0
    def test_pass_value_via_atom(self):
        obj = TestObject("some object")
        container = ConceptNode("container")
        key = ConceptNode("key")
        container.set_value(key, PtrValue(obj))

        value = container.get_value(key)

        ref = value.value()
        self.assertEqual(ref.name, "some object")
Пример #9
0
    def test_init_factor_graph_implication_link_product_rule2_given_b_c(self):
        self.init_factor_graph_implication_link_product_rule2()

        child_atomspace = self.create_child_atomspace()

        ConceptNode("B").set_value(key_evidence(), PtrValue(0))
        ConceptNode("C").set_value(key_evidence(), PtrValue(2))

        execute_atom(child_atomspace,
                     init_factor_graph_implication_link_product_rule())

        # check domain
        self.check_domain_value(ConceptNode("Variable-A"), 1)
        self.check_domain_value(ConceptNode("Variable-B"), 1)
        self.check_domain_value(ConceptNode("Variable-C"), 1)

        # check probability tensors
        self.check_tensor_value(ConceptNode("Factor-A-B-C"), np.array([0.7]))

        self.delete_child_atomspace()
Пример #10
0
    def init_factor_graph_implication_link_product_rule2(self):
        a = ConceptNode("A")
        b = ConceptNode("B")
        c = ConceptNode("C")

        implication = ImplicationLink(ListLink(a, b), c)

        self.implication_probability = [[[0.1, 0.2, 0.7], [0.2, 0.3, 0.5]]]

        # implication.set_value(key_probability(), PtrValue(Probability(self.implication_probability)))
        implication.set_value(key_probability(),
                              PtrValue(self.implication_probability))
Пример #11
0
 def __init__(self, atomspace):
     super().__init__()
     self.atomspace = atomspace
     self.mnist = MnistNet(ConceptNode("mnist"))
     self.prod = Product(ConceptNode("Product"))
     self.digit_prob = ProbOfDigit(ConceptNode("ProbOfDigit"))
     self.torch_sum = TorchSum(ConceptNode("TorchSum"))
     self.inh_weights = torch.nn.Parameter(torch.Tensor([0.3] * 10))
     #  create NumberNodes
     for i in range(10):
         NumberNode(str(i)).set_value(PredicateNode("cogNet"), PtrValue(i))
         inh1 = InheritanceLink(NumberNode(str(i)), ConceptNode("range"))
    def init_traffic_light(self):
        self.traffic_light = ConceptNode('TrafficLight')
        self.risk = ConceptNode('Risk')
        self.risk_given_traffic_light = ImplicationLink(
            self.traffic_light, self.risk)

        # [Green, Yellow, Red]
        self.traffic_light_probability = [0.4, 0.25, 0.35]
        self.traffic_light_risk_joint_probability = [[0.1, 0.9], [0.55, 0.45],
                                                     [0.95, 0.05]]

        self.traffic_light.set_value(key_domain(),
                                     PtrValue(["green", "yellow", "blue"]))
        self.traffic_light.set_value(key_probability(),
                                     PtrValue({
                                         "green": 0.4,
                                         "yellow": 0.25
                                     }))
        self.risk_given_traffic_light.set_value(
            key_probability(),
            PtrValue(self.traffic_light_risk_joint_probability))
Пример #13
0
    def init_rain_wet_grass_bayesian_network(self):
        print('Test: Sherlock Holmes and  Wet Grass')
        self.rain = ConceptNode('Rain')
        self.sprinkler = ConceptNode('Sprinkler')
        self.holmes_grass = ConceptNode('HolmesGrass')
        self.watson_grass = ConceptNode('WatsonGrass')
        self.watson_grass_given_rain = ImplicationLink(self.rain,
                                                       self.watson_grass)
        self.holmes_grass_given_sprinkler_rain = ImplicationLink(
            ListLink(self.sprinkler, self.rain), self.holmes_grass)

        self.rain_probability = [0.2, 0.8]
        self.rain.set_value(key_domain(), PtrValue(["true", "false"]))
        self.rain.set_value(key_probability(), PtrValue({"true": 0.2}))

        self.sprinkler_probability = np.array([0.1, 0.9])
        self.sprinkler.set_value(key_domain(),
                                 PtrValue(["switch-on", "switch-off"]))
        self.sprinkler.set_value(key_probability(),
                                 PtrValue({"switch-on": 0.1}))

        self.watson_grass_given_rain_probability = [[1.0, 0.0], [0.2, 0.8]]
        self.watson_grass_given_rain.set_value(
            key_probability(),
            PtrValue(self.watson_grass_given_rain_probability))

        self.holmes_grass_given_sprinkler_rain_probability = [[[1.0, 0.0],
                                                               [0.9, 0.1]],
                                                              [[1.0, 0.0],
                                                               [0.0, 1.0]]]
        self.holmes_grass_given_sprinkler_rain.set_value(
            key_probability(),
            PtrValue(self.holmes_grass_given_sprinkler_rain_probability))
Пример #14
0
def send_message_variable_factor(message, variable, factor, factors):
    domain = variable.get_value(key_domain()).value()
    message_value = np.ones(domain)

    for f in factors.get_out():
        if f != factor:
            msg_predicate = get_message_predicate(f, variable)
            msg_value = msg_predicate.get_value(key_message()).value()
            message_value = message_value * msg_value

    message.set_value(key_message(), PtrValue(message_value))
    print('send message (v-f):', variable.name, factor.name,
          message.get_value(key_message()).value())
Пример #15
0
def set_factor_tensor(factor, variables, joint_table_atom):
    """
    Sets tensor for the given factor.
    Tensor is taken from  joint probability table.
    If a given variable has an evidence index, only evidence part of the joint table is taken.

    :param factor: factor in factor graph
    :param variables: original variables from the bayesian network
    :param joint_table_atom: atom which contains joint probability table value
    """

    arguments = [get_variable_node_name(v) for v in variables]
    factor.set_value(key_arguments(), PtrValue(arguments))

    tensor = get_probability_tensor(joint_table_atom)

    for index, v in enumerate(variables):
        evidence_index = get_evidence_index(v)
        if evidence_index is not None:
            tensor = np.take(tensor, [evidence_index], index)

    # print("factor:", factor.name, "tensor:", tensor)
    factor.set_value(key_tensor(), PtrValue(tensor))
Пример #16
0
    def test_variable_evidence(self):
        variableA = ConceptNode("A")
        variableA.set_value(key_domain(), PtrValue(["a1", "a2"]))
        variableA.set_value(key_probability(), PtrValue({"a1": 0.7}))

        variableA.set_value(key_evidence(), PtrValue(0))
        self.assertEqual(0, get_evidence_index(variableA))

        variableA.set_value(key_evidence(), PtrValue(1))
        self.assertEqual(1, get_evidence_index(variableA))

        variableA.set_value(key_evidence(), PtrValue("a1"))
        self.assertEqual(0, get_evidence_index(variableA))

        variableA.set_value(key_evidence(), PtrValue("a2"))
        self.assertEqual(1, get_evidence_index(variableA))

        variableB = ConceptNode("B")
        variableB.set_value(key_domain(), PtrValue(["b1", "b2"]))
        variableB.set_value(key_evidence(), PtrValue("b1"))
        self.assertEqual(0, get_evidence_index(variableB))
Пример #17
0
    def test_init_factor_graph_implication_link_rule(self):
        a = ConceptNode("A")
        b = ConceptNode("B")

        implication = ImplicationLink(a, b)
        implication_probability = [[0.9, 0.1], [0.8, 0.2]]
        implication.set_value(key_probability(),
                              PtrValue(implication_probability))

        child_atomspace = self.create_child_atomspace()
        execute_atom(child_atomspace,
                     init_factor_graph_implication_link_rule())

        # check domain
        self.check_domain_value(ConceptNode("Variable-A"), 2)
        self.check_domain_value(ConceptNode("Variable-B"), 2)

        # check probability tensor
        self.check_tensor_value(ConceptNode("Factor-A-B"),
                                implication_probability)

        self.delete_child_atomspace()
Пример #18
0
    def test_variable_probability(self):
        variable = ConceptNode("A")

        variable.set_value(key_probability(), PtrValue([0.2, 0.8]))
        self.check_tensors_equal([0.2, 0.8], get_probability_tensor(variable))

        variable.set_value(key_domain(), PtrValue(["a", "b"]))

        variable.set_value(key_probability(), PtrValue({"a": 0.2, "b": 0.8}))
        self.check_tensors_equal([0.2, 0.8], get_probability_tensor(variable))

        variable.set_value(key_probability(), PtrValue({"a": 0.2}))
        self.check_tensors_equal([0.2, 0.8], get_probability_tensor(variable))

        variable.set_value(key_probability(), PtrValue({"b": 0.8}))
        self.check_tensors_equal([0.2, 0.8], get_probability_tensor(variable))

        variable.set_value(key_domain(), PtrValue(["a", "b", "c"]))
        variable.set_value(key_probability(), PtrValue({"a": 0.1, "c": 0.3}))
        self.check_tensors_equal([0.1, 0.6, 0.3],
                                 get_probability_tensor(variable))
Пример #19
0
string_key = ConceptNode("string-key")
string_node = ConceptNode("String")
string_node.set_value(string_key, StringValue("Hello, World!"))

string_value = string_node.get_value(string_key)
print(string_value.to_list())

string_node.set_value(string_key, StringValue(["Hello", "Opencog!"]))
string_value = string_node.get_value(string_key)
print(string_value.to_list())

string_value = string_node.get_value(string_key)
print(string_value.to_list())

from opencog.atomspace import PtrValue
import numpy as np

# Matrix
# (0, 1)
# (1, 0)
matrix = np.matrix([[0, 1], [1, 0]])

matrix_key = ConceptNode("matrix-key")
matrix_node = ConceptNode("Matrix")
matrix_node.set_value(matrix_key, PtrValue(matrix))

matrix_value = matrix_node.get_value(matrix_key)

print(matrix_value.value())
Пример #20
0
from opencog.type_constructors import *
from opencog.utilities import initialize_opencog
from opencog.atomspace import PtrValue

# Initialize AtomSpace
atomspace = AtomSpace()
initialize_opencog(atomspace)

key = ConceptNode("key")
node = ConceptNode("node")

dict = {"one": 1, "two": 2}

node.set_value(key, PtrValue(dict))

print('value:', node.get_value(key).value())
Пример #21
0
    child_atomspace.clear()
    finalize_opencog()
    initialize_opencog(atomspace)


# Define Atoms and Links
rain = ConceptNode('Rain')
sprinkler = ConceptNode('Sprinkler')
holmes_grass = ConceptNode('HolmesGrass')
watson_grass = ConceptNode('WatsonGrass')
watson_grass_given_rain = ImplicationLink(rain, watson_grass)
holmes_grass_given_sprinkler_rain = ImplicationLink(ListLink(sprinkler, rain), holmes_grass)

# Define probabilities values
# Rain a priory probability
rain.set_value(key_domain(), PtrValue(["true", "false"]))
rain.set_value(key_probability(), PtrValue({"true": 0.2}))

# Sprinkler a priory probability
sprinkler.set_value(key_domain(), PtrValue(["switch-on", "switch-off"]))
sprinkler.set_value(key_probability(), PtrValue({"switch-on": 0.1}))

# Watson Grass given Rain conditional probability table
watson_grass_given_rain_probability = [[1.0, 0.0],
                                       [0.2, 0.8]]
watson_grass_given_rain.set_value(key_probability(), PtrValue(watson_grass_given_rain_probability))

# Holmes Grass given Sprinkler and Rain conditional probability table
holmes_grass_given_sprinkler_rain_probability = [[[1.0, 0.0],
                                                  [0.9, 0.1]],
                                                 [[1.0, 0.0],
Пример #22
0
 def __init__(
     self, atom
 ):  #todo: atom is optional? if not given, generate by address? string name for concept instead?
     super().__init__()
     self.atom = atom
     atom.set_value(PredicateNode("cogNet"), PtrValue(self))
Пример #23
0
    def test_rain_wet_grass(self):
        self.init_rain_wet_grass_bayesian_network()

        # P(HG=wet)
        # P(HG=wet, WG, S, R)
        # HG=wet, index=0
        child_atomspace = self.create_child_atomspace()
        self.holmes_grass.set_value(key_evidence(), PtrValue(0))
        marginalization_divisor = belief_propagation(child_atomspace)

        print('marginalization divisor:', marginalization_divisor)

        # check domain
        self.check_domain_value(ConceptNode("Variable-Rain"), 2)
        self.check_domain_value(ConceptNode("Variable-Sprinkler"), 2)
        self.check_domain_value(ConceptNode("Variable-WatsonGrass"), 2)
        self.check_domain_value(ConceptNode("Variable-HolmesGrass"), 1)

        # check probability tensors
        self.check_tensor_value(ConceptNode("Factor-Rain"),
                                self.rain_probability)
        self.check_tensor_value(ConceptNode("Factor-Sprinkler"),
                                self.sprinkler_probability)
        self.check_tensor_value(ConceptNode("Factor-Rain-WatsonGrass"),
                                self.watson_grass_given_rain_probability)
        self.check_tensor_value(
            ConceptNode("Factor-Sprinkler-Rain-HolmesGrass"),
            np.array([[[1.0], [0.9]], [[1.0], [0.0]]]))

        self.assertAlmostEqual(0.272, marginalization_divisor)

        self.delete_child_atomspace()

        # P(HG=wet, R=true)
        # P(HG=wet, WG, S, R=true)
        # HG=wet, index=0
        # R=true, index=0

        child_atomspace = self.create_child_atomspace()
        self.holmes_grass.set_value(key_evidence(), PtrValue(0))
        self.rain.set_value(key_evidence(), PtrValue(0))
        marginalization_dividend = belief_propagation(child_atomspace)

        print('marginalization dividend:', marginalization_dividend)

        # check probability tensors
        self.check_tensor_value(ConceptNode("Factor-Rain"), np.array([0.2]))
        self.check_tensor_value(ConceptNode("Factor-Sprinkler"),
                                self.sprinkler_probability)
        self.check_tensor_value(ConceptNode("Factor-Rain-WatsonGrass"),
                                np.array([1.0, 0.0]))
        self.check_tensor_value(
            ConceptNode("Factor-Sprinkler-Rain-HolmesGrass"),
            np.array([[[1.0]], [[1.0]]]))

        self.assertAlmostEqual(0.2, marginalization_dividend)

        self.delete_child_atomspace()

        probability_rain_given_holmes_grass = marginalization_dividend / marginalization_divisor

        print('probability rain given Holmes wet grass:',
              probability_rain_given_holmes_grass)

        self.assertAlmostEqual(0.2 / 0.272,
                               probability_rain_given_holmes_grass)
Пример #24
0
def set_value(atom, value):
    key = atom.atomspace.add_node(types.PredicateNode, "cogNet")
    atom.set_value(key, PtrValue(value))