示例#1
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)
示例#2
0
def backchain_to_goal_tree(rules, hypothesis):
    ors = [hypothesis]
    for rule in rules:
        consequents = rule.consequent()
        for consequent in consequents:

            matched_vars = match(consequent, hypothesis)

            # matched_vars match
            if matched_vars or consequent == hypothesis:
                antecedent = rule.antecedent()
                if isinstance(antecedent, str):
                    populated = populate(antecedent, matched_vars)
                    ors.append(populated)
                    ors.append(backchain_to_goal_tree(rules, populated))
                else:
                    ante_rules = [
                        populate(rule, matched_vars) for rule in antecedent
                    ]
                    ante_res = [
                        backchain_to_goal_tree(rules, ante_rule)
                        for ante_rule in ante_rules
                    ]
                    if isinstance(antecedent, AND):
                        ors.append(AND(ante_res))
                    elif isinstance(antecedent, OR):
                        ors.append(OR(ante_res))

    return simplify(OR(ors))
示例#3
0
def backchain_to_goal_tree(rules, hypothesis):
    # find rules that produces this hypothesis
    rules_con = [hypothesis]

    for rule in rules:
        for con in rule.consequent():
            bindings = match(con, hypothesis)

            if (bindings != None):
                # this rule can result in the hypo
                ant = rule.antecedent()

                if (isinstance(ant, AND)):
                    rules_con.append(
                        AND([
                            backchain_to_goal_tree(rules,
                                                   populate(branch, bindings))
                            for branch in ant
                        ]))
                elif (isinstance(ant, OR)):
                    rules_con.append(
                        OR([
                            backchain_to_goal_tree(rules,
                                                   populate(branch, bindings))
                            for branch in ant
                        ]))
                else:
                    rules_con.append(
                        backchain_to_goal_tree(rules, populate(ant, bindings)))

    return simplify(OR(rules_con))
示例#4
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)
示例#5
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)
示例#6
0
def backchain_to_goal_tree(rules, hypothesis):
    ret = hypothesis

    for rule in rules:
        consequent = rule.consequent()

        for conse in consequent:
            bindings = match(conse, hypothesis)
            if bindings != None:
                antecedent = rule.antecedent()

                if is_leaf_condition(antecedent):
                    condition = antecedent.__class__

                    tmp = []
                    for ante in antecedent:
                        new_hypothesis = populate(ante, bindings)
                        ans = backchain_to_goal_tree(rules, new_hypothesis)
                        tmp.append(ans)

                    ret = OR(ret, condition(tmp))
                else:
                    new_hypothesis = populate(antecedent, bindings)
                    tmp = backchain_to_goal_tree(rules, new_hypothesis)
                    ret = OR(ret, tmp)

    return simplify(ret)
示例#7
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)
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.
    """
    matched = list([hypothesis])
    for rule in rules:
        bound_conseq = match(rule.consequent(), hypothesis)
        if bound_conseq is not None:
            new_antes = list()
            if isinstance(rule.antecedent(), str):
                bound_ante = populate(rule.antecedent(), bound_conseq)
                matched.append(bound_ante)
                matched.append(backchain_to_goal_tree(rules, bound_ante))
            for ant in rule.antecedent():
                new_antes.append(
                    backchain_to_goal_tree(rules, populate(ant, bound_conseq)))
            if isinstance(rule.antecedent(), AND):
                matched.append(AND(new_antes))
            if isinstance(rule.antecedent(), OR):
                matched.append(OR(new_antes))
    return simplify(OR(matched))
示例#9
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.
    """

    #creating the results of our hypothesis
    results = [hypothesis]

    #looping through all the rules (necessary for each new hypothesis under recursion)
    for rule in rules:

        #taking the binder variable
        binder = match(rule.consequent(), hypothesis)

        #seeing if there is actually a matching statement
        if binder or rule.consequent() == hypothesis:

            #collecting all the antecedents to a rule
            antecedents = rule.antecedent()

            #special case if there is only 1 antecedent
            if isinstance(antecedents, str):
                #resetting our hypothesis so we can recursively go
                #through the one hypothesis
                hypothesis = populate(antecedents, binder)
                #have to append the hypothesis itself
                results.append(hypothesis)
                #recursively go through rules again with new hypothesis
                results.append(backchain_to_goal_tree(rules, hypothesis))

            else:  #if the antecedent has more AND/OR statements (more depth)
                hypotheses = [
                    populate(antecedent, binder) for antecedent in antecedents
                ]

                #recursive results for each antecent(which became a new
                #hypothesis)
                sub_results = [
                    backchain_to_goal_tree(rules, hypothesis)
                    for hypothesis in hypotheses
                ]

                #binding the sub_results correctly based on how the
                #antecedents were stored
                if isinstance(antecedents, AND):
                    results.append(AND(sub_results))
                elif isinstance(antecedents, OR):
                    results.append(OR(sub_results))

    #returning simplified version as we go
    return simplify(OR(results))
