def tryKB(label, base):
    kbString = base['kb']
    kb = FolKB([])
    for kbLine in kbString.split('\n'):
        s = kbLine.strip()
        if len(s) == 0:
            continue
        if (s[0] == '#'):
            continue
        try:
            sentence = expr(s)
            kb.tell(sentence)
        except:
            traceback.print_exc()
    printKB(label, kb)
    print(indent(2), 'queries:')
    queryString = base['queries']
    for qLine in queryString.split('\n'):
        s = qLine.strip()
        if len(s) == 0:
            continue
        if (s[0] == '#'):
            continue
        try:
            query = expr(s)
            generator = kb.ask_generator(query)
            print(indent(3), str(query) + '?', end=' ')
            if 'limit' in base:
                printResults(query, generator, base['limit'])
            else:
                printResults(query, generator)
        except:
            traceback.print_exc()
Beispiel #2
0
def tryKB(label, base):
    kbString = base['kb']
    kb = FolKB([])
    for kbLine in kbString.split('\n'):
        s = kbLine.strip()
        if len(s) > 0:
            try:
                sentence = expr(s)
                kb.tell(sentence)
            except:
                traceback.print_exc()
    printKB(label, kb)
    queryString = base['queries']
    for qLine in queryString.split('\n'):
        s = qLine.strip()
        if len(s) > 0:
            try:
                query = expr(s)
                long = kb.ask(query)
                short = {}
                for v in long:
                    if v in query.args:
                        short[v] = long[v]
                print(indent(2), 'queries:')
                print(indent(3), str(query) + '?', short)
            except:
                traceback.print_exc()
Beispiel #3
0
def test_action():
    precond = 'At(c, a) & At(p, a) & Cargo(c) & Plane(p) & Airport(a)'
    effect = 'In(c, p) & ~At(c, a)'
    a = Action('Load(c, p, a)', precond, effect)
    args = [expr("C1"), expr("P1"), expr("SFO")]
    assert a.substitute(expr("Load(c, p, a)"), args) == expr("Load(C1, P1, SFO)")
    test_kb = FolKB(conjuncts(expr('At(C1, SFO) & At(C2, JFK) & At(P1, SFO) & At(P2, JFK) & Cargo(C1) & Cargo(C2) & Plane(P1) & Plane(P2) & Airport(SFO) & Airport(JFK)')))
    assert a.check_precond(test_kb, args)
    a.act(test_kb, args)
    assert test_kb.ask(expr("In(C1, P2)")) is False
    assert test_kb.ask(expr("In(C1, P1)")) is not False
    assert test_kb.ask(expr("Plane(P2)")) is not False
    assert not a.check_precond(test_kb, args)
Beispiel #4
0
def test_action():
    precond = [[expr("P(x)"), expr("Q(y, z)")], [expr("Q(x)")]]
    effect = [[expr("Q(x)")], [expr("P(x)")]]
    a=Action(expr("A(x,y,z)"), precond, effect)
    args = [expr("A"), expr("B"), expr("C")]
    assert a.substitute(expr("P(x, z, y)"), args) == expr("P(A, C, B)")
    test_kb = FolKB([expr("P(A)"), expr("Q(B, C)"), expr("R(D)")])
    assert a.check_precond(test_kb, args)
    a.act(test_kb, args)
    assert test_kb.ask(expr("P(A)")) is False
    assert test_kb.ask(expr("Q(A)")) is not False
    assert test_kb.ask(expr("Q(B, C)")) is not False
    assert not a.check_precond(test_kb, args)
Beispiel #5
0
def test_action():
    precond = [[expr("P(x)"), expr("Q(y, z)")], [expr("Q(x)")]]
    effect = [[expr("Q(x)")], [expr("P(x)")]]
    a = Action(expr("A(x,y,z)"), precond, effect)
    args = [expr("A"), expr("B"), expr("C")]
    assert a.substitute(expr("P(x, z, y)"), args) == expr("P(A, C, B)")
    test_kb = FolKB([expr("P(A)"), expr("Q(B, C)"), expr("R(D)")])
    assert a.check_precond(test_kb, args)
    a.act(test_kb, args)
    assert test_kb.ask(expr("P(A)")) is False
    assert test_kb.ask(expr("Q(A)")) is not False
    assert test_kb.ask(expr("Q(B, C)")) is not False
    assert not a.check_precond(test_kb, args)
