Beispiel #1
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)
Beispiel #2
0
def backchain_to_goal_tree(rules, hypothesis):
    hypothesis = OR(hypothesis)
    for rule in rules:
        var_list = match(
            rule.consequent()[0], hypothesis[0]
        )  #assume that rule.consequent() and hypothesis have exactly one string
        if var_list == None:
            continue

        else:
            if isinstance(rule.antecedent(), basestring):
                appendage = [
                    backchain_to_goal_tree(
                        rules, populate(rule.antecedent(), var_list))
                ]
            else:
                appendage = [
                    backchain_to_goal_tree(rules, populate(data, var_list))
                    for data in rule.antecedent()
                ]

            if isinstance(rule.antecedent(), AND):
                appendage = AND(appendage)
            else:
                #catch if class= basestring also, because it will be removed in simplify()
                appendage = OR(appendage)

            hypothesis.append(appendage)

    return simplify(hypothesis)
Beispiel #3
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.
    """
    hyp = OR([hypothesis])
    for rule in rules:
        # for consequent in rule.consequent():
        m = match(rule.consequent(), hypothesis)
        if m is not None:
            # good_consequent = populate(consequents, m)
            antecedents = rule.antecedent()
            if isinstance(antecedents, str):
                antecedents = [antecedents]
            antecedent = [
                backchain_to_goal_tree(rules, populate(a, m))
                for a in antecedents
            ]
            if isinstance(antecedents, OR):
                hyp.append(OR(antecedent))
            else:
                hyp.append(AND(antecedent))
    return simplify(hyp)
Beispiel #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):
    """
    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.
    """
    tree = OR(hypothesis)
    for rule in rules:
        bounded = match(rule.consequent(), hypothesis) #check if rule can produce the hypothesis
        if bounded != None:
            new_antecedent = populate(rule.antecedent(), bounded) #populate the vars of the rule's antecdent
            
            #recurse on antecedent
            if type(new_antecedent) == str:
                tree.append(backchain_to_goal_tree(rules,new_antecedent))
            else: 
                for i,new_hypothesis in enumerate(new_antecedent):
                    new_antecedent[i] = backchain_to_goal_tree(rules,new_hypothesis)
                tree.append(new_antecedent)
    return simplify(tree)
Beispiel #6
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.
    """

    tree = OR(hypothesis)
    
    if len(rules)==0:
        return hypothesis

    for rule in rules:
        if match(rule.consequent()[0], hypothesis) is not None:
            popRule = populate(rule.antecedent(), match(rule.consequent()[0], hypothesis))
            if isinstance(popRule, (AND, OR)):
                for i in xrange(len(popRule)):
                    popRule[i]=backchain_to_goal_tree(rules, popRule[i])
                tree.append(popRule)
            else:
                new_tree=backchain_to_goal_tree(rules, popRule)
                tree.append(new_tree)
    return simplify(tree)
Beispiel #7
0
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)
Beispiel #8
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.
    """

    tree = OR(hypothesis)
    for rule in rules:
        match_res = match(rule.consequent(), hypothesis)
        if match_res is not None:
            or_node = OR()
            tree.append(or_node)
            nodes = populate(rule.antecedent(), match_res)
            if type(nodes) == str:
                nodes = [nodes]
            for i in range(len(nodes)):
                nodes[i] = backchain_to_goal_tree(rules, nodes[i])
            or_node.append(nodes)

    tree = simplify(tree)
    return tree
Beispiel #9
0
def backchain_to_goal_tree(rules, hypothesis):
    # print ("backchain_to_goal_tree", rules, hypothesis)
    result = OR(hypothesis)

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

            if isinstance(rule.antecedent(), AND):
                new_rule = AND([
                    backchain_to_goal_tree(rules, populate(pattern, m))
                    for pattern in rule.antecedent()
                ])
                result.append(new_rule)
            elif isinstance(rule.antecedent(), OR):
                new_rule = OR([
                    backchain_to_goal_tree(rules, populate(pattern, m))
                    for pattern in rule.antecedent()
                ])
                result.append(new_rule)
            elif isinstance(rule.antecedent(), str):
                new_rule = OR(
                    backchain_to_goal_tree(rules,
                                           populate(rule.antecedent(), m)))
                result.extend(new_rule)
            else:
                print("backchain_to_goal_tree confusing antecedent",
                      rule.antecedent)
                return None

    return simplify(result)
Beispiel #10
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):
    
    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) 
Beispiel #12
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)
Beispiel #13
0
Datei: lab1.py Projekt: 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_rec(rules, hypothesis, protagonist):
    hy_li = hypothesis.split(' ')
    hy_li.pop(0)
    clean_hypothesis = ' '.join(hy_li)
    goaltree = OR()
    goaltree.append(protagonist + " " + clean_hypothesis)

    for rule in rules:
        clean_consequent = removeX(rule.consequent())
        if clean_consequent == clean_hypothesis:

            antecedents = rule.antecedent()
            if isinstance(antecedents, list):
                subtree = []
                if isinstance(antecedents, OR):
                    subtree = OR()
                if isinstance(antecedents, AND):
                    subtree = AND()
                for antecedent in antecedents:
                    subtree.append(
                        backchain_to_goal_tree_rec(rules, antecedent,
                                                   protagonist))

                goaltree.append(subtree)
            else:
                goaltree.append(
                    backchain_to_goal_tree_rec(rules, antecedents,
                                               protagonist))
    return goaltree
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.
    """
    goal_tree = OR(hypothesis)
    for rule in rules:
        bindings = match(rule.consequent(), hypothesis)
        if bindings != None:
            instantiated_ant = []
            if isinstance(rule.antecedent(), str):
                bounded_ant = populate(rule.antecedent(), bindings)
                goal_tree.append(bounded_ant)
                goal_tree.append(backchain_to_goal_tree(rules, bounded_ant))
            for ant in rule.antecedent():
                instantiated_ant.append(
                    backchain_to_goal_tree(rules, populate(ant, bindings)))
            if isinstance(rule.antecedent(), AND):
                goal_tree.append(AND(instantiated_ant))
            if isinstance(rule.antecedent(), OR):
                goal_tree.append(OR(instantiated_ant))
    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)