示例#10
0
文件: lab1.py 项目: 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)
示例#11
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 = [hypothesis]
    for rule in rules:
        for consequent in rule.consequent():  # Extend from python list
            bound_variables = match(consequent, hypothesis)
            if bound_variables is not None:  # We have matched expressions
                antecedent_list = rule.antecedent()
                if isinstance(antecedent_list,
                              RuleExpression):  # Complex expression
                    if isinstance(antecedent_list, AND):
                        inner_goal_tree = AND([
                            backchain_to_goal_tree(
                                rules, populate(expr, bound_variables))
                            for expr in antecedent_list
                        ])
                    elif isinstance(antecedent_list, OR):
                        inner_goal_tree = OR([
                            backchain_to_goal_tree(
                                rules, populate(expr, bound_variables))
                            for expr in antecedent_list
                        ])
                    goal_tree.append(inner_goal_tree)
                else:  # just a string, which is a single leaf node
                    new_hypothesis = populate(antecedent_list, bound_variables)
                    goal_tree.append(
                        OR(backchain_to_goal_tree(rules, new_hypothesis)))

    return simplify(OR(goal_tree))
def backchain_to_goal_tree(rules, hypothesis):
    tree = [hypothesis]
    for rule in rules:
        cons = rule.consequent()
        antec = rule.antecedent()

        #Busco "matches"
        isInConsequent = False
        for pattern in cons:
            dictMatch = match(pattern,hypothesis)
            if(dictMatch != None):
                isInConsequent = True
                #print "Match!"
                #print rule
                break

        if(isInConsequent):
            listaTemp = []
            if(not isinstance(antec,list)): #Es una expresion simple
                expP = populate(antec, dictMatch)
                expP = backchain_to_goal_tree(rules, expP)
                tree.append(expP)
            else:
                for exp in antec:
                    expP = populate(exp,dictMatch)
                    expP = backchain_to_goal_tree(rules,expP)
                    listaTemp.append(expP)

            if(isinstance(antec,AND)):
                tree.append(AND(listaTemp))
            elif(isinstance(antec,OR)):
                tree.append(OR(listaTemp))

    return simplify(OR(tree))
示例#14
0
def backchain_to_goal_tree(rules, hypothesis):            
    """
    LHG Code from 6.034, modified for the ADE system.

    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.
    """
    top_level = [hypothesis]
    
    for rule in rules:
        matching = match(rule.consequent(), hypothesis)
        
        if matching is not None:
            tree = []
            next = populate(rule.antecedent(), matching)
            ant_stuff = type(rule.antecedent())
            
            if ant_stuff is str: # leaf
                tree.append(backchain_to_goal_tree(rules, next))
            else: 
                for hyp in next:
                    tree.append(backchain_to_goal_tree(rules, hyp))
                    
            if ant_stuff == OR:
                top_level.append(OR(tree))
            else: top_level.append(AND(tree))
    return simplify(OR(top_level))
示例#15
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))
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
示例#17
0
文件: lab1.py 项目: kchobo13/6.034
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)
示例#18
0
def backchain_to_goal_tree(rules, hypothesis):
    result = []
    for rule in rules:
        matched = match(rule.consequent()[0], hypothesis)
        if matched != None:
            antecedent = rule.antecedent()
            result.append(iterate_node(rules, antecedent, matched))
    if len(result) > 0:
        return simplify(OR(hypothesis, OR(result)))
    else:
        return hypothesis
