def safe(self): """ Use logic to determine the set of locations I can prove to be safe. """ safe_spots = set() for x in range(1, self.size + 1): for y in range(1, self.size + 1): #Current location loc = "" + str(x) + "_" + str(y) #Add current location spot to the safe_spots if resolution(self.KB, logic.expr("L" + loc)): safe_spots.add((x, y)) #Not a pit or not a wumpus at current location if resolution(self.KB, logic.expr("~P" + loc)) and resolution( self.KB, logic.expr("~W" + loc)): safe_spots.add((x, y)) # If no smell, and no breeze, then all neighbors are safe locations. no_smell = resolution(self.KB, logic.expr("~S" + loc)) no_breeze = resolution(self.KB, logic.expr("~B" + loc)) if (no_smell and no_breeze): for n in self.get_neighbors(x, y, self.size): #print "Adding " + str(n) + " to safe_spots" safe_spots.add(n) #take intersection so that only neighbours are looked at #honestly, i dont think we should be double looping ehre neighbours = self.get_neighbors(self.location[0], self.location[1], self.size) return safe_spots.intersection(neighbours)
def _gen_decode(self, key): key = key.capitalize() results = self.ask("Var(" + key + ", value, type)") if isinstance(results, types.BooleanType): yield None for res in results: value = str(res[expr("value")]) typ = str(res[expr("type")]) if typ == "Int": yield int(value) elif typ == "Str": yield str(value).lower() elif typ == "Float": yield float(value) elif typ == "List": l = [] listID = str(value) gen = self._gen_decode(listID) hasElements = True while hasElements: try: l.append(gen.next()) except: hasElements = False yield l elif typ == "Dict": dictID = str(value) d = {} for i in self.ask("Pair(" + dictID + ", elemid)"): elemID = str(i[expr("elemid")]) newkey = self._gen_decode(elemID + "Key").next() newvalue = self._gen_decode(elemID + "Value").next() d[newkey] = newvalue yield d
def not_unsafe(self): """ Use logic to determine the set of locations I can't prove to be unsafe """ not_unsafe_spots = set() for x in range(1, self.size + 1): for y in range(1, self.size + 1): #Current location loc = "" + str(x) + "_" + str(y) if not logic_440.resolution(self.KB, logic.expr("L" + loc)): not_unsafe_spots.add((x,y)) if logic_440.resolution(self.KB, logic.expr("P" + loc)) or logic_440.resolution(self.KB, logic.expr("W" + loc)): if not_unsafe_spots.__contains__((x,y)): not_unsafe_spots.remove((x,y)) # If no smell, and no breeze, then all neighbors are safe locations. no_smell = logic_440.resolution(self.KB, logic.expr("~S" + loc)) no_breeze = logic_440.resolution(self.KB, logic.expr("~B" + loc)) if (no_smell and no_breeze): for n in get_neighbors(x, y, self.size): #print "Adding " + str(n) + " to not_unsafe_spots" not_unsafe_spots.add(n) return not_unsafe_spots
def safe(self): """ Use logic to determine the set of locations I can prove to be safe. """ safe_spots = set() for x in range(1, self.size + 1): for y in range(1, self.size + 1): #Current location loc = "" + str(x) + "_" + str(y) #Add current location spot to the safe_spots if logic_440.resolution(self.KB, logic.expr("L" + loc)): safe_spots.add((x,y)) #Not a pit or not a wumpus at current location if logic_440.resolution(self.KB, logic.expr("~P" + loc)) and logic_440.resolution(self.KB, logic.expr("~W" + loc)): safe_spots.add((x,y)) # If no smell, and no breeze, then all neighbors are safe locations. no_smell = logic_440.resolution(self.KB, logic.expr("~S" + loc)) no_breeze = logic_440.resolution(self.KB, logic.expr("~B" + loc)) if (no_smell and no_breeze): for n in get_neighbors(x, y, self.size): #print "Adding " + str(n) + " to safe_spots" safe_spots.add(n) return safe_spots
def __init__(self): # Knows there is no pit or wumpus in the starting spot self.knows = expr('~P30 & ~W30') # Lists of initial sentences templist = [] for x in range(4): for y in range(4): for l, r in (('B', 'P'), ('S', 'W')): tempLeft = "%s%s%s" % (l, x, y) tempRight = [] for s, t in get_neighbors(x, y): tempRight.append("%s%s%s" % (r, s, t)) templist.append("(%s <=> (%s))" % \ (tempLeft, ' | '.join(tempRight))) implications = expr(' & '.join(templist)) templist2 = ['W%s%s' % (i, j) for i in range(4) for j in range(4)] wumpus = expr(' | '.join(templist2)) templist3 = ['(~W%s%s | ~W%s%s)' % (i, j, x, y) for i in range(4) \ for j in range(4) \ for x in range(4) \ for y in range(4) \ if not ((i == x) and (j == y))] wumpus2 = expr(' & '.join(templist3)) # Insert lists of sentence expressions into KB self.knows &= implications self.knows &= wumpus self.knows &= wumpus2
def not_unsafe(self): """ Use logic to determine the set of locations I can't prove to be unsafe """ not_unsafe_spots = set() for x in range(1, self.size + 1): for y in range(1, self.size + 1): #Current location loc = "" + str(x) + "_" + str(y) if not resolution(self.KB, logic.expr("L" + loc)): not_unsafe_spots.add((x, y)) if resolution(self.KB, logic.expr("P" + loc)) or resolution( self.KB, logic.expr("W" + loc)): if not_unsafe_spots.__contains__((x, y)): not_unsafe_spots.remove((x, y)) # If no smell, and no breeze, then all neighbors are safe locations. no_smell = resolution(self.KB, logic.expr("~S" + loc)) no_breeze = resolution(self.KB, logic.expr("~B" + loc)) if (no_smell and no_breeze): for n in self.get_neighbors(x, y, self.size): #print "Adding " + str(n) + " to not_unsafe_spots" not_unsafe_spots.add(n) neighbours = self.get_neighbors(self.location[0], self.location[1], self.size) # print("i am look ing at neighbouts ") # print(neighbours) # print("this isthe intersection") # print(not_unsafe_spots.intersection(neighbours)) #take intersection so that only neighbours are looked at #honestly, i dont think we should be double looping ehre return not_unsafe_spots.intersection(neighbours)
def test_safe(self): agent = hw3.WumpusWorldAgent(4) agent.KB.tell(logic.expr('P2_3')) agent.KB.tell(logic.expr('~P1_1')) agent.KB.tell(logic.expr('~W1_1')) safe = agent.safe() self.assertTrue((2, 3) not in safe) self.assertTrue((1, 1) in safe)
def not_unsafe(self): notunsafe_set = Set([]) for i in range(1, self.size + 1): for j in range(1, self.size + 1): pit = logic.expr("P%d_%d" % (i,j)) wumpus = logic.expr("W%d_%d" % (i,j)) if not(((logic_440.resolution(self.KB, pit) or logic_440.resolution(self.KB, wumpus)))): notunsafe_set.add((i,j)) return notunsafe_set
def safe(self): safe_set = Set([]) for i in range(1, self.size + 1): for j in range(1, self.size + 1): not_pit = logic.expr("~P%d_%d" % (i,j)) not_wumpus = logic.expr("~W%d_%d" % (i,j)) if 'L%d_%d' in self.KB.clauses: safe_set.add((i,j)) elif ((logic_440.resolution(self.KB, not_pit) and logic_440.resolution(self.KB, not_wumpus))): safe_set.add((i,j)) return safe_set
def _gen_decode(self, key): key = key.capitalize() results = self.ask("Var(" + key + ", value, type)") if isinstance(results, bool): yield None for res in results: value = str(res[expr("value")]) typ = str(res[expr("type")]) if typ == "Int": yield int(value) elif typ == "Str": yield str(value).lower() elif typ == "Float": yield float(value) elif typ == "List": l = [] listID = str(value) gen = self._gen_decode(listID) hasElements = True while hasElements: try: l.append(gen.next()) except: hasElements = False yield l elif typ == "Dict": dictID = str(value) d = {} for i in self.ask("Pair(" + dictID + ", elemid)"): elemID = str(i[expr("elemid")]) if elemID == "Empty_object": continue newkey = self._gen_decode(elemID + "Key").next() newvalue = self._gen_decode(elemID + "Value").next() d[newkey] = newvalue yield d elif typ == "NoneType": yield None else: objid = str(key) res = self.ask("Var(" + objid + ", value, type)")[0] classname = str(res[expr("type")]) objdict = str(res[expr("value")]) try: module, clas = classname.split(".") obj = get_object_instance(clas, module) d = self._gen_decode(objdict).next() if d == None: d = {} obj.__dict__ = d yield obj except: raise GeneratorExit, "No such class in namespace: %s" % classname
def tell(self, sentence): if issubclass(sentence.__class__, str): sentence = expr(sentence) if is_definite_clause(sentence): self.clauses.append(sentence) else: raise Exception("Not a definite clause: %s" % sentence)
def run_minisat_test(): """ Test connection to MiniSat """ import logic queries = [("(P | ~P)", True), # SAT ("(P & ~P)", False), # UNSAT ("(P | R) <=> (~(Q | R) & (R >> ~(S <=> T)))", True) # SAT ] print "Running simple MiniSat test:" t = 1 failed = [] for query, expected_result in queries: print "-----------------------------------------------------" print "Test {0}".format(t) print " Query: '{0}'".format(query) query = logic.conjuncts(logic.to_cnf(logic.expr(query))) result = minisat(query, None, variable=None, value=True, verbose=False) print " Query CNF: {0}".format(query) print " Result: {0} (Expected: {1})".format(result.success, expected_result) if result.success != expected_result: print " FAILURE: unexpected result." failed.append(t) if result.success: print " Variable Assignment: {0}".format(result.varmap) t += 1 print "-----------------------------------------------------" if not failed: print "Successfully passed {0} tests.".format(len(queries)) else: print "Passed {0} test(s).".format(len(queries) - len(failed)) print "The following tests failed: {0}".format(failure) print "DONE."
def unvisited(self): unvisited = Set([]) for i in range(1, self.size + 1): for j in range(1, self.size +1): if logic.expr('L%d_%d' % (i,j)) not in self.KB.clauses: unvisited.add((i,j)) return unvisited
def giveFeedback(student_state): statement_list = [ "CorrectAnswer ==> (Message1 | Message2 | Message3 | Message7)", "~CorrectAnswer ==> (Message4 | Message5 | Message6 | Message8)", "(MasteredSkill & ~CorrectAnswer) & (MasteredSkill & CorrectStreak) ==> IsBored", "(NewSkill | IncorrectStreak) & CorrectAnswer ==> Message6", "(IncorrectStreak & CorrectAnswer) | (NewSkill & CorrectStreak) ==> NeedsEncouragement", "NeedsEncouragement & CorrectAnswer ==> Message2", "NeedsEncouragement & ~CorrectAnswer ==> Message4", "IsBored ==> Message3 | Message5", "(NewSkill & CorrectAnswer) | CorrectStreak ==> Message1" ] priority_array = [ "Message1", "Message2", "Message3", "Message4", "Message5", "Message6", "Message7", "Message8" ] msg_dict = { "Message1": M1, "Message2": M2, "Message3": M3, "Message4": M4, "Message5": M5, "Message6": M6, "Message7": M7, "Message8": M8 } feedback_msg = "Nothing Entailed" knowledge_base = PropKB() for s in statement_list: knowledge_base.tell(s) knowledge_base.tell(expr(student_state)) # Iterate through all propositions for p in priority_array: p_expr = expr(p) resolution_bool = pl_resolution(knowledge_base, p_expr) if resolution_bool: print(str(resolution_bool) + " : " + p) return "Message: " + msg_dict.get(p) else: neg_p_expr = expr('~' + p) knowledge_base.tell(neg_p_expr) print('Adding: ~' + p) return feedback_msg
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 unvisited(self): unvisitedList = [] for x in range(1, self.size + 1): for y in range(1, self.size + 1): s = 'L' + str(x) + '_' + str(y) if (logic_440.resolution(self.KB, logic.expr(s)) == False): unvisitedList.append((x, y)) return set(unvisitedList)
def __init__(self, cave_size): self.KB = logic.PropKB() self.size = cave_size for i in range(1, cave_size + 1): for j in range(1, cave_size + 1): neighbors = get_neighbors(i, j, cave_size) exp1 = 'B%d_%d <=> (' % (i,j) exp2 = 'S%d_%d <=> (' % (i,j) for k in range(len(neighbors)): if k == len(neighbors) - 1: exp1 += ' P%d_%d)' % neighbors[k] exp2 += ' W%d_%d)' % neighbors[k] else: exp1 += ' P%d_%d |' % neighbors[k] exp2 += ' W%d_%d |' % neighbors[k] self.KB.tell(logic.expr(exp1)) self.KB.tell(logic.expr(exp2))
def __init__(self, cave_size): self.KB = logic.PropKB() self.size = cave_size for x in range(1, cave_size + 1): for y in range(1, cave_size + 1): neigh = get_neighbors(x, y, cave_size) n1 = neigh[0][0] n2 = neigh[0][1] s = 'B' + str(x) + '_' + str(y) + ' <=> ' + 'P' + str( n1) + '_' + str(n2) t = 'S' + str(x) + '_' + str(y) + ' <=> ' + 'W' + str( n1) + '_' + str(n2) for n in neigh[1:]: s = s + ' | P' + str(n[0]) + '_' + str(n[1]) t = t + ' | W' + str(n[0]) + '_' + str(n[1]) self.KB.tell(logic.expr(s)) self.KB.tell(logic.expr(t))
def __init__(self, problem, num_of_transmitters): # TODO : COMPLETE BY STUDENTS locations = any_location(problem[4], problem[5], problem[6]) global state global states global move_back global prev_fit global space_kb space_kb = logic.PropKB() self.state= self.problem = (problem[0], self.make_inst_on_ships(problem[6], problem[3]), tuple(problem[4].items()), tuple(problem[5].items()), locations) print(self.problem) for ship in self.state[1]: pos_str = 'P' + str(ship[1]) self.space_kb.tell(~logic.expr(pos_str)) pos_str = 'P' + str((ship[1][0] + 1, ship[1][1], ship[1][2])) print(pos_str) self.space_kb.tell(~logic.expr(pos_str)) pos_str = 'P' + str((ship[1][0] - 1, ship[1][1], ship[1][2])) print(pos_str) self.space_kb.tell(~logic.expr(pos_str)) print(pos_str) pos_str = 'P' + str((ship[1][0], ship[1][1] + 1, ship[1][2])) print(pos_str) self.space_kb.tell(~logic.expr(pos_str)) pos_str = 'P' + str((ship[1][0], ship[1][1] - 1, ship[1][2])) print(pos_str) self.space_kb.tell(~logic.expr(pos_str)) pos_str = 'P' + str((ship[1][0], ship[1][1], ship[1][2] + 1)) print(pos_str) self.space_kb.tell(~logic.expr(pos_str)) pos_str = 'P' + str((ship[1][0], ship[1][1], ship[1][2] - 1)) print(pos_str) self.space_kb.tell(~logic.expr(pos_str))
def safe(self): safeList = [] for x in range(1, self.size + 1): for y in range(1, self.size + 1): s = '~W' + str(x) + '_' + str(y) + ' & ' + '~P' + str( x) + '_' + str(y) if (logic_440.resolution(self.KB, logic.expr(s)) == True): safeList.append((x, y)) return set(safeList)
def convert(self, clauses): """Converts strings into Exprs""" if isinstance(clauses, logic.Expr): clauses = logic.conjuncts(clauses) for i in range(len(clauses)): if clauses[i].op == '~': clauses[i] = logic.expr('Not' + str(clauses[i].args[0])) elif isinstance(clauses, str): clauses = clauses.replace('~', 'Not') if len(clauses) > 0: clauses = logic.expr(clauses) try: clauses = logic.conjuncts(clauses) except AttributeError: pass return clauses
def unvisited(self): """ Use logic to determine the set of locations I haven't visited yet. """ result = set() for x in range(1, self.size + 1): for y in range(1, self.size + 1): if not resolution(self.KB, logic.expr("L" + str(x) + "_" + str(y))): result.add((x, y)) return result
def unvisited(self): """ Use logic to determine the set of locations I haven't visited yet. """ result = set() for x in range(1, self.size + 1): for y in range(1, self.size + 1): if not logic_440.resolution(self.KB, logic.expr("L" + str(x) + "_" + str(y))): result.add((x,y)) return result
def predictSuccess(current_skills, equation): missing_skills = [] skillsNeeded = formulateProblem(equation, current_skills) for skill in skillsNeeded: skills_kb.tell(skill) if skill == "AddPosVar": resolution = logic.pl_resolution(skills_kb, logic.expr('S1')) if resolution == True: missing_skills.append('S1') if skill == "AddNegVar": resolution = logic.pl_resolution(skills_kb, logic.expr('S2')) if resolution == True: missing_skills.append('S2') if skill == "AddPosConst": resolution = logic.pl_resolution(skills_kb, logic.expr('S3')) if resolution == True: missing_skills.append('S3') if skill == 'AddNegConst': resolution = logic.pl_resolution(skills_kb, logic.expr('S4')) if resolution == True: missing_skills.append('S4') if skill == 'DivPosConst': resolution = logic.pl_resolution(skills_kb, logic.expr('S5')) if resolution == True: missing_skills.append('S5') if skill == 'DivNegConst': resolution = logic.pl_resolution(skills_kb, logic.expr('S6')) if resolution == True: missing_skills.append('S6') if skill == 'CombVar2Pos': resolution = logic.pl_resolution(skills_kb, logic.expr('S7')) if resolution == True: missing_skills.append('S7') if skill == 'CombVar2Neg': resolution = logic.pl_resolution(skills_kb, logic.expr('S8')) if resolution == True: missing_skills.append('S8') if skill == 'CombConst': resolution = logic.pl_resolution(skills_kb, logic.expr('S9')) if resolution == True: missing_skills.append('S9') for curr_skill in current_skills: if missing_skills.__contains__(curr_skill): missing_skills.remove(curr_skill) #print(missing_skills) return missing_skills
def new_literals(self, clause): """Generates new literals based on known predicate symbols. Generated literal must share atleast one variable with clause""" share_vars = variables(clause[0]) for l in clause[1]: share_vars.update(variables(l)) for pred, arity in self.pred_syms: new_vars = {standardize_variables(expr('x')) for _ in range(arity - 1)} for args in product(share_vars.union(new_vars), repeat=arity): if any(var in share_vars for var in args): yield Expr(pred, *[var for var in args])
def not_unsafe(self): roomlist = [] unsafeList = [] safeList = self.safe() for x in range(1, self.size + 1): for y in range(1, self.size + 1): roomlist.append((x, y)) if ((x, y) not in safeList): s = 'W' + str(x) + '_' + str(y) + ' | ' + 'P' + str( x) + '_' + str(y) if (logic_440.resolution(self.KB, logic.expr(s)) == True): unsafeList.append((x, y)) return set(roomlist) - set(unsafeList)
def new_literals(self, clause): """Generate new literals based on known predicate symbols. Generated literal must share at least one variable with clause""" share_vars = variables(clause[0]) for l in clause[1]: share_vars.update(variables(l)) for pred, arity in self.pred_syms: new_vars = {standardize_variables(expr('x')) for _ in range(arity - 1)} for args in product(share_vars.union(new_vars), repeat=arity): if any(var in share_vars for var in args): # make sure we don't return an existing rule if not Expr(pred, args) in clause[1]: yield Expr(pred, *[var for var in args])
def __init__(self, problem, num_of_transmitters): #building representation for world as in part 1 # problem is a tuple of all the input global GRID_LIMIT global my_world GRID_LIMIT = problem[0] spaceships = () # tuple of: (ShipName, Location) devices = ( ) # tuple of: (ShipName, DeviceName, Power, Calibrated, CalibrationTarget, FinalTarget,Hit) all_targets = () #define class propKB to use later self.lasers_logic = logic.PropKB() #define dictionary to save all grid to use later self.grid_dict = {} for x in range(GRID_LIMIT): for y in range(GRID_LIMIT): for z in range(GRID_LIMIT): self.grid_dict[(x, y, z)] = logic.expr('L' + str(x) + str(y) + str(z)) for ship_name in problem[1]: # creating spaceships tuple ship_starting_location = problem[6][ ship_name] # get ships location new_ship = (ship_name, ship_starting_location) spaceships = (new_ship, ) + spaceships # creating devices tuple all_devices = problem[3][ship_name] # get ships devices for device_name in all_devices: device_calib = problem[4][device_name] #####creating all targets tuple### if device_calib not in all_targets: all_targets = (device_calib, ) + all_targets for key in problem[5]: if key not in all_targets: all_targets = (key, ) + all_targets ################################# values = problem[5][key] if device_name in values: new_device = (ship_name, device_name, 0, 0, device_calib, key, 0) devices = (new_device, ) + devices my_world = (spaceships, devices, all_targets)
def main(): A, B, C = expr('A, B, C') knowledge_base = [A & C, B, A & B] statements = {'Arthur': B & C, 'Bertram': ~B, 'Carleton': A & B} murderer = None for suspect, statement in statements.items(): test = [*knowledge_base, ~statement] result = WalkSAT(test) if result is None: print(f"{suspect} didn't lie.") else: print(f"{suspect} lied.") murderer = suspect print(f'{murderer} is the murderer.')
def giveFeedback(studentState): message_kb = logic.PropKB() message_kb.tell('CorrectAnswer ==> (M1 | M2 | M3 | M7)') message_kb.tell('~CorrectAnswer ==> (M4 | M5 | M6 | M8)') message_kb.tell( '((MasteredSkill & ~CorrectAnswer) | (MasteredSkill & CorrectStreak)) ==> IsBored' ) message_kb.tell('(NewSkill | IncorrectStreak) ==> M6') message_kb.tell( '((IncorrectStreak & CorrectAnswer) | (NewSkill & CorrectStreak)) ==> NeedsEncouragement' ) message_kb.tell('NeedsEncouragement ==> (M2 | M4)') message_kb.tell('IsBored ==> (M3 | M5)') message_kb.tell('((NewSkill & CorrectAnswer) | CorrectStreak) ==> M1') message_kb.tell(studentState) feedbackMessage = 'no answer' if message_kb.ask_if_true(logic.expr('CorrectAnswer')): feedbackMessage = M7 if logic.pl_resolution(message_kb, logic.expr('M1')): feedbackMessage = M1 elif logic.pl_resolution(message_kb, logic.expr('M2')): feedbackMessage = M2 elif logic.pl_resolution(message_kb, logic.expr('M3')): feedbackMessage = M3 elif message_kb.ask_if_true(logic.expr('~CorrectAnswer')): feedbackMessage = M8 if logic.pl_resolution(message_kb, logic.expr('M4')): feedbackMessage = M4 elif logic.pl_resolution(message_kb, logic.expr('M5')): feedbackMessage = M5 elif logic.pl_resolution(message_kb, logic.expr('M6')): feedbackMessage = M6 """print('M1: ' + str(logic.pl_resolution(message_kb, logic.expr('M1')))) print('M2: ' + str(logic.pl_resolution(message_kb, logic.expr('M2')))) print('M3: ' + str(logic.pl_resolution(message_kb, logic.expr('M3')))) print('M4: ' + str(logic.pl_resolution(message_kb, logic.expr('M4')))) print('M5: ' + str(logic.pl_resolution(message_kb, logic.expr('M5')))) print('M6: ' + str(logic.pl_resolution(message_kb, logic.expr('M6')))) print('M7: ' + str(logic.pl_resolution(message_kb, logic.expr('M7')))) print('M8: ' + str(logic.pl_resolution(message_kb, logic.expr('M8')))) print('NeedsEncouragement: ' + str(message_kb.ask_if_true(logic.expr('NeedsEncouragement')))) print('IsBored: ' + str(message_kb.ask_if_true(logic.expr('IsBored'))))""" return feedbackMessage
def ask(self, q): e = expr(q) vars = variables(e) ans = fol_bc_ask(self, [e]) res = [] for a in ans: res.append(dict([(x, v) for (x, v) in a.items() if x in vars])) res.sort(key=str) if res == []: return False for r in res: if r != {}: return res return True # res is a list of empty dicts
def ask_kb(percept, move, agent): """ Ask the kb stuff """ oz_kb = agent.oz_kb sentence = pit_iff(move, agent.some_number) satisfy_dpll = dpll_satisfiable(expr(sentence)) isin_kb = lambda item_s: oz_kb.has_key(item_s) contradicts_kb = lambda item_s, obj: oz_kb[item_s] != satisfy_dpll[obj] has_all = True for key in satisfy_dpll.keys(): var = key.__repr__() if isin_kb(var) and contradicts_kb(var, key): return True if not isin_kb(var): has_all = False if has_all: agent.explored[move] = True return False
def test_unvisited(self): agent = hw3.WumpusWorldAgent(4) agent.KB.tell(logic.expr('L2_3')) unvisited = agent.unvisited() self.assertTrue((2, 3) not in unvisited) self.assertTrue((1, 1) in unvisited)
def test_background_knowledge(self): print Test agent = hw3.WumpusWorldAgent(4) agent.KB.tell(logic.expr('B1_1')) agent.KB.tell(logic.expr('~P1_2')) self.assertTrue(logic_440.resolution(agent.KB, logic.expr('P2_1')))
import logic import itertools KB = logic.PropKB() # initial state KB.tell(logic.expr("~At_0(Spare, Ground)")) KB.tell(logic.expr("At_0(Spare, Trunk)")) KB.tell(logic.expr("~At_0(Spare, Axle)")) KB.tell(logic.expr("At_0(Flat, Axle)")) KB.tell(logic.expr("~At_0(Flat, Ground)")) KB.tell(logic.expr("~At_0(Flat, Trunk)")) KB.tell(logic.expr("~At_0(Flat, Trunk)")) # KB.tell(logic.expr("At_1(Spare, Ground)")) # KB.tell(logic.expr("At_1(Spare, Trunk)")) # KB.tell(logic.expr("At_1(Spare, Axle)")) # KB.tell(logic.expr("At_1(Flat, Axle)")) # KB.tell(logic.expr("At_1(Flat, Ground)")) # KB.tell(logic.expr("At_1(Flat, Trunk)")) # KB.tell(logic.expr("At_1(Flat, Trunk)")) ##do not include not possible actions, will keep model simpler # first KB.tell(logic.expr("~Remove_0(Spare, Trunk) | At_0(Spare, Trunk)")) KB.tell(logic.expr("~Remove_0(Flat, Axle) | At_0(Flat, Axle)"))
import logic import itertools KB = logic.PropKB() #initial state # KB.tell(logic.expr("~At0SpareGround | At_0(Spare,Trunk) | ~At_0(Spare,Axle)")) # # # KB.tell(logic.expr("At_0(Flat,Axle) | ~At_0(Flat,Ground) | ~At_0(Flat,Trunk)")) KB.tell(logic.expr("~At0SpareGround")) KB.tell(logic.expr("At_0(Spare,Trunk)")) KB.tell(logic.expr("~At_0(Spare,Axle)")) KB.tell(logic.expr("At_0(Flat,Axle)")) KB.tell(logic.expr("~At_0(Flat,Ground)")) KB.tell(logic.expr("~At_0(Flat,Trunk)")) ##do not include not possible actions,will keep model simpler #first KB.tell(logic.expr("~Remove0SpareTrunk | At_0(Spare,Trunk)")) KB.tell(logic.expr("~Remove_0(Flat,Axle) | At_0(Flat,Axle)")) KB.tell(logic.expr("~Remove_1(Spare,Trunk) | At_1(Spare,Trunk)")) KB.tell(logic.expr("~Remove_1(Flat,Axle) | At_1(Flat,Axle)"))
def solve(steps): for moves in range(0, steps+1): print("trying with "+str(moves)+" moves") KB = logic.PropKB() #initial state KB.tell(logic.expr("~At_0(Spare, Ground)")) KB.tell(logic.expr("At_0(Spare, Trunk)")) KB.tell(logic.expr("~At_0(Spare, Axle)")) KB.tell(logic.expr("At_0(Flat, Axle)")) KB.tell(logic.expr("~At_0(Flat, Ground)")) KB.tell(logic.expr("~At_0(Flat, Trunk)")) #first preconditions for i in range(0,moves): KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Trunk) | At_"+str(i)+"(Spare, Trunk)")) KB.tell(logic.expr("~PutOn_"+str(i)+"(Spare, Axle) | At_"+str(i)+"(Spare, Ground)")) KB.tell(logic.expr("~PutOn_"+str(i)+"(Spare, Axle) | ~At_"+str(i)+"(Flat, Axle) ")) KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Axle) | At_"+str(i)+"(Spare, Axle)")) KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Axle) | At_"+str(i)+"(Flat, Axle)")) KB.tell(logic.expr("~PutOn_"+str(i)+"(Flat, Axle) | At_"+str(i)+"(Flat, Ground) ")) KB.tell(logic.expr("~PutOn_"+str(i)+"(Flat, Axle) | ~At_"+str(i)+"(Flat, Axle) ")) KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Trunk) | At_"+str(i)+"(Flat, Trunk)")) #second positive effects for i in range(0,moves): KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Trunk) | At_"+str(i+1)+"(Spare, Ground)")) KB.tell(logic.expr("~PutOn_"+str(i)+"(Spare, Axle) | At_"+str(i+1)+"(Spare, Axle)")) KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Axle) | At_"+str(i+1)+"(Spare, Ground)")) KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Axle) | At_"+str(i+1)+"(Flat, Ground)")) KB.tell(logic.expr("~PutOn_"+str(i)+"(Flat, Axle) | At_"+str(i+1)+"(Flat, Axle)")) KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Trunk) | At_"+str(i+1)+"(Flat, Ground)")) #third negative effects for i in range(0,moves): KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Trunk) | ~At_"+str(i+1)+"(Spare, Trunk)")) KB.tell(logic.expr("~PutOn_"+str(i)+"(Spare, Axle) | ~At_"+str(i+1)+"(Spare, Ground)")) KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Axle) | ~At_"+str(i+1)+"(Spare, Axle)")) KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Axle) | ~At_"+str(i+1)+"(Flat, Axle)")) KB.tell(logic.expr("~PutOn_"+str(i)+"(Flat, Axle) | ~At_"+str(i+1)+"(Flat, Ground)")) KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Trunk) | ~At_"+str(i+1)+"(Flat, Trunk)")) KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Spare, Ground)")) KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Spare, Axle)")) KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Spare, Trunk)")) KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Flat, Ground)")) KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Flat, Axle)")) KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Flat, Trunk)")) #fourth from false to true for i in range(0,moves): KB.tell(logic.expr("At_"+str(i)+"(Spare, Ground) | ~At_"+str(i+1)+"(Spare, Ground) | Remove_"+str(i)+"(Spare, Trunk) | Remove_"+str(i)+"(Spare, Axle)")) KB.tell(logic.expr("At_"+str(i)+"(Spare, Trunk) | ~At_"+str(i+1)+"(Spare, Trunk)")) KB.tell(logic.expr("At_"+str(i)+"(Spare, Axle) | ~At_"+str(i+1)+"(Spare, Axle) | PutOn_"+str(i)+"(Spare, Axle)")) KB.tell(logic.expr("At_"+str(i)+"(Flat, Axle) | ~At_"+str(i+1)+"(Flat, Axle) | PutOn_"+str(i)+"(Flat, Axle)")) KB.tell(logic.expr("At_"+str(i)+"(Flat, Ground) | ~At_"+str(i+1)+"(Flat, Ground) | Remove_"+str(i)+"(Flat, Axle) | Remove_"+str(i)+"(Flat, Trunk)")) KB.tell(logic.expr("At_"+str(i)+"(Flat, Trunk) | ~At_"+str(i+1)+"(Flat, Trunk)")) #fifth from true to false for i in range(0,moves): KB.tell(logic.expr("~At_"+str(i)+"(Spare, Ground) | At_"+str(i+1)+"(Spare, Ground) | PutOn_"+str(i)+"(Spare, Axle) | LeaveOvernight_"+str(i)+"")) KB.tell(logic.expr("~At_"+str(i)+"(Spare, Trunk) | At_"+str(i+1)+"(Spare, Trunk) | Remove_"+str(i)+"(Spare, Trunk) | LeaveOvernight_"+str(i)+"")) KB.tell(logic.expr("~At_"+str(i)+"(Spare, Axle) | At_"+str(i+1)+"(Spare, Axle) | Remove_"+str(i)+"(Spare, Axle) | LeaveOvernight_"+str(i)+"")) KB.tell(logic.expr("~At_"+str(i)+"(Flat, Axle) | At_"+str(i+1)+"(Flat, Axle) | Remove_"+str(i)+"(Flat, Axle) | LeaveOvernight_"+str(i)+"")) KB.tell(logic.expr("~At_"+str(i)+"(Flat, Ground) | At_"+str(i+1)+"(Flat, Ground) | PutOn_"+str(i)+"(Flat, Axle) | LeaveOvernight_"+str(i)+"")) KB.tell(logic.expr("~At_"+str(i)+"(Flat, Trunk) | At_"+str(i+1)+"(Flat, Trunk) | Remove_"+str(i)+"(Flat, Trunk) | LeaveOvernight_"+str(i)+"")) #list of all possible actions #actions without timestamp, will be added later actions = ["Remove_(Spare, Trunk)", "PutOn_(Spare, Axle)", "Remove_(Spare, Axle)", "Remove_(Flat, Axle)", "PutOn_(Flat, Axle)", "Remove_(Flat, Trunk)", "LeaveOvernight_"] #sixth, only one action can take place for i in range(0,moves): for elem in itertools.combinations(actions, 2): KB.tell(logic.expr("~"+elem[0].replace("_","_"+str(i))+" | ~"+elem[1].replace("_","_"+str(i)))) #seventh, one action must take place for i in range(0,moves): seventh = "" for elem in actions: seventh += elem.replace("_","_"+str(i)) + " | " seventh = seventh[:-2] KB.tell(logic.expr(seventh)) #add goal KB.tell(logic.expr("At_"+str(moves)+"(Spare, Axle)")) #some manual cnf just to be sure string = "" for elem in KB.clauses: elem = logic.to_cnf(str(elem)) string = string + str(elem) + " & " string = string[:-2] action_stubs = ["Remove", "PutOn", "LeaveOvernight"] #print only true values answer = logic.dpll_satisfiable(logic.expr(string)) if answer == False: print("Couldn't solve problem in "+str(moves)+" turns") else: print("Found solution with "+str(moves)+" turns") for elem in answer: if answer[elem]: if any(sub in str(elem) for sub in action_stubs): print(str(elem)+ " : " +str(answer[elem])) break
import logic if __name__ == '__main__': wumpus_kb = logic.PropKB() P11, P12, P21, P22, P31, B11, B21 = logic.expr( 'P11, P12, P21, P22, P31, B11, B21') #B100 = logic.expr('B100') wumpus_kb.tell(~P11) wumpus_kb.tell(B11 | '<=>' | ((P12 | P21))) wumpus_kb.tell(B21 | '<=>' | ((P11 | P22 | P31))) wumpus_kb.tell(~B11) ship = (1, 23, 4) shipstr = 'P' + str((ship[0] + 1, ship[1], ship[2])) #for v in ship: # shipstr += str(v) print(shipstr) wumpus_kb.tell(~logic.expr(shipstr)) result = logic.dpll_satisfiable( logic.to_cnf( logic.associate('&', wumpus_kb.clauses + [logic.expr(P22)]))) print(result) result = logic.dpll_satisfiable( logic.to_cnf( logic.associate('&', wumpus_kb.clauses + [logic.expr(shipstr)]))) print(result)
def action(self): self.update_stats(self.lastAction) per = self.percepts # Update knowledge base if self.position not in self.visited: # print('update kb') self.visited.add(self.position) pos = self.position lpos = self.lastPos #print(pos) self.knownWorld[pos[0]][pos[1]] = self.percepts if (self.percepts[0] == 'stench'): toTell = 'S%s%s' % (pos[0], pos[1]) self.kb.tell(expr(toTell)) else: toTell = '~S%s%s' % (pos[0], pos[1]) self.kb.tell(expr(toTell)) if (self.percepts[1] == 'breeze'): toTell = 'B%s%s' % (pos[0], pos[1]) self.kb.tell(expr(toTell)) else: toTell = '~B%s%s' % (pos[0], pos[1]) self.kb.tell(expr(toTell)) if (self.percepts[4] == 'scream'): self.wumpusAlive = False toTell1 = '~W%s%s' % (pos[0], pos[1]) toTell2 = '~P%s%s' % (pos[0], pos[1]) self.kb.tell(expr(toTell1)) self.kb.tell(expr(toTell2)) # Using corner logic # UPDATE SURROUNDINGS temp = get_neighbors(pos[0], pos[1]) - self.visited #print "surrounding-visited: ", temp temp = temp - self.safe temp = temp - self.notsafe tempS = set() tempN = set() if (per[0] is not 'stench') and (per[1] is not 'breeze'): self.unsure |= self.unsure - set((pos[0], pos[1])) tempS |= temp else: self.unsure |= temp tempF = self.unsure.copy() if len(self.visited) > 1: # add unsure locations as either safe or unsafe for f in tempF: if self.kb.ask(expr('(P%s%s)' % (f[0], f[1]))): self.unsure.remove(f) tempN.add(f) elif self.kb.ask(expr('(W%s%s)' % (f[0], f[1]))): if self.wumpusAlive is True: self.unsure.remove(f) tempN.add(f) else: self.unsure.remove(f) tempS.add(f) elif self.kb.ask(expr('(~W%s%s & ~P%s%s)' % (f[0], f[1], f[0], f[1]))): self.unsure.remove(f) tempS.add(f) if len(tempS) > 0: self.safe |= tempS if len(tempN) > 0: self.notsafe |= tempN self.safe = self.safe - self.visited # # #print "safe list: ", self.safe #print 'danger list: ', self.notsafe #print 'unsure list: ', self.unsure # if (self.start is True) and (self.percepts[0] == 'stench'): action = 'shoot' elif (self.percepts[2] == 'glitter') and (self.hasGold is not True): action = 'grab' elif (self.position == (3, 0)) and ((self.hasGold is True) or (self.escape is True)): action = 'climb' elif (len(self.plan) > 0): # TAKE ACTION FROM PLAN action = self.plan.pop() #print "plan:action: ", action else: # CREATE PLAN # If the agent has gold his next goal should be the exit (start square) posGoals = None if self.hasGold is True: tempGoal = (3, 0) self.unsureGoal = False else: if len(self.safe) > 0: posGoals = self.safe self.unsureGoal = False elif len(self.unsure) > 0: posGoals = self.unsure self.unsureGoal = True else: self.escape = True self.unsureGoal = False if (posGoals is not None): tempGoal = posGoals.pop() else: tempGoal = (3, 0) self.unsureGoal = False #print "Goal: ", tempGoal self.plan = self.create_plan(tempGoal) #print "Plan: ", self.plan # Shoot arrow before final move to make sure if (self.unsureGoal is True) and (len(self.plan) == 1) and \ (self.percepts[0] == 'stench') and (self.arrow == 1): action = 'shoot' else: action = self.plan.pop() #print "pc:action: ", action self.start = False self.lastAction = action return action
def retract(self, sentence): if issubclass(sentence.__class__, str): sentence = expr(sentence) self.clauses.remove(sentence)
import logic KB = logic.PropKB() #initial state KB.tell(logic.expr("At_0(Flat, Axle) & At_0(Spare, Trunk)")) #first KB.tell(logic.expr("~Remove_0(Flat, Axle) | At_0(Flat, Axle)")) KB.tell(logic.expr("~PutOn_0(Flat, Axle) | At_0(Flat, Ground)")) #second KB.tell(logic.expr("~Remove_0(Flat, Axle) | At_1(Flat, Ground)")) KB.tell(logic.expr("~PutOn_0(Flat, Axle) | At_1(Flat, Axle)")) #third KB.tell(logic.expr("~Remove_0(Flat, Axle) | ~At_1(Flat, Axle)")) KB.tell(logic.expr("~PutOn_0(Flat, Axle) | ~At_1(Flat, Ground)")) #fourth KB.tell(logic.expr("At_0(Flat, Axle) | ~At_1(Flat, Axle) | PutOn_0(Flat, Axle)")) KB.tell(logic.expr("At_0(Flat, Ground) | ~At_1(Flat, Ground) | Remove_0(Flat, Axle)"))
import logic import itertools KB = logic.PropKB() # initial state # KB.tell(logic.expr("~At_0(Spare, Ground) | At_0(Spare, Trunk) | ~At_0(Spare, Axle)")) # # # KB.tell(logic.expr("At_0(Flat, Axle) | ~At_0(Flat, Ground) | ~At_0(Flat, Trunk)")) KB.tell(logic.expr("~At_0(Spare, Ground)")) KB.tell(logic.expr("At_0(Spare, Trunk)")) KB.tell(logic.expr("~At_0(Spare, Axle)")) KB.tell(logic.expr("At_0(Flat, Axle)")) KB.tell(logic.expr("~At_0(Flat, Ground)")) KB.tell(logic.expr("~At_0(Flat, Trunk)")) ##do not include not possible actions, will keep model simpler # first KB.tell(logic.expr("~Remove_0(Spare, Trunk) | At_0(Spare, Trunk)")) KB.tell(logic.expr("~Remove_0(Flat, Axle) | At_0(Flat, Axle)")) KB.tell(logic.expr("~Remove_1(Spare, Trunk) | At_1(Spare, Trunk)")) KB.tell(logic.expr("~Remove_1(Flat, Axle) | At_1(Flat, Axle)")) KB.tell(logic.expr("~PutOn_2(Spare, Axle) | At_2(Spare, Ground)"))
import logic import itertools KB = logic.PropKB() #initial state KB.tell(logic.expr("~At_0(Spare, Ground)")) KB.tell(logic.expr("At_0(Spare, Trunk)")) KB.tell(logic.expr("~At_0(Spare, Axle)")) KB.tell(logic.expr("At_0(Flat, Axle)")) KB.tell(logic.expr("~At_0(Flat, Ground)")) KB.tell(logic.expr("~At_0(Flat, Trunk)")) #first preconditions KB.tell(logic.expr("~Remove_0(Spare, Trunk) | At_0(Spare, Trunk)")) KB.tell(logic.expr("~PutOn_0(Spare, Axle) | At_0(Spare, Ground)")) KB.tell(logic.expr("~PutOn_0(Spare, Axle) | ~At_0(Flat, Axle) ")) KB.tell(logic.expr("~Remove_0(Spare, Axle) | At_0(Spare, Axle)")) KB.tell(logic.expr("~Remove_0(Flat, Axle) | At_0(Flat, Axle)")) KB.tell(logic.expr("~PutOn_0(Flat, Axle) | At_0(Flat, Ground) ")) KB.tell(logic.expr("~PutOn_0(Flat, Axle) | ~At_0(Flat, Axle) ")) KB.tell(logic.expr("~Remove_0(Flat, Trunk) | At_0(Flat, Trunk)")) KB.tell(logic.expr("~Remove_1(Spare, Trunk) | At_1(Spare, Trunk)")) KB.tell(logic.expr("~PutOn_1(Spare, Axle) | At_1(Spare, Ground)")) KB.tell(logic.expr("~PutOn_1(Spare, Axle) | ~At_1(Flat, Axle) "))
import logic import itertools KB = logic.PropKB() #initial state KB.tell(logic.expr("At_0(Flat, Axle) & ~At_0(Flat, Ground) & ~At_0(Flat, Trunk)")) KB.tell(logic.expr("~At_0(Spare, Axle) & ~At_0(Spare, Ground) & At_0(Spare, Trunk)")) # KB.tell(logic.expr("At_0(Flat, Axle) & At_0(Spare, Trunk)")) # #initial locations imply parts are not elsewhere at the same time # KB.tell(logic.expr("~At_0(Flat, Axle) | (~At_0(Flat, Trunk) & ~At_0(Flat, Ground))")) #first KB.tell(logic.expr("~Remove_0(Flat, Axle) | At_0(Flat, Axle)")) KB.tell(logic.expr("~PutOn_0(Flat, Axle) | At_0(Flat, Ground) ")) KB.tell(logic.expr("~PutOn_0(Flat, Axle) | ~At_0(Flat, Axle) ")) KB.tell(logic.expr("~Remove_0(Flat, Trunk) | At_0(Flat, Trunk)")) #second KB.tell(logic.expr("~Remove_0(Flat, Axle) | At_1(Flat, Ground)")) KB.tell(logic.expr("~PutOn_0(Flat, Axle) | At_1(Flat, Axle)")) KB.tell(logic.expr("~Remove_0(Flat, Trunk) | At_1(Flat, Ground)"))
def test_not_unsafe(self): agent = hw3.WumpusWorldAgent(4) agent.KB.tell(logic.expr('P2_3')) not_unsafe = agent.not_unsafe() self.assertTrue((2, 3) not in not_unsafe) self.assertTrue((1, 1) in not_unsafe)
class successKB(logic.PropKB): AddPosVar, AddNegVar, AddPosConst, AddNegConst, DivPosConst, DivNegConst, CombVar2Pos, CombVar2Neg, CombConst, S1, S2, S3, S4, S5, S6, S7, S8, S9 = logic.expr( 'AddPosVar, AddNegVar, AddPosConst, AddNegConst, DivPosConst, DivNegConst, CombVar2Pos, CombVar2Neg, ' 'CombConst, S1, S2, S3, S4, S5, S6, S7, S8, S9') skills_kb.tell(AddPosVar | "==>" | S1) skills_kb.tell(AddNegVar | "==>" | S2) skills_kb.tell(AddPosConst | "==>" | S3) skills_kb.tell(AddNegConst | "==>" | S4) skills_kb.tell(DivPosConst | "==>" | S5) skills_kb.tell(DivNegConst | "==>" | S6) skills_kb.tell(CombVar2Pos | "==>" | S7) skills_kb.tell(CombVar2Neg | "==>" | S8) skills_kb.tell(CombConst | "==>" | S9)
import logic import itertools KB = logic.PropKB() #initial state KB.tell(logic.expr("At_0(C1, SFO)")) KB.tell(logic.expr("~At_0(C1, JFK)")) KB.tell(logic.expr("At_0(C2, JFK)")) KB.tell(logic.expr("~At_0(C2, SFO)")) KB.tell(logic.expr("At_0(P1, SFO)")) KB.tell(logic.expr("~At_0(P1, JFK)")) KB.tell(logic.expr("At_0(P2, JFK)")) KB.tell(logic.expr("~At_0(P2, SFO)")) KB.tell(logic.expr("~In_0(C1, P1)")) KB.tell(logic.expr("~In_0(C2, P1)")) KB.tell(logic.expr("~In_0(C1, P2)")) KB.tell(logic.expr("~In_0(C2, P2)")) moves = 6 #first preconditions for i in range(0,moves): KB.tell(logic.expr("~Load_"+str(i)+"(C1, JFK, P1) | At_"+str(i)+"(C1, JFK)")) KB.tell(logic.expr("~Load_"+str(i)+"(C1, JFK, P1) | At_"+str(i)+"(P1, JFK)")) KB.tell(logic.expr("~Load_"+str(i)+"(C1, JFK, P2) | At_"+str(i)+"(C1, JFK)"))
import logic KB = logic.PropKB() #initial state KB.tell(logic.expr("At_0(Flat, Axle) & At_0(Spare, Trunk)")) #initial locations imply parts are not elsewhere at the same time KB.tell(logic.expr("~At_0(Flat, Axle) | (~At_0(Flat, Trunk) & ~At_0(Flat, Ground))")) KB.tell(logic.expr("~At_0(Spare, Trunk) | (~At_0(Spare, Axle) & ~At_0(Spare, Ground))")) #first first = ["~Remove_Time(Spare, Trunk) | At_Time(Spare, Trunk)", "~PutOn_Time(Spare, Axle) | At_Time(Spare, Ground)", "~PutOn_Time(Spare, Axle) | ~At_Time(Flat, Axle)", "~Remove_Time(Spare, Axle) | At_Time(Spare, Axle)", "~Remove_Time(Flat, Axle) | At_Time(Flat, Axle)", "~PutOn_Time(Flat, Axle) | At_Time(Flat, Ground)", "~PutOn_Time(Flat, Axle) | ~At_Time(Flat, Axle)", "~Remove_Time(Flat, Trunk) | At_Time(Flat, Trunk)"] for x in range(0, 3): for elem in first: KB.tell(logic.expr(elem.replace("Time", str(x)))) #second second = ["~Remove_Time(Spare, Trunk) | At_Time2(Spare, Ground)", "~PutOn_Time(Spare, Axle) | At_Time2(Spare, Axle)", "~Remove_Time(Spare, Axle) | At_Time2(Spare, Ground)", "~Remove_Time(Flat, Axle) | At_Time2(Flat, Ground)",
def giveFeedback(studentState): feedback_KB.tell(logic.expr(studentState)) if studentState == "CorrectAnswer": feedbackMessage = M7 elif studentState == "~CorrectAnswer": feedbackMessage = M8 if studentState.__contains__("~CorrectAnswer"): if logic.pl_resolution(feedback_KB, logic.expr('M4')): feedbackMessage = M4 elif logic.pl_resolution(feedback_KB, logic.expr('M5')): feedbackMessage = M5 elif logic.pl_resolution(feedback_KB, logic.expr('M6')): feedbackMessage = M6 elif logic.pl_resolution(feedback_KB, logic.expr('M8')): feedbackMessage = M8 elif studentState.__contains__("Correct"): if logic.pl_resolution(feedback_KB, logic.expr('M1')): feedbackMessage = M1 elif logic.pl_resolution(feedback_KB, logic.expr('M2')): feedbackMessage = M2 elif logic.pl_resolution(feedback_KB, logic.expr('M3')): feedbackMessage = M3 elif logic.pl_resolution(feedback_KB, logic.expr('M7')): feedbackMessage = M7 else: if logic.pl_resolution(feedback_KB, logic.expr('M1')): feedbackMessage = M1 elif logic.pl_resolution(feedback_KB, logic.expr('M2')): feedbackMessage = M2 elif logic.pl_resolution(feedback_KB, logic.expr('M3')): feedbackMessage = M3 if logic.pl_resolution(feedback_KB, logic.expr('M4')): feedbackMessage = M4 elif logic.pl_resolution(feedback_KB, logic.expr('M5')): feedbackMessage = M5 elif logic.pl_resolution(feedback_KB, logic.expr('M6')): feedbackMessage = M6 elif logic.pl_resolution(feedback_KB, logic.expr('M7')): feedbackMessage = M7 elif logic.pl_resolution(feedback_KB, logic.expr('M8')): feedbackMessage = M8 #print(feedbackMessage) return feedbackMessage
def execute(cmd, net, timing, kb, tp): """ Carry out the user command. Inputs: cmd: string, user's typed command net: dict, netlist (see parse_netlist) timing: dict, input stimulus (see parse_stimulus) kb: logic.PropKB, knowledge base tp: int, number of discrete time points in which the inputs are stimulated """ assert isinstance(cmd, str) assert isinstance(net, dict) assert isinstance(timing, dict) assert isinstance(kb, logic.PropKB) cmd = cmd.split(' ') if not cmd[0]: return if cmd[0] == 'list': print get_nodes(net, timing) return elif cmd[0] == 'help': help_msg(False) return elif cmd[0] == 'quit': exit() # Note: for probing, I bypass the KB if the node is found in the timing stimulus. It is much faster to do it # this way. elif cmd[0] == 'probe': if len(cmd) != 2: print 'Error: incorrect command, type help to see command format.' return # node[0] = node name # node[1] = time point node = cmd[1].split('_') if node[0] not in get_nodes(net, timing): print 'Error: node', node[0], 'does not exist' return if len(node) == 2: if int(node[1]) not in range(tp): print 'Error: time point out of range (indexing starts at 0).' return print 'Node', node[0], 'at time', node[1] + ':', if node[0] in timing: print timing[node[0]][int(node[1])] else: tr = logic.pl_resolution(kb, logic.expr('_'.join(node))) print '1' if tr else '0' return elif len(node) == 1: if node[0] in timing: print node[0] + ':', timing[node[0]] else: print 'Finding values for node', node[0] + '...' temp = [] for x in range(tp): tr = logic.pl_resolution(kb, logic.expr(node[0] + '_' + str(x))) temp.append(1 if tr else 0) print node[0] + ':', temp return else: print 'Error: incorrect node format.' return elif cmd[0] == 'check': if len(cmd) != 2: print 'Error: incorrect command, type help to see command format.' return print 'Finding value of', cmd[1] + '...' print logic.pl_resolution(kb, logic.expr(cmd[1])) return else: print 'Error: incorrect command, type help to see command format.' return