Esempio n. 1
0
File: lab1.py Progetto: cookt/mit
def backchain_to_goal_tree(rules, hypothesis):
    tree=OR(hypothesis)
    #print "hypothesis: "+str(hypothesis)
    matches=False
    for rule in rules:
        #print "rule: "+str(rule)
        cons=rule.consequent()
        ant=rule.antecedent()
        #print "cons: "+str(cons)
        for c in cons:
            #print "c:"+str(c)
            if match(c,hypothesis)!=None:
                matches=True
                if isinstance(ant, AND):
                    subtree=AND()
                    for a in ant:
                        subtree.append(backchain_to_goal_tree(rules,populate(a, match(c,hypothesis))))
                elif isinstance(ant, OR):
                    subtree=OR()
                    for a in ant:
                        subtree.append(backchain_to_goal_tree(rules,populate(a,match(c,hypothesis))))
                else:
                   subtree=backchain_to_goal_tree(rules, populate(ant,match(c,hypothesis)))
                tree.append(subtree)     
    if not(match):
        tree.append(hypothesis)
    return simplify(tree)
def backchain_to_goal_tree(rules, hypothesis):

    length = len(rules)

    if length == 0:
        return hypothesis
    tree = OR()

    for element in rules:
        con = element.consequent()
        mat = match(con[0], hypothesis)
        if mat is not None and len(mat) >= 0:
            antec = element.antecedent()
            if isinstance(antec, list):
                sub = AND()
                if isinstance(antec, OR): sub = OR()
                for x in antec:
                    new_tree = backchain_to_goal_tree(rules, populate(x, mat))
                    sub.append(new_tree)
                tree.append(sub)
            else:
                new_tree = backchain_to_goal_tree(rules, populate(antec, mat))
                tree.append(AND(new_tree))
        else:
            tree.append(hypothesis)
    new = simplify(tree)
    return new
Esempio n. 3
0
def backchain_to_goal_tree(rules, hypothesis):
    treeNode = OR(hypothesis)
    #For every rule in the tree, see which ones have consequents that match my hypothesis
    matches = []
    #iterate through every rule and collect the ones whose consequents match my hypothesis
    for rule in rules:
        #Fill in each consequent of the rule with the correct name of the antecendents
        for consequent in rule.consequent():
            matchAttempt = match(consequent, hypothesis)
            #If we can match one of the consequents, we want to fill in the atecedents with the appropriate hypothesis
            if(matchAttempt != None and not rule in matches):
                for i, expression in enumerate(rule.antecedent()):
                    rule.antecedent()[i] = populate(expression, matchAttempt)
                matches.append(rule)
    #At this point  we have a list of the rules that match, and all of the antecendents are filled in with the variable names we can fill them in with
    treeNode = OR(hypothesis)
    for ruleMatch in matches:
        antecedent = ruleMatch.antecedent()
        if( isinstance(antecedent, AND)):
            node = AND()
        else:
            node = OR()
        for newHypothesis in antecedent:
            node.append(backchain_to_goal_tree(rules, newHypothesis))
        treeNode.append(node)
    return simplify(treeNode)
Esempio n. 4
0
def backchain_to_goal_tree(rules, hypothesis, myLeaf=[]):
    count = 0
    for i in range(len(rules)):
        bindings = (match(rules[i].consequent()[0], hypothesis))
        if bindings is not None:
            print 'type of bindings', bindings
            andLeaf = AND()
            orLeaf = OR()
            for x in range(len(rules[i].antecedent())):
                print 'in antecedent.....', rules[i].antecedent()[x]
                node = populate((rules[i].antecedent()[x]), bindings)
                if type(rules[i].antecedent()) == AND:
                    andLeaf.append(
                        populate((rules[i].antecedent()[x]), bindings))
                    myLeaf.append(simplify(andLeaf))
                    print 'andLeaf', andLeaf
                if type(rules[i].antecedent()) == OR:
                    orLeaf.append(
                        populate((rules[i].antecedent()[x]), bindings))
                    myLeaf.append(simplify(orLeaf))
                    print 'orLeaf', orLeaf

                disnode = backchain_to_goal_tree(rules, node)
        else:
            print 'hypothesis'
            #myLeaf.append(hypothesis)

    return simplify(myLeaf)