Beispiel #6
0
def predictSuccess(current_skills, equation):
    curr_skills_KB = FolKB()
    required_skills_KB = FolKB()
    required_skills = set()
    # Create KnowledgeBase for current skills that exist
    for skill in current_skills:
        curr_skills_KB.tell(expr(skill))

    steps_for_solving = solveEquation(equation)
    lht = getLeftTerms(equation)
    rht = getRightTerms(equation)
    divisor = calcDivisor(lht, rht)
    rht_var_combine = calcCombineVars(rht)
    lht_var_combine = calcCombineVars(lht)

    for step in steps_for_solving:
        if 'addVar' in step:
            if step[6] == '-':
                required_skills.add('S2')
            else:
                required_skills.add('S1')
        elif 'addConst' in step:
            if step[9] == '-':
                required_skills.add('S4')
            else:
                required_skills.add('S3')
        elif 'divide' in step:
            if divisor > 0:
                required_skills.add('S5')
            else:
                required_skills.add('S6')
        elif ('combineRightConst' or 'combineRightConstTwo') in step:
            required_skills.add('S9')
        elif 'combineLeftVar':
            if (rht_var_combine > 0) | (lht_var_combine > 0):
                required_skills.add('S7')
            else:
                required_skills.add('S8')

    for sk in required_skills:
        required_skills_KB.tell(expr(sk))
    for curr_sk in curr_skills_KB.clauses:
        if curr_sk in required_skills_KB.clauses:
            required_skills_KB.retract(curr_sk)

    missing_skills = required_skills_KB.clauses
    return missing_skills
def tryKB(label, base):
    kb = FolKB([])

    # define the Differ predicate,
    # e.g., Differ(A, B), Differ(B, C), ...
    if 'Differ' in base:
        objString = base['Differ']
        objects = []
        for obj in objString.split(','):
            obj = obj.strip(' \t\n\r')
            if obj == '':
                continue
            if obj[0] == '#':
                continue
            objects.append(obj)
        for ob1 in objects:
            for ob2 in objects:
                if ob1 == ob2:
                    continue
                s = 'Differ(' + ob1 + ', ' + ob2 + ')'
                try:
                    sentence = expr(s)
                    kb.tell(sentence)
                except:
                    traceback.print_exc()

    # read facts and rules
    kbString = base['kb']
    for kbLine in kbString.split('\n'):
        s = kbLine.strip()
        if len(s) == 0:
            continue
        if (s[0] == '#'):
            continue
        try:
            sentence = expr(s)
            kb.tell(sentence)
        except:
            traceback.print_exc()
    printKB(label, kb)

    # now, ask some questions
    print(indent(2), 'queries:')
    queryString = base['queries']
    for qLine in queryString.split('\n'):
        s = qLine.strip()
        if len(s) == 0:
            continue
        if (s[0] == '#'):
            continue
        try:
            query = expr(s)
            generator = kb.ask_generator(query)
            print(indent(3), str(query) + '?', end=' ')
            if 'limit' in base:
                printResults(query, generator, base['limit'])
            else:
                printResults(query, generator)
        except:
            traceback.print_exc()
Beispiel #8
0
def test_graph_call():
    pdll = spare_tire()
    negkb = FolKB([expr('At(Flat, Trunk)')])
    graph = Graph(pdll, negkb)

    levels_size = len(graph.levels)
    graph()

    assert levels_size == len(graph.levels) - 1
Beispiel #9
0
    def check_precond(self, kb, args):
        """Checks if the precondition is satisfied in the current state"""

        if isinstance(kb, list):
            kb = FolKB(kb)

        for clause in self.precond:
            if self.substitute(clause, args) not in kb.clauses:
                return False
        return True
Beispiel #10
0
    def act(self, kb, args):
        """Executes the action on the state's knowledge base"""

        if isinstance(kb, list):
            kb = FolKB(kb)

        if not self.check_precond(kb, args):
            raise Exception('Action pre-conditions not satisfied')
        for clause in self.effect:
            kb.tell(self.substitute(clause, args))
            if clause.op[:3] == 'Not':
                new_clause = Expr(clause.op[3:], *clause.args)

                if kb.ask(self.substitute(new_clause, args)) is not False:
                    kb.retract(self.substitute(new_clause, args))
            else:
                new_clause = Expr('Not' + clause.op, *clause.args)

                if kb.ask(self.substitute(new_clause, args)) is not False:    
                    kb.retract(self.substitute(new_clause, args))

        return kb