def myfunc(rule, rules, deneme, hypothesis):
    yedek = OR()

    for ante in rule.antecedent():
        deger = myfunc2(rule, rules, populate(ante, deneme), deneme)
        #print(deger)
        if deger != OR() and deger != rule.antecedent():
            yedek.append(deger)
            #print(yedek)
    #print(populate(ante,deneme))
    #print(simplify(yedek))
    if yedek == OR():
        return OR()
    #return AND(yedek,populate(ante,deneme))
    if type(rule.antecedent()) == OR:
        return OR(yedek, myfunc3(rule, deneme))
    return AND(yedek, myfunc3(rule, deneme))
Beispiel #18
0
def backchain_to_goal_tree(rules, hypothesis):
    matches = OR()
    bindings = {}
    tree = OR()
    for rule in rules:
        consequent = rule.consequent()[0]
        if match(consequent, hypothesis):
            matches.append(rule)
            bindings = variables(consequent)
    if len(matches) < 1:
        return hypothesis
    else:
        for rule in matches:
            for exp in rule.antecedent():
                n_hypothesis = populate(exp, bindings)
                tree.append(backchain_to_goal_tree(rules, n_hypothesis))
    return simplify(tree)
Beispiel #19
0
def backchain_to_goal_tree(rules, hypothesis):
    tree = OR(hypothesis)
    for rule in rules:
        for c in rule.consequent():
            bindings = match(c, hypothesis)
            if bindings is not None:
                populated_antecedent = populate(rule.antecedent(), bindings)
                if isinstance(populated_antecedent, str):
                    populated_antecedent = OR(populated_antecedent)

                for i, hyp in enumerate(populated_antecedent):
                    sub_tree = backchain_to_goal_tree(rules, hyp)
                    populated_antecedent[i] = sub_tree

                tree.append(populated_antecedent)

    return simplify(tree)
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)
Beispiel #21
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
Beispiel #22
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
Beispiel #23
0
def backchain_to_goal_tree(rules, hypothesis):
    # check rules for matching consequents
    #   i) no matches -> hypothesis is a leaf
    #   ii) matches -> OR(antecedent)

    or_cond = OR()

    # always append the hypothesis
    or_cond.append(hypothesis)

    for rule in rules:
        bindings = match(rule.consequent()[0], hypothesis)
        if bindings:
            # append the goal tree from the antecedent
            ante = rule.antecedent()
            if isinstance(ante, RuleExpression):
                or_cond.append( expand_subtree(ante, bindings, rules) )

    return simplify( or_cond )
Beispiel #24
0
def backchain_to_goal_tree(rules, hypothesis):
    matchedRules = []
    orExpression = OR(hypothesis)
    for rule in rules:
        for expression in rule.consequent():
            thisMatch = match(expression, hypothesis)
            if(not thisMatch is None):
                ruleExpression = orExpression
                antecedant = rule.antecedent()
                if(isinstance(antecedant, RuleExpression)):
                    if(isinstance(antecedant, AND)):
                        andExpression = AND()
                        orExpression.append(andExpression)
                        ruleExpression = andExpression
                    for antecedantExpression in antecedant:
                        ruleExpression.append(backchain_to_goal_tree(rules, populate(antecedantExpression, thisMatch)))
                else:
                    orExpression.append(populate(backchain_to_goal_tree(rules, antecedant), thisMatch))
    return simplify(orExpression)
