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'}
Example #2
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)