コード例 #1
1
def backchain_to_goal_tree(rules, hypothesis):
    goal_tree = [hypothesis]
    for rule in rules:
        # take THEN part of a rule
        consequent = rule.consequent()
        for option in consequent:
            bindings = match(option, hypothesis)
            if bindings or option == hypothesis:
                # take IF part of a rule
                antecedent = rule.antecedent()
                if isinstance(antecedent, str):
                    new_hypothesis = populate(antecedent, bindings)
                    goal_tree.append(backchain_to_goal_tree(rules, new_hypothesis))
                    goal_tree.append(new_hypothesis)
                else:
                    statements = [populate(ante_expr, bindings) for ante_expr in antecedent]
                    new_goal_tree = []
                    for statement in statements:
                        new_goal_tree.append(backchain_to_goal_tree(rules, statement))

                    # check the leaves of AND-OR tree and recursively backward chain on them.
                    if isinstance(antecedent, AND):
                        goal_tree.append(AND(new_goal_tree))
                    else:
                        goal_tree.append(OR(new_goal_tree))
    return simplify(OR(goal_tree))
コード例 #2
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)
コード例 #3
0
ファイル: backchain.py プロジェクト: Calcifer777/mit-6034
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))
コード例 #4
0
ファイル: backchain.py プロジェクト: dan214/Hello-World
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)
コード例 #5
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
コード例 #6
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)
コード例 #7
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.
    """
    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))
コード例 #8
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)
コード例 #9
0
ファイル: lab1.py プロジェクト: Nandhini1296/MIT-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.
    """
    results=[hypothesis]
    for rule in rules:
        consequent=rule.consequent()
        for expr in consequent:
           bindings=match(expr,hypothesis)
           if bindings or expr == hypothesis:
                antecedent=rule.antecedent()
                if isinstance(antecedent,str):
                   new_hypothesis=populate(antecedent,bindings)
                   results.append(backchain_to_goal_tree(rules,new_hypothesis))
                   results.append(new_hypothesis)
                else:
                    statements=[populate(new_antecedent,bindings) for new_antecedent in antecedent]
                    new_results=[]
                    for statement in statements:
                        new_results.append(backchain_to_goal_tree(rules,statement))
                    if isinstance (antecedent, AND):
                        results.append(AND(new_results))
                    elif isinstance(antecedent,OR):
                        results.append(OR(new_results))
    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):
    """
    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:
        variables = match(rule.consequent(), hypothesis)
        if variables is not None:
            if isinstance(rule.antecedent(), OR):
                tree.append(OR([ backchain_to_goal_tree(rules, ant) for ant in populate(rule.antecedent(), variables)]))
            elif isinstance(rule.antecedent(), AND):
                tree.append(AND([ backchain_to_goal_tree(rules, ant) for ant in populate(rule.antecedent(), variables)]))
            else:
                tree.append(backchain_to_goal_tree(rules, populate(rule.antecedent(), variables)))
    
    return simplify(tree)
コード例 #12
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)
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))
コード例 #14
0
ファイル: backchain.py プロジェクト: dan214/Hello-World
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)
コード例 #15
0
def backchain_to_goal_tree(rules, hypothesis):

    results = [hypothesis]

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

        for expr in consequent:
            bindings = match(expr, hypothesis)

            if bindings or expr == hypothesis:
                antecedent = rule.antecedent()

                if isinstance(antecedent, str):
                    new_hypothesis = populate(expr, bindings)
                    results.append(
                        backchain_to_goal_tree(rules, new_hypothesis))
                    results.append(new_hypothesis)
                else:
                    statements = [
                        populate(expr, bindings) for ante_expr in antecedent
                    ]
                    new_results = []
                    for statement in statements:
                        new_results.append(
                            backchain_to_goal_tree(rules, statement))
                    results.append(create_statement(new_results, antecedent))
    return simplify(results)
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))
コード例 #17
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))
コード例 #18
0
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) 
コード例 #19
0
ファイル: backchain.py プロジェクト: joeloskarsson/MIT6.034
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))
コード例 #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):
    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))
コード例 #22
0
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
コード例 #23
0
ファイル: backchain.py プロジェクト: QuestionC/mit6034
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)
コード例 #24
0
ファイル: lab1.py プロジェクト: farrigaba/6.034
def backchain_test(rules, hypothesis):
    consequent_match_list = []
    goal_tree = OR()
    antecedent_hypotheses = AND()
    for rule in rules:
        for consequent in rule.consequent():
            if not match(consequent, hypothesis) == None:
                print populate(consequent, match(consequent, hypothesis))
    return 'hello kitty'
コード例 #25
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.
    """
    #find a rule which has the hypothesis as the conclusion and testing its premises
    # Rule Z14:
    IF(
        AND(
            '(?x) is a bird',  #in rule Z3       
            '(?x) does not fly',  #opposite of rule Z4
            '(?x) swims',
            '(?x) has black and white color'),
        THEN('(?x) is a penguin'))
    # penguin = opus?
    #OR('opus is a penguin', AND(
    #OR('opus is a bird', 'opus has feathers'),
    #AND('opus flies', 'opus lays eggs'))
    #'opus does not fly',
    #'opus swims',
    #'opus has black and white color' ))
    #Rule Z14: if

    results = [hypothesis]
    for rule in rules:
        consequent = rule.consequent()
        for expr in consequent:
            bindings = match(expr, hypothesis)
            if bindings or expr == hypothesis:
                antecedent = rule.antecedent()
                if isinstance(antecedent, str):
                    new_hypothesis = populate(antecedent, bindings)
                    results.append(
                        backchain_to_goal_tree(rules, new_hypothesis))
                    results.append(new_hypothesis)
                else:
                    statements = [
                        populate(ante_expr, bindings)
                        for ante_expr in antecedent
                    ]
                    new_results = []
                    for statement in statements:
                        new_results.append(
                            backchain_to_goal_tree(rules, statement))
                    results.append(create_statement(new_results, antecedent))
    return simplify(OR(results))