def backchain_to_goal_tree(rules, hypothesis):
    
    goal_tree = OR(hypothesis)
    
    for rule in rules:
        consequence_pattern = rule.consequent()[0]
        bindings = match(consequence_pattern,hypothesis)
        
        if bindings == None:
            #print 'no rule was found'
            continue
        else:
            
            if isinstance(rule.antecedent(),AND):
                subtree = AND()
            else:
                subtree = OR()
            
            if isinstance(rule.antecedent(),(OR,AND)):
                for antecedent in rule.antecedent():
                    new_hypo = populate(antecedent,bindings)
                    subtree.append(backchain_to_goal_tree(rules,new_hypo))
                    goal_tree.append(subtree)
            else:
                new_hypo = populate(rule.antecedent(),bindings)
                subtree.append(backchain_to_goal_tree(rules,new_hypo))
                goal_tree.append(subtree)
                        
    return simplify(goal_tree) 
Esempio n. 6
0
def backchain_to_goal_tree(rules, hypothesis,myLeaf = []):
    count = 0
    for i in range(len(rules)):
        bindings = (match(rules[i].consequent()[0],hypothesis))
        if bindings is not None:
            print 'type of bindings',bindings
            andLeaf = AND()
            orLeaf = OR()
            for x in range(len(rules[i].antecedent())):
                print 'in antecedent.....',rules[i].antecedent()[x]
                node = populate((rules[i].antecedent()[x]),bindings)
                if type(rules[i].antecedent()) == AND:
                    andLeaf.append(populate((rules[i].antecedent()[x]),bindings))
                    myLeaf.append(simplify(andLeaf))
                    print 'andLeaf', andLeaf
                if type(rules[i].antecedent()) == OR:
                    orLeaf.append(populate((rules[i].antecedent()[x]),bindings))
                    myLeaf.append(simplify(orLeaf))
                    print 'orLeaf',orLeaf
                
                
                disnode = backchain_to_goal_tree(rules,node)
        else:
            print 'hypothesis'
            #myLeaf.append(hypothesis)
             
    return simplify(myLeaf)
def myfunc3(rule, deneme):
    eleman = AND()
    for liste in populate(rule.antecedent(), deneme):
        if not liste in antelist:
            antelist.append(liste)
            eleman.append(liste)
    return eleman
Esempio n. 8
0
File: lab1.py Progetto: corcillo/ai
def backchain_to_goal_tree(rules, hypothesis):
    anyMatches = False
    results = OR(hypothesis)
    for rule in rules:
        for statement in rule.consequent():
            matchOutput = match(statement, hypothesis)
            if matchOutput !=None:
                anyMatches = True 
                populatedAnt = populate(rule.antecedent(), matchOutput) #populate antecedent with vocab
                if isinstance(populatedAnt,list):
                    ands = AND()
                    ors = OR()
                    for statement in populatedAnt: #populated Ant is and / or
                        if isinstance(populatedAnt,AND):
                            ands.append(backchain_to_goal_tree(rules,statement))
                        elif isinstance(populatedAnt,OR):
                            ors.append(backchain_to_goal_tree(rules,statement))
                    if len(ands)!=0:
                        results.append(ands)
                    elif len(ors)!=0:
                        results.append(ors)
                else:
                    results.append(backchain_to_goal_tree(rules,populatedAnt))
    if anyMatches == False:
        results.append(OR(hypothesis))
    return simplify(results)
Esempio n. 9
0
def backchain_to_goal_tree(rules, hypothesis):
    goal_tree = OR()
    goal_tree.append(hypothesis)  # The hypothesis is the ultimate CSF

    if not rules:
        return list(goal_tree)  # Bad base test? Not sure why the need to cast back to list

    for rule in rules:
        consequent = rule.consequent()[0]  # should handle multiple?
        bindings = match(consequent, hypothesis)

        if bindings or bindings == {}:
            antecedent = rule.antecedent()
            if isinstance(antecedent, AND):
                branch = AND()
                for condition in antecedent:
                    cond = populate(condition, bindings)
                    branch.append(backchain_to_goal_tree(rules, cond))
                goal_tree.append(branch)
            elif isinstance(antecedent, OR):
                branch = OR()
                for condition in antecedent:
                    cond = populate(condition, bindings)
                    branch.append(backchain_to_goal_tree(rules, cond))
                goal_tree.append(branch)
            else:  # leaf
                leaf = populate(antecedent, bindings)
                goal_tree.append(leaf)
                goal_tree.append(backchain_to_goal_tree(rules, leaf))  # new leaf may match older consequent, need to check again

    return simplify(goal_tree)