def backchain_to_goal_tree(rules, hypothesis):
    i = 0
    tree = OR()

    for rule in rules:
        #for ante in rule.antecedent():
        #if i>=1 and i<len(rule.antecedent()):
        #birsey.append(ante)
        #i+=1
        for cons in rule.consequent():
            if match(cons, hypothesis) or hypothesis == cons:
                deneme = match(cons, hypothesis)
                #bakalim=(backchain_to_goal_tree,populate(rule.antecedent(),deneme),rules)
                #print(rule)
                tree.append(
                    OR(hypothesis, myfunc(rule, rules, deneme, hypothesis)))
    if tree == OR():
        return ['stuff']
    antelist.clear()
    return simplify(tree)
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)
Beispiel #27
0
def backchain_to_goal_tree(rules, hypothesis):
   
    result = OR(hypothesis)
   
    for rule in rules:
        b = []
        hype = []
        for con in rule.consequent():
            if match(con, hypothesis) is not None:
                    b.append(match(con, hypothesis))   
                    for i in b:
                        if i is not None and isinstance(rule.antecedent(), (AND, OR)):
                            for j in rule.antecedent():
                                if populate(j, i) is not None:
                                    hype.append(populate(j, i))
                        elif i is not None:
                            if populate(rule.antecedent(), i) is not None:
                                hype.append(populate(rule.antecedent(), i))

        if len(hype) > 0:
            if isinstance(rule.antecedent(), AND):
                result.append(AND())
                for h in hype:
                    result[-1].append(backchain_to_goal_tree(rules, h))
            elif isinstance(rule.antecedent(), OR):
                result.append(OR())
                for h in hype:
                    result[-1].append(backchain_to_goal_tree(rules, h))
            else:
                for h in hype:
                    result.append(backchain_to_goal_tree(rules, h))
    
    result=simplify(result)

    return result
Beispiel #28
0
def backchain_to_goal_tree(rules, hypothesis):
    #    print 'START backchain_to_goal_tree', hypothesis
    goal_tree = OR()
    matching_rules = find_matching_rules(rules, hypothesis)
    #print "matching rules", matching_rules
    if len(matching_rules) > 0:
        goal_tree.append(hypothesis)
        for rule in matching_rules:
            consequent = rule.consequent()
            antecedent = rule.antecedent()

            for c in consequent:
                bindings = match(c, hypothesis)
                if bindings != None:
                    #print "consequent:", c
                    #print "antecedent:", antecedent
                    #print "bindings:", bindings
                    if isinstance(antecedent, (OR, AND)):
                        for i in xrange(len(antecedent)):
                            new_hypothesis = populate(antecedent[i], bindings)
                            #print "new hypothesis", new_hypothesis
                            antecedent[i] = backchain_to_goal_tree(
                                rules, new_hypothesis)
                        goal_tree.append(antecedent)
                    else:
                        new_hypothesis = populate(antecedent, bindings)
                        goal_tree.append(
                            backchain_to_goal_tree(rules, new_hypothesis))
        goal_tree = simplify(goal_tree)
    else:
        goal_tree = hypothesis
    return goal_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
