def test_forward_chaining():
    def condition1(subject):
        return subject['animal'] == 'dog'

    def condition2(subject):
        return subject['legsQuantity'] == '4'

    def consequence1(subject):
        subject['legsQuantity'] = '4'

    def consequence2(subject):
        subject['locomotion'] = 'quadruped'

    rule1 = Rule('all dogs have 4 legs', condition1, consequence1, {'animal': 'dog'}, ('animal',))
    rule2 = Rule('Anything with 4 legs is a quadruped', condition2, consequence2, {'legsQuantity': '4'},
                 ('legsQuantity',))

    rs = RuleSet()
    rs.add_rule(rule1)
    rs.add_rule(rule2)

    kb = KnowledgeBase()
    kb.add_knowledge({'animal': 'dog'})

    ie = ForwardChainingInferenceEngine(kb, rs)
    ie.run_engine()

    assert ie.knowledge_base.knowledge == {'animal': 'dog', 'legsQuantity': '4', 'locomotion': 'quadruped'}
def test_backward_chaining_missing_rule_when_false():
    def condition1(subject):
        return subject['animal'] == 'dog'

    def condition2(subject):
        return subject['legsQuantity'] == '4'

    def consequence1(subject):
        subject['legsQuantity'] = '4'

    def consequence2(subject):
        subject['locomotion'] = 'quadruped'

    rule2 = Rule('Anything with 4 legs is a quadruped', condition2, consequence2, {'legsQuantity': '4'},
                 ('legsQuantity',))
    rs = RuleSet()
    rs.add_rule(rule2)

    kb = KnowledgeBase()
    kb.add_knowledge({'animal': 'dog'})

    ie = BackwardChainingInferenceEngine(kb, rs)
    ie.set_hypothesis({'locomotion': 'quadruped'})

    assert ie.run_engine() is False
Esempio n. 3
0
def backward_chaining_method(rules, init_knowledge, hypothesis):
    rules_set = RuleSet()
    map(rules_set.add_rule, rules)

    knowledge_base = KnowledgeBase()
    knowledge_base.add_knowledge(yaml.safe_load(init_knowledge))

    inference_engine = BackwardChainingInferenceEngine(knowledge_base, rules_set)
    inference_engine.set_hypothesis(yaml.safe_load(hypothesis))
    result = inference_engine.run_engine()

    logger.info('Result: {}'.format(result))
Esempio n. 4
0
def forward_chaining_method(rules, init_knowledge):
    rules_set = RuleSet()
    map(rules_set.add_rule, rules)

    knowledge_base = KnowledgeBase()
    knowledge_base.add_knowledge(yaml.safe_load(init_knowledge))

    inference_engine = ForwardChainingInferenceEngine(knowledge_base, rules_set)
    inference_engine.run_engine()

    logger.info('Final Knowledge')
    logger.info(knowledge_base.knowledge)