示例#19
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.
    """

    toReturnTrees = [hypothesis]
    matches = False
    for rule in rules:
        for consequent in rule.consequent():
            variables = match(consequent, hypothesis)

            if variables == None:
                continue

            matches = True

            # the thing you have to prove is true,
            # in order to prove your hypothesis is true
            antecedent = rule.antecedent(
            )  #populate(rule.antecedent(), variables)

            # the subtree you will return
            tree = None

            if isinstance(antecedent, str):
                tree = backchain_to_goal_tree(rules,
                                              populate(antecedent, variables))
            elif isinstance(antecedent, AND):
                tree = AND([
                    backchain_to_goal_tree(rules, populate(clause, variables))
                    for clause in antecedent
                ])
            elif isinstance(antecedent, OR):
                tree = OR([
                    backchain_to_goal_tree(rules, populate(clause, variables))
                    for clause in antecedent
                ])
            tree = simplify(tree)

            toReturnTrees.append(tree)

    if not matches:
        return hypothesis

    return simplify(simplify(OR([toReturnTrees])))
示例#20
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
示例#21
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
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)
示例#23
0
def backchain_to_goal_tree(rules, hypothesis):
    """    
#Try 3
    tree = [hypothesis]
    for rule in rules:
        for exp in rule.consequent():
            matching = match(exp, hypothesis)
            if matching !=None:
                antecedent = rule.antecedent()
                if type(antecedent) is str:
                    newHyp = populate(antecedent, matching)
                    tree.append(backchain_to_goal_tree(rules, newHyp))
                    tree.append(newHyp)
                else:
                    statements = [populate(exp, matching) for exp in antecedent]
                    newTree = []
                    for statement in statements:
                        newTree.append(backchain_to_goal_tree(rules, statement))
                    if type(antecedent) == type(OR()):
                        tree.append(OR(newTree))
                    else:
                        tree.append(AND(newTree))
    return simplify(OR(tree))
