コード例 #1
0
    def test_conjunction_fuzzy_with_virtual_evaluation(self):
        """Test for correct vardecl parameter initialization in BackwardChainer

        vardecl = VariableList() would cause empty set as backward chaining result
        vardecl = UNDEFINED should produce two results: (Item0, large), (Item1, small)
        """

        self.init()

        scheme_eval(self.atomspace, '(load-from-path "fuzzy-conjunction-introduction-config.scm")')
        rbs = ConceptNode("conjunction-rule-base")

        item0 = ConceptNode("Item0")
        item1 = ConceptNode("Item1")
        size = ConceptNode("Size")
        small = ConceptNode("small")
        large = ConceptNode("large")
        InheritanceLink(item0, ConceptNode("Items")).tv = TruthValue(0.9, 0.9)
        InheritanceLink(item1, ConceptNode("Items")).tv = TruthValue(0.9, 0.9)
        InheritanceLink(small, size).tv = TruthValue(1.0, 1.0)
        InheritanceLink(large, size).tv = TruthValue(1.0, 1.0)
        P = GroundedPredicateNode("py:run_predicate")
        X = VariableNode("$X")
        Y = VariableNode("$Y")
        P_A = EvaluationLink(P, ListLink(X, Y))
        target = AndLink(InheritanceLink(Y, size), InheritanceLink(X, ConceptNode("Items")), P_A)

        bc = BackwardChainer(self.atomspace, rbs, target)
        bc.do_chain()
        results = bc.get_results()
        self.assertTrue(len(results.get_out()) == 2)
        del bc
コード例 #2
0
 def test_modus_ponens(self):
     rule_base = ConceptNode('PLN')
     set_ttv(ConceptNode("apple"), TTruthValue((0.8, 0.9)))
     inh = InheritanceLink(ConceptNode("apple"), ConceptNode("fruit"))
     set_ttv(inh, TTruthValue(0.8, 0.4))
     bc = BackwardChainer(self.atomspace, rule_base, ConceptNode("fruit"))
     bc.do_chain()
     result = get_ttv(bc.get_results().out[0])
     self.assertTrue(abs(0.68 - float(result.mean)) < 0.0001)
コード例 #3
0
 def test_modus_ponens(self):
     rule_base = initialize_pln()
     set_ttv(ConceptNode("apple"), TTruthValue((0.8, 0.9)))
     inh = InheritanceModule(ConceptNode("apple"),
                             ConceptNode("fruit"),
                             tv=torch.tensor((0.8, 0.4)))
     bc = BackwardChainer(self.atomspace, rule_base, ConceptNode("fruit"))
     bc.do_chain()
     result = get_ttv(bc.get_results().out[0])
     self.assertTrue((0.68 - float(result.mean)) < 0.00000000000001)
コード例 #4
0
def run_message_passing_ure():
    res = execute_atom(atomspace, directed_message_edge_creation_rule)
    res = execute_atom(atomspace, create_initial_messages_rule)

    fc_message_sending_rule_name = DefinedSchemaNode("fc-message-sending-rule")

    DefineLink(fc_message_sending_rule_name, create_messages_rule)

    fc_message_sending_rbs = ConceptNode("fc-message-sending-rule")

    InheritanceLink(fc_message_sending_rbs, ConceptNode("URE"))

    MemberLink(fc_message_sending_rule_name, fc_message_sending_rbs)

    # Set URE maximum-iterations
    from opencog.scheme_wrapper import scheme_eval

    execute_code = \
        '''
        (use-modules (opencog rule-engine))
        (ure-set-num-parameter (ConceptNode "fc-message-sending-rbs") "URE:maximum-iterations" 30)
        '''

    scheme_eval(atomspace, execute_code)

    # chainer = ForwardChainer(atomspace,
    #                          ConceptNode("fc-message-sending-rule"),
    #                          SetLink())

    # log.set_level('FINE')
    # chainer = ForwardChainer(atomspace,
    #                          ConceptNode("fc-message-sending-rule"),
    #                          get_message(VariableNode("$V1"), VariableNode("$V2")),
    #                          VariableList(
    #                              TypedVariableLink(VariableNode("$V1"), TypeNode("ConceptNode")),
    #                              TypedVariableLink(VariableNode("$V2"), TypeNode("ConceptNode")))
    #                          )

    # chainer = BackwardChainer(atomspace,
    #                          ConceptNode("fc-message-sending-rule"),
    #                          get_message(VariableNode("$V1"), VariableNode("$V2")))

    chainer = BackwardChainer(
        atomspace, ConceptNode("fc-message-sending-rule"),
        get_message(VariableNode("$V1"), VariableNode("$V2")),
        VariableList(
            TypedVariableLink(VariableNode("$V1"), TypeNode("ConceptNode")),
            TypedVariableLink(VariableNode("$V2"), TypeNode("ConceptNode"))))

    chainer.do_chain()

    results = chainer.get_results()
    log.set_level('INFO')

    res = execute_atom(atomspace, create_node_value_rule)