def backchain_to_goal_tree(rules, hypothesis):
    root = OR(hypothesis)
    for rule in rules:
        for consequent in rule.consequent():
            matchResult = match(consequent, hypothesis)
            if matchResult != None:
                antecedent = rule.antecedent()
                newHypothesis = AND() if isinstance(antecedent, AND) else OR()
                if isinstance(antecedent, str):
                    antecedent = [antecedent]
                for part in antecedent:
                    newHypothesis.append(backchain_to_goal_tree(rules, populate(part, matchResult)))
                root.append(newHypothesis)
    return simplify(root)
Esempio n. 11
0
def backchain_to_goal_tree(rules, hypothesis):
    goal_tree = OR(hypothesis)
    for rule in rules:
        consequent = rule.consequent()[0]
        matching = match(consequent, hypothesis)
        if matching or matching == {}:
            if isinstance(rule.antecedent(), AND):
                leaf_tree = AND()
                for antecedent in rule.antecedent():
                    if populate(antecedent, matching):
                        leaf_tree.append(
                            backchain_to_goal_tree(
                                rules, populate(antecedent, matching)))
                        goal_tree.append(leaf_tree)
                    else:
                        leaf_tree.append(
                            backchain_to_goal_tree(rules, antecedent))
            elif isinstance(rule.antecedent(), OR):
                leaf_tree = OR()
                for antecedent in rule.antecedent():
                    if populate(antecedent, matching):
                        leaf_tree.append(
                            backchain_to_goal_tree(
                                rules, populate(antecedent, matching)))
                        goal_tree.append(leaf_tree)
                    else:
                        leaf_tree.append(
                            backchain_to_goal_tree(rules, antecedent))
            else:
                goal_tree.append(
                    backchain_to_goal_tree(
                        rules, populate(rule.antecedent(), matching)))

    return simplify(goal_tree)
Esempio n. 12
0
def backchain_to_goal_tree(rules, hypothesis):
    """
    Takes a hypothesis (string) and a list of rules (list
    of IF objects), returning an AND/OR tree representing the
    backchain of possible statements we may need to test
    to determine if this hypothesis is reachable or not.

    This method should return an AND/OR tree, that is, an
    AND or OR object, whose constituents are the subgoals that
    need to be tested. The leaves of this tree should be strings
    (possibly with unbound variables), *not* AND or OR objects.
    Make sure to use simplify(...) to flatten trees where appropriate.
    """
    print('---->', rules, '---->', hypothesis, len(rules))
    if len(rules) == 0:
        return hypothesis

    tree = OR()

    for rule in rules:
        rule_consequent = rule.consequent()
        # Rule consequents always have just a single statement.
        rule_match = match(rule_consequent, hypothesis)
        # if rule_match, stupid mistake which has already been claimed in the website and said that 'match("foo", "foo") => {}' would be false
        if rule_match is not None:
            rule_antecedent = rule.antecedent()
            if isinstance(rule_antecedent, list):
                sub_tree = AND()
                if isinstance(rule_antecedent, OR):
                    sub_tree = OR()

                for sub in rule_antecedent:
                    new_tree = backchain_to_goal_tree(
                        rules, populate(sub, rule_match))
                    sub_tree.append(new_tree)

                tree.append(sub_tree)

            else:
                new_tree = backchain_to_goal_tree(
                    rules, populate(rule_antecedent, rule_match))
                tree.append(AND(new_tree))

        else:
            tree.append(hypothesis)

    result = simplify(tree)
    return result
Esempio n. 13
0
def backchain_to_goal_tree(rules, hypothesis):
    matching_rules = []
    runningOR = OR()
    for rule in rules:
        match_result = match(rule._action[0], hypothesis)
        if match_result != None:
            runningOR.append(populate(rule._action[0], match_result))
            conditional = rule._conditional
            runningCondition = AND()
            for condition in range(0, len(conditional)):
                condition2 = populate(conditional[condition], match_result)
                runningCondition.append(backchain_to_goal_tree(rules, condition2))
            runningOR.append(runningCondition)
    if len(runningOR) != 0:
        return simplify(runningOR)
    else:
        return hypothesis