コード例 #26
0
ファイル: lab1.py プロジェクト: graceyin1218/6.034-labs
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])))
コード例 #27
0
ファイル: lab1.py プロジェクト: yeyimilk/MIT-6.034-AI
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
コード例 #28
0
ファイル: rules.py プロジェクト: vspenubarthi/anomaly-explain
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))
コード例 #29
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)
コード例 #30
0
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
コード例 #31
0
ファイル: lab1.py プロジェクト: CodeIsLie/IntellectualSystems
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
コード例 #32
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)
コード例 #33
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:
        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)
コード例 #34
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)
コード例 #35
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))
コード例 #36
0
ファイル: backchain.py プロジェクト: ajspencer/ocwAI
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)
コード例 #37
0
ファイル: backchain.py プロジェクト: cstoner/courses
def backchain_to_goal_tree(rules, hypothesis):
    matched_rules = []
    results = []

    for rule in rules:
        rule_str = rule.consequent()[0]
        if match(rule_str, hypothesis) is not None:
            res = match(rule_str, hypothesis)
            matched_rules.append(populate(rule.antecedent(), res))

    for m in matched_rules:
        if isinstance(m, AND):
            res = []
            for item in m:
                res.append(backchain_to_goal_tree(rules, item))
            results.append(AND(res))

        elif isinstance(m, OR):
            res = []
            for item in m:
                res.append(backchain_to_goal_tree(rules, item))
            results.append(OR(res))

        elif isinstance(m, str):
            results.append(backchain_to_goal_tree(rules, m))

        else:
            raise Exception, "Not sure what do do with object '{}'".format(m) 

    return simplify(OR([hypothesis] + results))