コード例 #5
0
ファイル: test.py プロジェクト: singnet/opencog
 def test_contraposition(self):
     rule_base = ConceptNode('PLN')
     A = PredicateNode('A')
     set_ttv(A, (1.0, 1.0))
     B = PredicateNode('B')
     set_ttv(B, (1.0, 1.0))
     set_ttv(ImplicationLink(A, B), (1.0, 1.0))
     NBNA = ImplicationLink(NotLink(B), NotLink(A))
     bc = BackwardChainer(self.atomspace, rule_base, NBNA)
     bc.do_chain()
     result = bc.get_results().out[0]
     self.assertTrue(0 < get_ttv(result).confidence,
             'fails due to https://github.com/opencog/opencog/issues/3465')
コード例 #6
0
ファイル: test.py プロジェクト: singnet/opencog
 def test_fuzzy_conjunction(self):
     rule_base = ConceptNode('PLN')
     apple = ConceptNode('apple')
     inh_green = InheritanceLink(PredicateNode("green"), ConceptNode("color"))
     set_ttv(inh_green, torch.tensor([0.96, .9]))
     ev_green = EvaluationLink(PredicateNode('green'), apple)
     set_ttv(ev_green, TTruthValue(0.85, 0.95))
     conj = AndLink(ev_green, inh_green)
     bc = BackwardChainer(self.atomspace, rule_base, conj)
     bc.do_chain()
     result = get_ttv(bc.get_results().out[0])
     self.assertTrue(abs(result.mean - 0.85) < 0.0001)
     self.assertTrue(abs(result.confidence - 0.9) < 0.0001)
コード例 #7
0
ファイル: test_bc.py プロジェクト: noskill/atomspace
    def test_bc_deduction(self):
        """port of crisp.scm from examples/rule-engine/simple"""

        print("Enter test_bc_deduction")
        self.init()

        print("test_bc_deduction: pre scheme eval")
        scheme_eval(self.atomspace, '(use-modules (opencog))')
        scheme_eval(self.atomspace, '(use-modules (opencog exec))')
        scheme_eval(self.atomspace, '(use-modules (opencog rule-engine))')
        print("test_bc_deduction: pre scheme load")
        scheme_eval(self.atomspace,
                    '(load-from-path "bc-deduction-config.scm")')
        print("test_bc_deduction: post scheme load")

        A = ConceptNode("A", TruthValue(1, 1))
        B = ConceptNode("B")
        C = ConceptNode("C")
        AB = InheritanceLink(A, B)
        AB.tv = TruthValue(1, 1)
        BC = InheritanceLink(B, C)
        BC.tv = TruthValue(1, 1)
        crisprbs = ConceptNode("crisp-rule-base")
        # InheritanceLink(crisprbs, ConceptNode("URE"))
        print("test_bc_deduction: pre backchain ctor")
        chainer = BackwardChainer(
            self.atomspace, ConceptNode("URE"),
            InheritanceLink(VariableNode("$who"), C),
            TypedVariableLink(VariableNode("$who"), TypeNode("ConceptNode")))

        scheme_eval(self.atomspace, '(gc)')
        print("test_bc_deduction: post backchain ctor")
        chainer.do_chain()
        print("test_bc_deduction: post chaining")
        scheme_eval(self.atomspace, '(gc)')
        results = chainer.get_results()
        print("test_bc_deduction: post results")
        scheme_eval(self.atomspace, '(gc)')
        resultAC = None
        for result in results.get_out():
            if result.get_out()[0].name == "A":
                resultAC = result
                break
        self.assertTrue(resultAC is not None)
        self.assertTrue(resultAC.tv == AB.tv)
        self.assertEquals("A", resultAC.get_out()[0].name)
        self.assertEquals("C", resultAC.get_out()[1].name)
        del chainer