Beispiel #11
0
def spare_tire_graphplan():
    pdll = spare_tire()
    negkb = FolKB([expr('At(Flat, Trunk)')])
    graphplan = GraphPlan(pdll, negkb)
    ##Not sure
    goals_pos = [expr('At(Spare, Axle)'), expr('At(Flat, Ground)')]
    goals_neg = []

    while True:
        if goal_test(graphplan.graph.levels[-1].poskb, goals_pos) and graphplan.graph.non_mutex_goals(goals_pos+goals_neg, -1):
            solution = graphplan.extract_solution(goals_pos, goals_neg, -1)
            if solution:
                return solution
        graphplan.graph.expand_graph()
        if len(graphplan.graph.levels)>=2 and graphplan.check_leveloff():
            return None
Beispiel #12
0
    def act(self, kb, args):
        """Executes the action on the state's knowledge base"""

        if isinstance(kb, list):
            kb = FolKB(kb)

        if not self.check_precond(kb, args):
            raise Exception('Action pre-conditions not satisfied')
        for clause in self.effect:
            kb.tell(self.substitute(clause, args))
            if clause.op[:3] == 'Not':
                new_clause = Expr(clause.op[3:], *clause.args)

                if kb.ask(self.substitute(new_clause, args)) is not False:
                    kb.retract(self.substitute(new_clause, args))
            else:
                new_clause = Expr('Not' + clause.op, *clause.args)

                if kb.ask(self.substitute(new_clause, args)) is not False:
                    kb.retract(self.substitute(new_clause, args))

        return kb
Beispiel #13
0
 def __init__(self, clauses=None):
     self.const_syms = set()
     self.pred_syms = set()
     FolKB.__init__(self, clauses)
def predictSuccess(current_skills, equation, debug=False):
    skills_needed = []
    statements, counts = parse_equation(equation)
    print("Predicting success on " + equation)
    print("\tSkills: " + str(current_skills))
    if debug:
        print("\tStatements: " + str(statements))

    skills_kb = FolKB()
    for statement in statements:
        skills_kb.tell(expr(statement))

    # Skill 9 - combine two constant terms
    if len(counts["Const"]["Left"]) + len(counts["Const"]["Right"]) > 1:
        skills_kb.tell(expr("LeftConst(a) & RightConst(b) ==> Skill9(a, b)"))
        skills_kb.tell(expr("RightConst(a) & RightConst(b) ==> Skill9(a, b)"))

    # Skill 8 - combine two variable terms on a side to get a negative number
    # Skill 7 - combine two variable terms on a side to get a positive number
    if len(counts["Var"]["Left"]) + len(counts["Var"]["Right"]) > 1:
        if len(counts["Var"]["Left"]) == 1 and len(
                counts["Var"]["Right"]) == 1:  # Ex: 2x=4x+1
            if counts["Var"]["Left"][0] - counts["Var"]["Right"][0] < 0:
                skills_kb.tell(
                    expr("LeftVar(a) & RightVar(b) ==> Skill8(a, b)"))
            else:
                skills_kb.tell(
                    expr("LeftVar(a) & RightVar(b) ==> Skill7(a, b)"))
        elif len(counts["Var"]["Left"]) >= 2:
            if counts["Var"]["Left"][0] + counts["Var"]["Left"][
                    1] < 0:  # Ex: 4x-6x=4
                skills_kb.tell(
                    expr("LeftVar(a) & LeftVar(b) ==> Skill8(a, b)"))
            else:
                skills_kb.tell(
                    expr("LeftVar(a) & LeftVar(b) ==> Skill7(a, b)"))
        elif len(counts["Var"]["Right"]) >= 2:
            if counts["Var"]["Right"][0] + counts["Var"]["Right"][
                    1] < 0:  # Ex: 4=4x-6x
                skills_kb.tell(
                    expr("RightVar(a) & RightVar(b) ==> Skill8(a, b)"))
            else:
                skills_kb.tell(
                    expr("RightVar(a) & RightVar(b) ==> Skill7(a, b)"))

    # Skill 6 - divide both sides by a negative constant
    # Skill 5 - divide both sides by a positive constant
    final_var_value = 0
    for varVal in counts["Var"]["Left"]:
        final_var_value += varVal
    for varVal in counts["Var"]["Right"]:
        final_var_value -= varVal
    if debug:
        print("\tFinal var value: " + str(final_var_value))
    if final_var_value < 0:
        skills_kb.tell(expr("LeftVar(a) ==> Skill6(a)"))
        skills_kb.tell(expr("RightVar(a) ==> Skill6(a)"))
    elif final_var_value == 1:
        pass
    else:
        skills_kb.tell(expr("LeftVar(a) ==> Skill5(a)"))
        skills_kb.tell(expr("RightVar(a) ==> Skill5(a)"))

    # Skill 4 - add a negative constant term from both sides
    # Skill 3 - add a positive constant term to both sides
    if len(counts["Const"]["Left"]) > 0:
        final_left_value = 0
        for constVal in counts["Const"]["Left"]:
            final_left_value += constVal
        if final_left_value < 0:
            skills_kb.tell(expr("LeftConst(a) ==> Skill3(a)"))
        else:
            skills_kb.tell(expr("LeftConst(a) ==> Skill4(a)"))

    skills = [
        "Skill9", "Skill8", "Skill7", "Skill6", "Skill5", "Skill4", "Skill3",
        "Skill2", "Skill1"
    ]
    two_param_skills = ["Skill9", "Skill8", "Skill7"]

    # Skill 2 - add a negative variable term to both sides
    # Skill 1 - add a positive variable term to both sides
    if len(counts["Var"]["Right"]) > 0:
        final_right_value = 0
        for varVal in counts["Var"]["Right"]:
            final_right_value += varVal
        if final_right_value < 0:
            skills_kb.tell(expr("RightVar(a) ==> Skill1(a)"))
        else:
            skills_kb.tell(expr("RightVar(a) ==> Skill2(a)"))

    if debug:
        print("\tAsk KB:")
    for skill in skills:
        if skill in two_param_skills and skills_kb.ask(expr(skill + '(a, b)')):
            skills_needed.append(skill[0] + skill[-1])
            if debug:
                print("\t\t" + skill + " ==> NEEDED")
        elif skills_kb.ask(expr(skill + '(a)')):
            skills_needed.append(skill[0] + skill[-1])
            if debug:
                print("\t\t" + skill + " ==> NEEDED")

    missing_skills = []
    for skill in skills_needed:
        if skill not in current_skills:  # If we don't know the skill yet
            missing_skills.append(skill)
    return missing_skills