Esempio n. 14
0
def backchain_to_goal_tree(rules, hypothesis):
    goalTree = OR(hypothesis)
    for rule in rules:
        for consequent in rule.consequent():
            bindings = match(consequent, hypothesis)
            if bindings != None:
                tp = AND() if isinstance(rule.antecedent(), AND) else OR()
                antecedents = rule.antecedent()
                if not isinstance(antecedents, list):
                    antecedents = [antecedents]
                for antecedent in antecedents:
                    tp.append(
                        backchain_to_goal_tree(rules,
                                               populate(antecedent, bindings)))
                print tp
                goalTree.append(tp)
    return simplify(goalTree)
Esempio n. 15
0
def backchain_to_goal_tree(rules, hypothesis):

    if len(rules) == 0:
        return hypothesis

    # initilialise a new node which will contain all of the matching consequences
    goal_tree = OR()

    # try to match the hypothesis to a THEN statment in the rules
    for i in range(len(rules)):
        # get the other potential matching leaf
        rule = rules[i]

        # check if there is a match
        matching = match(rule.consequent()[0], hypothesis)

        # in not none you have found a match
        if matching != None:
            # get the consequent and the antecedent
            cns = rule.consequent()[0]
            ant = rule.antecedent()

            if isinstance(ant, list):
                sub = AND()

                if isinstance(ant, OR):
                    sub = OR()
                for statment in ant:
                    # print(statment)
                    # now recursivly call backchain on the ants statments
                    new_node = backchain_to_goal_tree(
                        rules, populate(statment, matching))

                    sub.append(new_node)

                # sub.append(ant)
                goal_tree.append(sub)
            else:
                goal_tree.append(
                    backchain_to_goal_tree(rules, populate(ant, matching)))

        else:
            goal_tree.append(hypothesis)

    return simplify(goal_tree)
Esempio n. 16
0
def backchain_to_goal_tree(rules, hypothesis):
    matching_rules = []
    runningOR = OR()
    for rule in rules:
        match_result = match(rule._action[0], hypothesis)
        if match_result != None:
            runningOR.append(populate(rule._action[0], match_result))
            conditional = rule._conditional
            runningCondition = AND()
            for condition in range(0, len(conditional)):
                condition2 = populate(conditional[condition], match_result)
                runningCondition.append(
                    backchain_to_goal_tree(rules, condition2))
            runningOR.append(runningCondition)
    if len(runningOR) != 0:
        return simplify(runningOR)
    else:
        return hypothesis
Esempio n. 17
0
def backchain_to_goal_tree(rules, hypothesis):
	goal_tree = OR(hypothesis)

	for rule in rules:
		for expr in rule.consequent():
			bindings = match(expr, hypothesis)
			if bindings or bindings == {}: # we have a match
				antecedent = rule.antecedent()
				subtree = AND() if isinstance(antecedent, AND) else OR()

				if isinstance(antecedent, str):
					new_nodes = [populate(antecedent, bindings)]
				else:
					new_nodes = [populate(subexpr, bindings) for subexpr in antecedent]

				for new_node in new_nodes:
					subtree.append(backchain_to_goal_tree(rules, new_node))
				
				goal_tree.append(subtree)

	return simplify(goal_tree)
Esempio n. 18
0
def backchain_to_goal_tree(rules, hypothesis):
    output = OR(hypothesis)
    matches = [
        populate(r.antecedent(), match(r.consequent()[0], hypothesis))
        for r in rules if matcher(r, hypothesis)
    ]
    if len(matches) > 0:
        for m in matches:
            if isinstance(m, AND):
                to_append = AND()
            else:
                to_append = OR()
            if not isinstance(m, (AND, OR)):
                m = AND(m)
            for a in m:
                child_append = OR(a)
                child_append.append(backchain_to_goal_tree(rules, a))
                to_append.append(child_append)
            output.append(to_append)
    else:
        output.append(OR())
    return simplify(output)