コード例 #8
0
def main():
    build_modus_ponens()
    # train implication or just weigths of modus_ponens_formula
    train_implication = False
    if train_implication:
        print("train implication and modus_ponens_formula' weights")
    else:
        print("train only modus_ponens_formula' weights")

    optimizer = optim.SGD(params(train_implication), lr=1e-1)
    initial_w = w.clone()
    print('initial ' + res_string.format(*initial_w))
    print("inital implication links")
    for color in colors:
        for fruit in fruits:
            print(ImplicationLink(PredicateNode(fruit), PredicateNode(color)))

    for i in range(300):
        fruit_id = np.random.randint(len(fruits))
        color_id = np.random.choice(len(colors), p=Pcolorfruit[fruit_id])
        fruit = fruits[fruit_id]
        color = colors[color_id]
        x = fruit + "-" + str(i)
        set_ttv(EvaluationLink(PredicateNode(fruit), ConceptNode(x)),
                TTruthValue(1.0, 1.0))
        optimizer.zero_grad()
        loss = torch.zeros(1)
        for c in colors:
            bc = BackwardChainer(
                atomspace, rule_base,
                EvaluationLink(PredicateNode(c), ConceptNode(x)))
            bc.do_chain()
            evlink = bc.get_results().out[0]
            p = get_ttv(evlink)
            # print(evlink)
            if color == c:
                loss = loss - torch.log(p[0])
            else:
                loss = loss - torch.log(1 - p[0])
        loss.backward()
        optimizer.step()
    print("implication links")
    for color in colors:
        for fruit in fruits:
            print(ImplicationLink(PredicateNode(fruit), PredicateNode(color)))
    print("after training")
    print(res_string.format(w[0], w[1], w[2], w[2], w[3]))
コード例 #9
0
ファイル: test_bc.py プロジェクト: linas/atomspace
    def test_bc_deduction(self):
        """port of crisp.scm from examples/ure/simple"""

        print ("Enter test_bc_deduction")
        self.init()

        print ("test_bc_deduction: pre scheme eval")
        scheme_eval(self.atomspace, '(use-modules (opencog))')
        scheme_eval(self.atomspace, '(use-modules (opencog exec))')
        scheme_eval(self.atomspace, '(use-modules (opencog ure))')
        print ("test_bc_deduction: pre scheme load")
        scheme_eval(self.atomspace, '(load-from-path "bc-deduction-config.scm")')
        print ("test_bc_deduction: post scheme load")

        A = ConceptNode("A", TruthValue(1, 1))
        B = ConceptNode("B")
        C = ConceptNode("C")
        AB = InheritanceLink(A, B)
        AB.tv = TruthValue(1, 1)
        BC = InheritanceLink(B, C)
        BC.tv = TruthValue(1, 1)
        crisprbs = ConceptNode("crisp-rule-base")
        # InheritanceLink(crisprbs, ConceptNode("URE"))
        print ("test_bc_deduction: pre backchain ctor")
        chainer = BackwardChainer(self.atomspace,
                                  ConceptNode("URE"),
                                  InheritanceLink(VariableNode("$who"), C),
                                  TypedVariableLink(VariableNode("$who"), TypeNode("ConceptNode")))

        scheme_eval(self.atomspace, '(gc)')
        print ("test_bc_deduction: post backchain ctor")
        chainer.do_chain()
        print ("test_bc_deduction: post chaining")
        scheme_eval(self.atomspace, '(gc)')
        results = chainer.get_results()
        print ("test_bc_deduction: post results")
        scheme_eval(self.atomspace, '(gc)')
        resultAC = None
        for result in results.get_out():
            if result.get_out()[0].name == "A":
                resultAC = result
                break
        self.assertTrue(resultAC is not None)
        self.assertTrue(resultAC.tv == AB.tv)
        self.assertEquals("A", resultAC.get_out()[0].name)
        self.assertEquals("C", resultAC.get_out()[1].name)
        del chainer