Beispiel #15
0
 def __init__(self, initial_state, actions, goal_test):
     self.kb = FolKB(initial_state)
     self.actions = actions
     self.goal_test_func = goal_test
from logic import FolKB
from utils import expr

kb = FolKB(
    map(expr, [
        'List(xs) ==> List(Ins(x, xs))', 'List(EmptyList)',
        'Pert(x, Ins(x, xs))', 'Pert(x, ys) ==> Pert(x, Ins(y,ys))',
        'Concat(EmptyList, ys, ys)',
        'Concat(xs, ys, zs) ==> Concat(Ins(x, xs), ys, Ins(x, zs))'
    ]))


def test_list():
    assert repr(kb.ask(expr('List(EmptyList)'))) == '{}'
    assert repr(kb.ask(
        expr('List(Ins(One, EmptyList))'))) == '{v_3: One, v_2: EmptyList}'
    assert repr(kb.ask(expr('List(Ins(One, Ins(Two, EmptyList)))'))) == '{v_7: One, v_6: Ins(Two, EmptyList),' \
                                                                        ' v_9: Two, v_8: EmptyList}'
    assert repr(kb.ask(expr('List(Ins(One, Two))'))) == 'False'


def test_x_in_2_1_3():
    answer = kb.ask_generator(
        expr('Pert(x, (Ins(Two,Ins(One ,Ins(Three, EmptyList)))))'))
    for i in answer:
        if i == 0:
            assert i.x == 'Two'
        if i == 1:
            assert i.x == 'One'
        if i == 2:
            assert i.x == 'Three'
Beispiel #17
0
    def perform_actions(self):
        """Performs the necessary actions and returns a new Level"""

        new_kb = FolKB(list(set(self.next_state_links.keys())))
        return Level(new_kb)
Beispiel #18
0
 def __init__(self, pddl):
     self.pddl = pddl
     self.kb = FolKB(pddl.init)
     self.levels = [Level(self.kb)]
     self.objects = set(arg for clause in self.kb.clauses for arg in clause.args)
Beispiel #19
0
 def perform_actions(self):
     new_kb_pos, new_kb_neg = FolKB(
         list(set(self.next_state_links_pos.keys()))), FolKB(
             list(set(self.next_state_links_neg.keys())))
     return Level(new_kb_pos, new_kb_neg)
 def __init__(self, clauses=[]):
     self.const_syms = set()
     self.pred_syms = set()
     FolKB.__init__(self, clauses)