コード例 #38
0
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
コード例 #39
0
ファイル: backchain.py プロジェクト: czod/MITOCW6.034SC
def backchain_to_goal_tree(rules, hypothesis, toprint = 0):
    #  Found git entry from junoon53.  Outlined flow.  Recreating from flow.

    goal_tree = [hypothesis]

    if toprint >=1 : clno = getframeinfo(currentframe()).lineno;funcDebug({"\n Hypothesis is: ":hypothesis,"\n Goal tree is: ":goal_tree},clno)

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

        if toprint >= 1: clno = getframeinfo(currentframe()).lineno;funcDebug({"\n Rule is ":rule,"\n Consequent is ":consequent},clno)
        
        for expr in consequent:
            bindings = match(expr,hypothesis)

            if toprint >= 1: clno = getframeinfo(currentframe()).lineno;funcDebug({"\n expr is ":expr,"\n bindings is ":bindings},clno)

            # if bindings is not equal to None, which is return by match when no match is made,
            # or if the expression retrieved from the consequent of the rule is equal to the
            # hypothesis, retrieve the antecedents of the rule for tests and recursion.  Otherwise,
            # fetch the next expression.
            
            if bindings or expr == hypothesis:
                antecedent = rule.antecedent()

                # Is the antecedent a string?  If so we can recurse on it as a new hypothesis.
                #  If not it must be a list of expressions that we will have to parse.
                if isinstance(antecedent,str):
                    new_hypo = populate(antecedent,bindings)
                    goal_tree.append(backchain_to_goal_tree(rules,new_hypo))
                    # Once recursion completes and the results of that recursion are
                    # appended to the goal tree, we can append the new_hypo to the goal tree.
                    goal_tree.append(new_hypo)
                else:
                    # Assuming antecedent is a list of expressions, retrieve them and assemble a list
                    # of statements to be acted on
                    #  junoon53 used a list comprehension here but I'm going to write out the whole for
                    # loop just to make sure I know what is going on.
                    statements = []
                    new_goal_tree=[]
                    for anteEx in antecedent:
                        statements.append(populate(anteEx,bindings))
                    for statement in statements:
                        new_goal_tree.append(backchain_to_goal_tree(rules,statement))
                    goal_tree.append(createStatement(new_goal_tree,antecedent))
                        
    return simplify(OR(goal_tree))
コード例 #40
0
ファイル: backchain.py プロジェクト: bsinger98/AI-Course
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
コード例 #41
0
def backchain_to_goal_tree(rules, hypothesis):
	or_conditionals=[hypothesis]
	for rule in rules:
		for consequent in list(rule.consequent()):
			matches = match(consequent,hypothesis)
			if matches!=None:
				antecedent = rule.antecedent()
				if isinstance(antecedent,AND) or isinstance(antecedent,OR):
					sub_tree  = [backchain_to_goal_tree(rules,populate(element,matches)) for element in list(antecedent)]
					if isinstance(antecedent,AND):
						or_conditionals.append(AND(sub_tree))
					else:
						or_conditionals.append(OR(sub_tree))
				else:
					or_conditionals.append(backchain_to_goal_tree(rules,populate(antecedent,matches)))
	return simplify(OR(or_conditionals))
	raise NotImplementedError
コード例 #42
0
ファイル: backchain.py プロジェクト: Arvhus/Playground
def backchain_to_goal_tree(rules, hypothesis):
    rule_match = []

    for rule in rules:
        value = match(rule.consequent()[0], hypothesis)
        if value is not None:
            rule_match.append(rule)
            # print rule
        else:
            pass

    if len(rule_match) == 0:
        return hypothesis

    else:
        or_add = OR(hypothesis)
        for rule in rule_match:
            vars = match(rule.consequent()[0], hypothesis)
            if isinstance(rule.antecedent(), OR):
                for idx, ant in enumerate(rule.antecedent()):
                    add_or = backchain_to_goal_tree(
                        rules,  populate(ant, vars))
                    if idx == 0:
                        or_lst = OR(add_or)
                    else:
                        or_lst = OR(or_lst, add_or)
                or_lst = simplify(or_lst)
                or_add = OR(or_add, or_lst)

            elif isinstance(rule.antecedent(), AND):
                for idx, ant in enumerate(rule.antecedent()):
                    add_and = backchain_to_goal_tree(
                        rules,  populate(ant, vars))
                    if idx == 0:
                        and_lst = AND(add_and)
                    else:
                        and_lst = AND(and_lst, add_and)
                and_lst = simplify(and_lst)
                or_add = OR(or_add, and_lst)
            else:
                for idx, ant in enumerate([rule.antecedent()]):
                    add_and = backchain_to_goal_tree(
                        rules,  populate(ant, vars))
                or_add = OR(or_add, add_and)
        return simplify(or_add)