"""

    #Try 2
    tree = [hypothesis]
    for rule in rules:
        for exp in rule.consequent():
            matching = match(exp, hypothesis)
            if matching != None:
                filledAnts = populate(rule.antecedent(), matching)

                if type(filledAnts) == type(AND()):
                    andState = AND([
                        backchain_to_goal_tree(rules, state)
                        for state in filledAnts
                    ])
                    tree.append(andState)
                elif type(filledAnts) == type(OR()):
                    orState = OR([
                        backchain_to_goal_tree(rules, state)
                        for state in filledAnts
                    ])
                    tree.append(orState)
                else:
                    tree.append(backchain_to_goal_tree(rules, filledAnts))
    return simplify(OR(tree))
示例#24
0
 def transform(goal_tree):
     if isinstance(goal_tree, AND):
         return AND(map(lambda g: transform(g), goal_tree))
     elif isinstance(goal_tree, OR):
         return OR(map(lambda g: transform(g), goal_tree))
     else:
         return backchain_to_goal_tree(rules, populate(goal_tree, substitutions))
def create_statement(statements, rule):
    if isinstance(rule, AND):
        return AND(statements)

    elif isinstance(rule, OR):

        return OR(statements)
示例#26
0
def backchain_to_goal_tree(rules, hypothesis):
    hows = []
    for rule in rules:
        if isinstance(rule.consequent(), basestring):
            cons = [rule.consequent()]
        else:
            cons = rule.consequent()
        for c in rule.consequent():
            m = match(c, hypothesis)
            if m is not None:
                instantiated_candidate = populate(c, m)
                hows.append(instantiated_candidate)

                antecedents_hows = []
                if isinstance(rule.antecedent(), basestring):
                    ants = [rule.antecedent()]
                else:
                    ants = rule.antecedent()
                for ant in ants:
                    p_ant = populate(ant, m) 
                    ant_hows = backchain_to_goal_tree(rules, p_ant)
                    antecedents_hows.append(ant_hows)
                
                if isinstance(rule.antecedent(), basestring) or isinstance(rule.antecedent(), OR) :
                    for ant_hows in antecedents_hows:
                        hows.append(ant_hows)
                elif isinstance(rule.antecedent(), AND):
                    hows.append(AND(*antecedents_hows))
                else:
                    raise ValueError, "something is wront with this antecedent: %s" % rule.antecedent()

    if not hows:
        return hypothesis
    else:
        return simplify(OR(hows))
def backchain_to_goal_tree(rules, hypothesis):
    new_hyp_list = []
    goaltree = []

    for rule in rules:
        for word in rule.consequent():
            if match(rule.consequent()[0], hypothesis) != None:
                new_hyp = populate(rule.antecedent(),
                                   match(rule.consequent()[0], hypothesis))
                new_hyp_list += [new_hyp]

    goaltree += [hypothesis]
    for new_hyp in new_hyp_list:
        goaltree += [new_hyp]

    goaltree = OR(goaltree)

    if len(goaltree) != 0:
        for i in range(1, len(goaltree)):
            if isinstance(goaltree[i], (list, tuple)):
                for j in range(0, len(goaltree[i])):
                    goaltree[i][j] = simplify(
                        backchain_to_goal_tree(rules, goaltree[i][j]))
            else:
                goaltree[i] = simplify(
                    backchain_to_goal_tree(rules, goaltree[i]))

    goaltree = simplify(goaltree)

    return goaltree
示例#28
0
def backchain_to_goal_tree(rules, hypothesis):
    or_list = []
    for rule in rules:
        match_bindings = match(rule.consequent()[0], hypothesis)
        if match_bindings is not None:
            ant = populate(rule.antecedent(), match_bindings)
            if isinstance(ant, str):
                or_list.append(backchain_to_goal_tree(rules, ant))
            elif isinstance(ant, AND):
                or_list.append(
                    AND([backchain_to_goal_tree(rules, a) for a in ant]))
            elif isinstance(ant, OR):
                or_list.append(
                    OR([backchain_to_goal_tree(rules, a) for a in ant]))
            else:
                print "ERROR:", ant, "is not str, AND, or OR"
    return simplify(OR([hypothesis] + or_list))
示例#29
0
def iterate_node(rules, node, mapping):
    if isinstance(node, str):
        leaf = populate(node, mapping)
        return backchain_to_goal_tree(rules, leaf)
    elif isinstance(node, OR):
        return(OR([iterate_node(rules, exp, mapping) for exp in node]))
    elif isinstance(node, AND):
        return(AND([iterate_node(rules, exp, mapping) for exp in node]))
示例#30
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
示例#31
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)
示例#32
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)
示例#33
0
 def find_ante(rules, hypothesis):
     antecedents = [hypothesis]
     for rule in rules:
         result = match(rule.consequent(), hypothesis)
         if result != None:
             ante = populate(rule.antecedent(), result)
             if isinstance(ante, AND):
                 antecedents.append(
                     simplify(AND([find_ante(rules, cond)
                                   for cond in ante])))
             elif isinstance(ante, OR):
                 antecedents.append(
                     simplify(OR([find_ante(rules, cond)
                                  for cond in ante])))
             else:
                 antecedents.append(find_ante(rules, ante))
     return simplify(OR(antecedents))
示例#34
0
文件: lab1.py 项目: fabatef/6.034
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 ('HYPOTHESIS: ', hypothesis)
    tree = [hypothesis]
    for rule in rules:
        consequent = rule.consequent()
        bindings = match(consequent, hypothesis)
        #print ('BINDINGS: ', bindings)
        #found a matching rule
        if bindings != None:
            antecedent = rule.antecedent()
            #if the antecedent is a statement, add it to the tree and recurse on it as the new hypothesis
            if isinstance(antecedent, str):
                new_hypothesis = populate(antecedent, bindings)
                tree.append(new_hypothesis)
                tree.append(backchain_to_goal_tree(rules, new_hypothesis))

            #if not, go through each statement in antecedent, and recurse on them, build their subtree and add to the tree
            else:
                statements = [
                    populate(statement, bindings) for statement in antecedent
                ]
                subtree = []
                for statement in statements:
                    subtree.append(backchain_to_goal_tree(rules, statement))
                #print ('SUBTREE: ', subtree)

                #for an AND antecedent
                if isinstance(antecedent, AND):
                    tree.append(AND(subtree))
                #for an OR antecedent
                else:
                    tree.append(OR(subtree))
    #print ('TREE: ', tree)
    return simplify(OR(tree))
示例#35
0
文件: lab1.py 项目: mmladenik/6.034
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)
示例#36
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
示例#37
0
文件: backchain.py 项目: AIRising/AI
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)
示例#38
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 )
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)
示例#40
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)
示例#41
0
文件: lab1.py 项目: 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)