Esempio n. 19
0
def backchain_to_goal_tree(rules, hypothesis):
    if not rules:
        return hypothesis

    tree = OR(hypothesis)

    for rule in rules:
        for consequent in rule.consequent():
            matches = match(consequent, hypothesis)
            if matches == None:
                continue

            variables = {}
            for name, value in matches.items():
                variables[name] = value

            antecedents = rule.antecedent()

            # If antecedents is a string, behave as it is a list with single item - unify antecedents handling
            if isinstance(antecedents, str):
                antecedents = [antecedents]

            # Determine type of antecedents
            if isinstance(rule.antecedent(), AND):
                statements = AND()
            else:
                statements = OR()

            # For each antecedent generate new possible subtree
            for antecedent in antecedents:
                new_hypothesis = populate(antecedent, variables)
                subtree = backchain_to_goal_tree(rules, new_hypothesis)
                statements.append(subtree)

            tree.append(simplify(statements))

    return simplify(tree)
Esempio n. 20
0
def backchain_to_goal_tree(rules, hypothesis):
    goal_tree = OR(hypothesis)
    consequent_match_list = []

    # check through each rule
    for rule in rules:
        # if any consequent matches append rule
        # for consequent in THEN('(?x) is a penguin', '(?x) is a zebra') -> '(?x) is a penguin'
        for consequent in rule.consequent():
            # match('(?x) is a penguin', 'opus is a penguin') -> {x:'opus'}
            matched_variable = match(consequent, hypothesis)
            # if the consequent matches the hypothesis
            if not matched_variable == None:
                # populate('(?x) is a penguin', {x: opus}) -> 'opus is a penguin'
                # if the consequent really does match the hypothesis
                consequent_matched = populate(consequent, matched_variable)
                if consequent_matched == hypothesis:
                    # store the appropriate matched consequent, variable, and associated antecedents from the rule in a list
                    variables = match(consequent, hypothesis)
                    # append.(['(?x) is a penguin', {x: opus}, AND('(?x) is a bird', '(?x) does not fly')])
                    # consequent_match_list.append([consequent, variables, rule.antecedent()])
                    # go through each antecedent (or just the one if it is one)
                    antecedents = rule.antecedent()
                    # only one antecedent
                    if isinstance(antecedents, str):
                        if type(rule.antecedent()) is AND:
                            and_a = AND()
                            # associate antecedent with variable to form new hypothesis
                            # populate('(?x) is a bird', {x: 'opus'}) -> 'opus is a bird'
                            antecedent_matched = populate(
                                antecedents, variables)
                            # fill in goal tree AND() part with 'opus is a bird'
                            # now check if 'opus is a bird' as a new hypothesis generates antecedents and recursively act on
                            and_a.append(
                                backchain_to_goal_tree(rules,
                                                       antecedent_matched))
                            goal_tree.append(and_a)
                        else:
                            # associate antecedent with variable to form new hypothesis
                            # populate('(?x) is a bird', {x: 'opus'}) -> 'opus is a bird'
                            antecedent_matched = populate(
                                antecedents, variables)
                            # fill in goal tree AND() part with 'opus is a bird'
                            # now check if 'opus is a bird' as a new hypothesis generates antecedents and recursively act on
                            goal_tree.append(
                                backchain_to_goal_tree(rules,
                                                       antecedent_matched))
                    # multiple antecedents
                    else:
                        if type(rule.antecedent()) is AND:
                            and_a = AND()
                            for antecedent in rule.antecedent():
                                # associate antecedent with variable to form new hypothesis
                                # populate('(?x) is a bird', {x: 'opus'}) -> 'opus is a bird'
                                antecedent_matched = populate(
                                    antecedent, variables)
                                # fill in goal tree AND() part with 'opus is a bird'
                                # now check if 'opus is a bird' as a new hypothesis generates antecedents and recursively act on
                                and_a.append(
                                    backchain_to_goal_tree(
                                        rules, antecedent_matched))
                                goal_tree.append(and_a)
                        else:
                            for antecedent in rule.antecedent():
                                # associate antecedent with variable to form new hypothesis
                                # populate('(?x) is a bird', {x: 'opus'}) -> 'opus is a bird'
                                antecedent_matched = populate(
                                    antecedent, variables)
                                # fill in goal tree AND() part with 'opus is a bird'
                                # now check if 'opus is a bird' as a new hypothesis generates antecedents and recursively act on
                                goal_tree.append(
                                    backchain_to_goal_tree(
                                        rules, antecedent_matched))

    return simplify(goal_tree)