コード例 #43
0
ファイル: backchain.py プロジェクト: Superman8218/ai
def antecedents_goal_tree(rule, rules, binding):
    ant = rule.antecedent()
    new_hypothesis = populate(ant, binding)
    if not (isinstance(ant, AND) or isinstance(ant, OR)):
        return rule_match_goal_tree(rules, new_hypothesis)
    subtrees = [rule_match_goal_tree(rules, item) for item in new_hypothesis]
    if isinstance(ant, AND):
        return AND(subtrees)
    else: 
        return OR(subtrees)
コード例 #44
0
def backchain_antecedents(rules, bindings, rule):

	tree = []

	antecedents = rule.antecedent()

	if isinstance(antecedents, str): antecedents = AND(antecedents)

	for antecedent in antecedents:

		branch = simplify(backchain_support(rules, populate(antecedent, bindings)))

		if branch is None:
			tree.append(populate(antecedent, bindings))
		else:
			tree.append(branch)

	if isinstance(rule.antecedent(), AND): return simplify(AND(tree))
	else: return simplify(OR(tree))
コード例 #45
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)
コード例 #46
0
def backchain_to_goal_tree(rules, hypothesis):
    results = [hypothesis]
    for rule in rules:
        consequent = rule.consequent()
        for expr in consequent:
            bindings = match(expr, hypothesis)
            if bindings or expr == hypothesis:
                antecedent = rule.antecedent()
                if isinstance(antecedent, str):
                    new_hypothesis = populate(antecedent, bindings)
                    results.append(backchain_to_goal_tree(rules, new_hypothesis))
                    results.append(new_hypothesis)
                else:
                    statements = [populate(ante_expr, bindings) for ante_expr in antecedent]
                    new_results = []
                    for statement in statements:
                        new_results.append(backchain_to_goal_tree(rules, statement))
                    results.append(create_statement(new_results, antecedent))
    return simplify(OR(results))
コード例 #47
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)
コード例 #48
0
ファイル: backchain.py プロジェクト: colinmcd94/courses
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)
コード例 #49
0
def backchain_support(rules, hypothesis):

	tree = []

	for rule in rules:
		for consequent in rule.consequent():
			bindings = match(consequent, hypothesis)
		
			if bindings is not None:
				tree.append(populate(consequent, bindings))	
				tree.append(backchain_antecedents(rules, bindings, rule))

	if len(tree) is not 0: return simplify(OR(tree))
コード例 #50
0
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)
コード例 #51
0
ファイル: backchain.py プロジェクト: szimmer1/mit_6_034
def expand_subtree(subtree, bindings, rules):
    # build an identical subtree by recursively
    # walking and replacing each leaf with a backchained
    # tree

    cloned_node = subtree.__class__()
    for expression in subtree:
        if isinstance(expression, RuleExpression):
            cloned_node.append( expand_subtree(expression, bindings) )
        else:
            # assume if it's not a RuleExpression, it's a leaf node
            hypothesis = populate(expression, bindings)
            cloned_node.append( backchain_to_goal_tree(rules, hypothesis) )

    return simplify( cloned_node )