コード例 #10
0
    def test_cons_disj_elimination(self):
        rule_base = ConceptNode('PLN')
        A = PredicateNode('A')
        set_ttv(A, (1.0, 1.0))
        B = PredicateNode('B')
        set_ttv(B, (1.0, 1.0))
        C = PredicateNode('C')
        set_ttv(C, (1.0, 1.0))
        set_ttv(ImplicationLink(A, C), (0.55, 0.55))
        set_ttv(ImplicationLink(A, OrLink(B, C)), (1.0, 1.0))

        impl = ImplicationLink(A, B)
        bc = BackwardChainer(self.atomspace, rule_base, impl)
        bc.do_chain()
        result = get_ttv(bc.get_results().out[0])
        self.assertTrue(result.mean == 1.0)
        alpha = 0.9
        self.assertTrue(result.confidence == alpha * 0.55)
コード例 #11
0
def main():
    generate_modus_ponens()
    optimizer = optim.SGD(params(), lr=1e-2)
    for i in range(100):
        fruit_id = np.random.randint(len(fruits))
        color_id = np.random.choice(len(colors),
                                    p=P_color_given_fruit[fruit_id])
        fruit = fruits[fruit_id]
        color = colors[color_id]
        x = fruit + "-" + str(i)

        # a particular fruit, color observation
        EvaluationLink(PredicateNode(fruit),
                       ConceptNode(x)).tv = TTruthValue(1.0, 1.0)

        optimizer.zero_grad()
        loss = torch.zeros(1)
        for c in colors:
            # compute P(fruit|color)
            bc = BackwardChainer(
                atomspace, rule_base,
                EvaluationLink(PredicateNode(c), ConceptNode(x)))
            bc.do_chain()
            evlink = bc.get_results().out[0]
            p_fruit_given_color = evlink.tv
            print(evlink)
            if color == c:
                loss = loss - torch.log(p_fruit_given_color.mean)
            else:
                loss = loss - torch.log(1 - p_fruit_given_color.mean)
        print('loss: ' + str(loss))
        loss.backward()
        optimizer.step()
    print("results after train:")
    for color in colors:
        for fruit in fruits:
            print(ImplicationLink(PredicateNode(fruit), PredicateNode(color)))
コード例 #12
0
    def test_rule_engine(self):
        rule_base = initialize_pln()
        apple = ConceptNode('apple')
        colors = torch.rand(3, 4, 4)
        colors[GREEN] = 0.8
        colors = colors
        inp = InputModule(apple, colors)
        # red <- color
        # green <- color
        green = GreenPredicate(ConceptNode('green'))
        inh_red = InheritanceLink(ConceptNode("red"), ConceptNode("color"))
        inh_red = InheritanceModule(inh_red, torch.tensor([0.9, 0.95]))
        inh_green = InheritanceModule(ConceptNode("green"),
                                      ConceptNode("color"),
                                      tv=torch.tensor([0.6, .9]))
        # And(Evaluation(GreenPredicate, apple), Inheritance(green, color))
        conj = AndLink(green.evaluate(inp.execute()), inh_green.execute())

        bc = BackwardChainer(self.atomspace, rule_base, conj)
        bc.do_chain()
        result = get_ttv(bc.get_results().out[0])
        self.assertEqual(min(colors[GREEN].mean(), inh_green.tv.mean),
                         result.mean)
        self.assertEqual(inh_green.tv.confidence, result.confidence)
コード例 #13
0
# Initialize AtomSpace

atomspace = AtomSpace()
initialize_opencog(atomspace)

# Import URE Deduction Rules
from sample_ure_deduction import *

# Knowledge Base
A = ConceptNode("A")
B = ConceptNode("B")
C = ConceptNode("C")

AB = InheritanceLink(A, B)
BC = InheritanceLink(B, C)

A.tv = TruthValue(1, 1)
AB.tv = TruthValue(0.8, 0.9)
BC.tv = TruthValue(0.85, 0.95)

# Run Forward Chainer

chainer = BackwardChainer(
    atomspace, deduction_rbs, InheritanceLink(VariableNode("$X"), C),
    TypedVariableLink(VariableNode("$X"), TypeNode("ConceptNode")))

chainer.do_chain()
results = chainer.get_results()

print(results)