Beispiel #30
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)
Beispiel #31
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.
    """
    goal_tree = OR()
    for rule in rules:
        var = match(rule.consequent(),hypothesis)
        if var != None: 
            sub_hypothesis = populate(rule.antecedent(), var)
            if isinstance(sub_hypothesis, OR):
                sub_tree = [backchain_to_goal_tree(rules, antecedent) for antecedent in sub_hypothesis]
                goal_tree.append(OR(sub_tree))

            elif isinstance(sub_hypothesis, AND):
                sub_tree = [backchain_to_goal_tree(rules, antecedent) for antecedent in sub_hypothesis]
                goal_tree.append(AND(sub_tree))
        
            else:
                goal_tree.append(backchain_to_goal_tree(rules, sub_hypothesis))
    
    return simplify(OR(hypothesis, goal_tree))
Beispiel #32
0
def backchain_to_goal_tree(rules, hypothesis):
    #print "Rules: ",rules
    print "H: ",hypothesis
    #if hypothesis=='zot':
    #print "Rules: ",rules
    #nodes=[rule.antecedent() for rule in rules if (match(rule.consequent()[0],hypothesis) or match=={})]
    #print nodes
    a={}
    nodes=[]
    for rule in rules:
        #print "Consequent: ",rule.consequent()[0]
        d=match(rule.consequent()[0],hypothesis)
        #print d
        if d or d=={}:
            #print "MATCHED!!"
            nodes.append(rule.antecedent())
            #print rule.antecedent()
            #print nodes
        test_match=match(rule.consequent()[0],hypothesis)
        if test_match:
            a = dict(a.items()+test_match.items())
    print a
    
    tree=OR(hypothesis)
    
    for node in nodes:
        print "type: ",type(node)
        if type(node) is OR or type(node) is AND:
            print "\n\nAppending list of nodes: ",[backchain_to_goal_tree(rules, populate(elem,a)) for elem in node]
            tree.append(type(node)([backchain_to_goal_tree(rules, populate(elem,a)) for elem in node]))
        else:
            print "\n\nAppending node: ",backchain_to_goal_tree(rules,populate(node,a))
            
            tree.append(backchain_to_goal_tree(rules,populate(node,a)))
    print "\n\n#####TREE!!\n",simplify(tree)
    
                
    
    return simplify(tree)
Beispiel #33
0
def backchain_to_goal_tree(rules, hypothesis):
    goal = OR(hypothesis)
    backchain = partial(backchain_to_goal_tree, rules)

    for rule in rules:
        csq = rule.consequent()
        if isinstance(csq, str): csq = [csq]

        for clause in csq:
            binds = match(clause, hypothesis)

            if binds != None:
                ants = rule.antecedent()
                if isinstance(ants, str): ants = [ants]

                op = None
                if isinstance(ants, OR): op = OR
                else: op = AND

                goal.append(op([backchain(populate(ant, binds)) for ant in ants]))

    return simplify(goal)
Beispiel #34
0
def backchain_to_goal_tree(rules, hypothesis):
    ##    raise NotImplementedError
    goal_tree = OR(hypothesis)
    for rule in rules:
        consequce = rule.consequent()[0]
        bindings = match(consequce, hypothesis)
        sub_tree = []
        if bindings is not None and len(bindings) > 0:
            antecedent = rule.antecedent()

            for elem in antecedent:
                new_hypothesis = populate(elem, bindings)
                pop_elem = backchain_to_goal_tree(rules, new_hypothesis)
                sub_tree.append(simplify(pop_elem))

            if isinstance(antecedent, AND):
                sub_tree = AND(sub_tree)
            elif isinstance(antecedent, OR):
                sub_tree = OR(sub_tree)
        if len(sub_tree) > 0:
            goal_tree.append(sub_tree)
    return goal_tree
def backchain_to_goal_tree(rules, hypothesis):
    all_consequents = [
        rule.consequent()[index] for rule in rules
        for index in range(0, len(rule.consequent()))
    ]
    matched_rules = [
        rule for rule in rules
        if match(rule.consequent()[0], hypothesis) != None
    ]
    chain = OR(hypothesis)
    for rule in matched_rules:
        bindings = get_bindings(rule.consequent(), hypothesis)
        template, antecedents = extract(rule.antecedent())
        for antecedent in antecedents:
            if antecedent_is_not_consequent_of_any_rule(
                    all_consequents, antecedent):
                template.append(populate(antecedent, bindings))
            else:
                template.append(
                    backchain_to_goal_tree(rules,
                                           populate(antecedent, bindings)))
        chain.append(template)
    return simplify(chain)
Beispiel #36
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)
Beispiel #37
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
Beispiel #38
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)
def myfunc2(rule, rules, hypothesis, deneme):
    yedek = OR()
    for rule in rules:
        for cons in rule.consequent():
            #print(cons)
            if match(cons, hypothesis):
                deneme = match(cons, hypothesis)
                #print(rule.antecedent())
                antelist.append(hypothesis)
                yedek.append(hypothesis)
                gelendeger = myfunc(rule, rules, deneme, hypothesis)
                if gelendeger != OR():
                    yedek.append(gelendeger)
                else:
                    yedek.append(populate(rule.antecedent(), deneme))

    #print(simplify(yedek))
    return yedek
Beispiel #40
0
def backchain_to_goal_tree(rules, hypothesis):
    unbound = [(rule.antecedent(), match(rule.consequent()[0], hypothesis))
               for rule in rules
               if not match(rule.consequent()[0], hypothesis) is None]
    bound = OR(hypothesis)
    for (ante, binding) in unbound:
        if type(ante) is AND:
            node_list = [populate(exp, binding) for exp in ante]
            bound.append(
                AND([
                    backchain_to_goal_tree(rules, node) for node in node_list
                ]))
        elif type(ante) is OR:
            node_list = [populate(exp, binding) for exp in ante]
            bound.append(
                OR([backchain_to_goal_tree(rules, node)
                    for node in node_list]))
        else:
            node = populate(ante, binding)
            bound.append(backchain_to_goal_tree(rules, node))
    return simplify(bound)