コード例 #52
0
ファイル: backchain.py プロジェクト: happyherp/littlethings
def backchain_to_goal_tree(rules, hypothesis):
    print "backchain_to_goal_tree", hypothesis
    possible = [hypothesis]

    for rule in rules:
        print "rule", rule
        for consequence in rule.consequent():
            bindings = match(consequence, hypothesis)
            if bindings != None:
                print "bindings", bindings
                sub_hypothesis = populate(rule.antecedent(), bindings)
                print "sub_hypothesis", sub_hypothesis
                sub_hypothesis_extended = extendGoalTree(rules, sub_hypothesis)
                possible.append(sub_hypothesis_extended)
    
    return simplify(OR(possible) )
コード例 #53
0
ファイル: backchain.py プロジェクト: rafaroar/6.034-labs
def backchain_to_goal_tree(rules, hypothesis):

    #print "\n", "HYPOTHESIS", hypothesis
    
    new_hypothesis = []
    variable = ""
    for rule in rules:
        for cons in rule.consequent():
            if match(cons, hypothesis) != None:
                new_hypothesis.append(rule.antecedent())
                variable = match(cons, hypothesis)
                #print "match!", cons, rule.antecedent()
                #print "variable", variable
                
    #print "new hypothesis", new_hypothesis

    if len(new_hypothesis) < 1:
        return hypothesis

    branches = [hypothesis]
    
    for antec in new_hypothesis:
        expr = populate(antec, variable)
        #print antec, variable, populate(antec, variable)
        
        if isinstance (expr, str):
            minitree = backchain_to_goal_tree(rules, expr)
            
        else:
            branchez = []
            for argg in expr:
                branchez.append(backchain_to_goal_tree(rules, argg))
            if isinstance (expr, OR):
                minitree = simplify(OR(branchez))
            elif isinstance (expr, AND):
                minitree = simplify(AND(branchez))
                
        branches.append(minitree)

    #print "  TREE", branches
    tree = simplify(OR(branches))

    return tree
コード例 #54
0
ファイル: backchain.py プロジェクト: eewayhsu/6.034
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))
コード例 #55
0
def backchain_to_goal_tree(rules, hypothesis):
    or_condition = []
    no_match = True
    for rule in rules:
        consequents = rule.consequent()
        if not isinstance(consequents, list):
            consequents = [consequents]
        for consequent in consequents:
            var_map = match(consequent, hypothesis)
            if var_map is None:
                continue

            no_match = False
            and_sub_condition = []
            if var_map == {}:
                and_sub_condition.append(AND())

            conditions = rule.antecedent()
            is_and = True
            if not isinstance(conditions, list):
                conditions = [conditions]
            if isinstance(conditions, OR):
                is_and = False

            for condition in conditions:
                pop_res = populate(condition, var_map)
                and_sub_condition.append(backchain_to_goal_tree(rules, pop_res))

            if is_and:
                or_condition.append(AND(and_sub_condition))
            else:
                or_condition.append(OR(and_sub_condition))

    if no_match:
        return hypothesis

    res = OR([hypothesis, OR(or_condition)])
    res = simplify(res)
    return res
コード例 #56
0
ファイル: lab1.py プロジェクト: wsnalice/6.034_Fall_15
def backchain_to_goal_tree(rules, hypothesis):
    temp = hypothesis
    l = []
    for i in rules:
        q = i.consequent()
        p = False
        for j in q:
            m = match(j,hypothesis)
            if (m != None):
                n = populate(i.antecedent(), m)
                l.append(n)
    if (len(l) == 0):
        return hypothesis
    for i in l:
        if isinstance(i,str):
            i = backchain_to_goal_tree(rules,i)
        else:
            x = len(i)
            for j in range(x):
                i[j] = backchain_to_goal_tree(rules,i[j])
        temp = simplify(OR(temp, i))
    return temp
コード例 #57
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.
    """
    or_content = [hypothesis]

    for rule in rules:
        for consequent in rule.consequent():
            _match = match(consequent, hypothesis)
            if _match is not None:
                or_content.append(recursive(rules, populate(rule.antecedent(),_match)))

    return simplify(OR(or_content))