def giveFeedback(studentState): # Add the rules of feedback system feedbackkb = logic.PropKB() feedbackkb.tell(C | '==>' | (expr('M1') | expr('M2') | expr('M3') | expr('M7'))) feedbackkb.tell(~C | '==>' | (expr('M4') | expr('M5') | expr('M6') | expr('M8'))) feedbackkb.tell(((M & ~C) | (M & CS)) | '==>' | B) feedbackkb.tell((N | IS) | '==>' | expr('M6')) feedbackkb.tell(((IS & C) | (N & CS)) | '==>' | E) feedbackkb.tell(E | '==>' | (expr('M2') | expr('M4'))) feedbackkb.tell(B | '==>' | (expr('M3') | expr('M5'))) feedbackkb.tell(((N & C) | CS) | '==>' | expr('M1')) # Add student state feedbackkb.tell(studentState) # Iteratively Add ~M1, ~M2, .... ~M8 to knowledge base whenever a resolution returns false for i in range(1, 9): msg = 'M' + str(i) if i == 2: feedbackkb.tell(expr('~M4')) if logic.pl_resolution( feedbackkb, expr(msg)): # If entailment happens, return that message return dictionary[i] if i == 2: feedbackkb.retract(expr('~M4')) feedbackkb.tell( expr('~' + msg) ) # Can add to knowledge base since we know can't be this particular msg return None
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 __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 __init__(self): self.KB = logic.PropKB() self.size = 4 cave_size = 4 self.location = (1, 1) self.direction = Direction("down") self.holding = [] self.performance = 0 self.foundGold = False # example of propositional logic #self.KB.tell("B11 <=> (P12|P21)") #self.KB.tell("~B11") # background knowledge about the wumpus world # Every x on the board for x in range(1, cave_size + 1): #Every y on the board for y in range(1, cave_size + 1): #Breeze notBreeze Stench notStench B = "B" + str(x) + "_" + str(y) + " <=> (" notB = "~B" + str(x) + "_" + str(y) + " <=> (" S = "S" + str(x) + "_" + str(y) + " <=> (" notS = "~S" + str(x) + "_" + str(y) + " <=> (" #Lets get the nearby neighbors neighbors = self.get_neighbors(x, y, self.size) for n in neighbors: B += " P" + str(n[0]) + "_" + str(n[1]) + " |" for n in neighbors: notB += " ~P" + str(n[0]) + "_" + str(n[1]) + " &" for n in neighbors: S += " W" + str(n[0]) + "_" + str(n[1]) + " |" for n in neighbors: notS += " ~W" + str(n[0]) + "_" + str(n[1]) + " &" B = B[:-1] + ")" notB = notB[:-1] + ")" S = S[:-1] + ")" notS = notS[:-1] + ")" self.KB.tell(B) self.KB.tell(notB) self.KB.tell(S) self.KB.tell(notS)
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 __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): self.KB = logic.PropKB()
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)
S7 = 'combine two variable terms on a side to get a positive number' # (e.g., combine 3x+6x to make 9x) S8 = 'combine two variable terms on a side to get a negative number' # (e.g., combine 3x-6x to make -9x) S9 = 'combine two constant terms' # (e.g., combine 3-6 to make -3) #add if right side is just one constant or variable #add if left side is just one constant or variable def main(): giveFeedback("IncorrectStreak & CorrectAnswer") solveEquation("3x+2=6+3x") predictSuccess(['S8', 'S9'], '3+5x=8+3') stepThroughProblem("3x+2=8", "add -2", ['S8', 'S9']) feedback_KB = logic.PropKB() class createKB(logic.PropKB): CorrectAnswer, NewSkill, MasteredSkill, CorrectStreak, IncorrectStreak, NeedsEncouragement, IsBored, M1, M2, M3, M4, M5, M6, M7, M8 = logic.expr( 'CorrectAnswer, NewSkill, MasteredSkill, CorrectStreak, IncorrectStreak, NeedsEncouragement, IsBored, M1, M2, M3, M4, M5, M6, M7, M8' ) feedback_KB.tell(CorrectAnswer | '==>' | M1 | M2) feedback_KB.tell(CorrectAnswer | "==>" | (~M4 & ~M5)) feedback_KB.tell(~CorrectAnswer | "==>" | (~M2 & ~M3)) feedback_KB.tell(~CorrectAnswer | '==>' | M4) feedback_KB.tell((MasteredSkill & ~CorrectAnswer) | (MasteredSkill & CorrectStreak) | '==>' | IsBored) feedback_KB.tell(NewSkill | IncorrectStreak | '==>' | M6) feedback_KB.tell((IncorrectStreak & CorrectAnswer) | (NewSkill & CorrectStreak) | '==>' | NeedsEncouragement)
import sys, logic, utils if __name__ == '__main__': input_file = sys.argv[1] fp = open(input_file, "r") lines = fp.readlines() additionalInfo = [] query = [] count = 0 mine_kb = logic.PropKB() for i in range(len(lines)): if '#' not in lines[i]: boardSize = lines[i].rstrip() if '# Additional Info' in lines[i]: count = i break for i in range(count, len(lines)): if '#' not in lines[i]: additionalInfo.append(lines[i].rstrip()) if '# Query Sentences' in lines[i]: count = i break for i in range(count, len(lines)): if '#' not in lines[i]: query.append(lines[i].rstrip()) for i in range(len(additionalInfo)): temp = logic.to_cnf(utils.expr(additionalInfo[i])) mine_kb.tell(temp) x = int(boardSize[0]) y = int(boardSize[2]) for i in range(x): for j in range(y):
def solve_problem(input): police = input['police'] medics = input['medics'] covid_kb = logic.PropKB() tag_list = ['H', 'S', 'U'] if police or medics: return 'Sorry, simulation for teams is not available' row_num = len(input['observations'][0]) col_num = len(input['observations'][0][0]) time_frame = len(input['observations']) clause_list = [] time = 0 for obs in input['observations']: for i in range(row_num): for j in range(col_num): for tag in tag_list: var = "{}{}{}{}".format(tag, i, j, time) if tag == obs[i][j]: covid_kb.tell(utils.expr(var)) elif tag != '?': negate_var = '~' + var covid_kb.tell(utils.expr(negate_var)) clause_list.append( "H{row}{col}{curr} <=> (~S{row}{col}{curr} & ~U{row}{col}{curr})" .format(row=i, col=j, curr=time)) clause_list.append( "S{row}{col}{curr} <=> (~H{row}{col}{curr} & ~U{row}{col}{curr})" .format(row=i, col=j, curr=time)) clause_list.append( "U{row}{col}{curr} <=> (~H{row}{col}{curr} & ~S{row}{col}{curr})" .format(row=i, col=j, curr=time)) if time > 2: clause_list.append( "S{row}{col}{curr} ==> ((S{row}{col}{prev1} & S{row}{col}{prev2} & H{row}{col}{prev3})" "| (S{row}{col}{prev1} & H{row}{col}{prev2}) | (H{row}{col}{prev1}))" .format(row=i, col=j, curr=time, prev1=time - 1, prev2=time - 2, prev3=time - 3)) if 0 < time < time_frame - 2: clause_list.append( "(H{row}{col}{prev} & S{row}{col}{curr}) ==> (S{row}{col}{next1} & S{row}{col}{next2} & H{row}{col}{next3})" .format(row=i, col=j, prev=time - 1, curr=time, next1=time + 1, next2=time + 2, next3=time + 3)) if time < time_frame: clause_list.append( "U{row}{col}{curr} <=> U{row}{col}{next}".format( row=i, col=j, curr=time, next=time + 1)) if i == 0: if j == 0: clause_list.append( "(~S{under}{col}{curr} & ~S{row}{right}{curr} & H{row}{col}{curr}) <=> H{row}{col}{next}" .format(row=i, col=j, curr=time, under=i + 1, right=j + 1, next=time + 1)) elif j == col_num - 1: clause_list.append( "(~S{under}{col}{curr} & ~S{row}{left}{curr} & H{row}{col}{curr}) <=> H{row}{col}{next}" .format(row=i, col=j, curr=time, under=i + 1, left=j - 1, next=time + 1)) else: clause_list.append( "(~S{under}{col}{curr} & ~S{row}{right}{curr} & ~S{row}{left}{curr} & H{row}{col}{curr}) <=> H{row}{col}{next}" .format(row=i, col=j, curr=time, under=i + 1, right=j + 1, left=j - 1, next=time + 1)) elif i == row_num - 1: if j == 0: clause_list.append( "(~S{over}{col}{curr} & ~S{row}{right}{curr} & H{row}{col}{curr}) <=> H{row}{col}{next}" .format(row=i, col=j, curr=time, over=i - 1, right=j + 1, next=time + 1)) elif j == col_num - 1: clause_list.append( "(~S{over}{col}{curr} & ~S{row}{left}{curr} & H{row}{col}{curr}) <=> H{row}{col}{next}" .format(row=i, col=j, curr=time, over=i - 1, left=j - 1, next=time + 1)) else: clause_list.append( "((~S{over}{col}{curr}) & (~S{row}{right}{curr}) & (~S{row}{left}{curr}) & (H{row}{col}{curr})) <=> H{row}{col}{next}" .format(row=i, col=j, curr=time, over=i - 1, right=j + 1, left=j - 1, next=time + 1)) elif j == 0: clause_list.append( "(~S{over}{col}{curr} & ~S{row}{right}{curr} & ~S{under}{col}{curr} & H{row}{col}{curr}) <=> H{row}{col}{next}" .format(row=i, col=j, curr=time, over=i - 1, right=j + 1, under=i + 1, next=time + 1)) elif j == col_num - 1: clause_list.append( "(~S{over}{col}{curr} & ~S{row}{left}{curr} & ~S{under}{col}{curr} & H{row}{col}{curr}) <=> H{row}{col}{next}" .format(row=i, col=j, curr=time, over=i - 1, left=j - 1, under=i + 1, next=time + 1)) else: clause_list.append( "(~S{over}{col}{curr} & ~S{row}{left}{curr} & ~S{row}{right}{curr} & ~S{under}{col}{curr} & H{row}{col}{curr}) <=> H{row}{col}{next}" .format(row=i, col=j, curr=time, over=i - 1, left=j - 1, right=j + 1, under=i + 1, next=time + 1)) time += 1 for clause in clause_list: covid_kb.tell(utils.expr(clause)) answer_dict = {} for query in input['queries']: ((i, j), t, slot) = query if slot == "Q" or slot == "I": answer_dict.update({query: 'F'}) continue alpha = utils.expr("{}{}{}{}".format(slot, i, j, t)) negate_alpha = utils.expr("~{}{}{}{}".format(slot, i, j, t)) if logic.pl_resolution(covid_kb, alpha): answer_dict.update({query: 'T'}) elif logic.pl_resolution(covid_kb, negate_alpha): answer_dict.update({query: 'F'}) else: answer_dict.update({query: '?'}) return answer_dict
class SpaceshipController: "This class is a controller for a spaceship problem." space_kb = logic.PropKB() states = [] state = () move_back = None prev_fit = None 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)) # search.Problem.__init__(self, self.problem) def next_move_to_mission(self, mission, state): actions = self.actions(state) if len(mission[0]) == 3: tmp_min_dist = None for action in actions: if action[0] == "move" and action[1] == mission[1][0]: for cali in state[2]: if cali[0]==mission[1][2][0] and cali[0] == mission[0][2][0]: dist=modified_manhattan_distance(action[3],cali[1]) if tmp_min_dist is None: if self.result(state,action) not in self.states: tmp_min_dist = (dist[0],action) else: tmp_min_dist = (2*(self.state[0]*self.state[0]), action) if dist[0] < tmp_min_dist[0]: if self.result(state,action) not in self.states: tmp_min_dist = (dist[0],action) return tmp_min_dist[1] if len(mission[0]) == 2: tmp_min_dist = None for action in actions: if action[0] == "move" and action[1] == mission[1][0]: dist=modified_manhattan_distance(action[3],mission[0][1][0]) if tmp_min_dist is None: if self.result(state,action) not in self.states: tmp_min_dist = (dist[0],action) else:tmp_min_dist = ((self.state[0]*self.state[0])*2, action) else: if dist[0] < tmp_min_dist[0]: if self.result(state,action) not in self.states: tmp_min_dist = (dist[0],action) #print (tmp_min_dist[0]) return tmp_min_dist[1] def get_next_action(self, observation): # TODO : COMPLETE BY STUDENTS # get observation for the current state and return next action to apply (and None if no action is applicable) #self.space_kb.tell() cleared = False #print(self.state) for prev_tar in self.problem[3]: for tar in self.state[3]: if prev_tar[0] == tar[0]: if len(prev_tar[1]) != len(tar[1]): self.states=[] self.prev_fit = None cleared=True if cleared: print("CLEARED") self.problem=self.state # Take a ship and look for the closest target+calibration actions = self.actions(self.state) #print(actions) next_action = None next_target = None ship_missions=[] for ship in self.state[1]: for action in actions: if observation.get(ship[0]) != -1: if observation.get(ship[0]) == 1: pos_str = 'P' + str(ship[1]) self.space_kb.tell(~logic.expr(pos_str)) elif observation.get(ship[0])==0: 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])) self.space_kb.tell(~logic.expr(pos_str)) pos_str = 'P' + str((ship[1][0]-1, ship[1][1], ship[1][2])) self.space_kb.tell(~logic.expr(pos_str)) pos_str = 'P' + str((ship[1][0], ship[1][1]+1, ship[1][2])) self.space_kb.tell(~logic.expr(pos_str)) pos_str = 'P' + str((ship[1][0], ship[1][1]-1, ship[1][2])) self.space_kb.tell(~logic.expr(pos_str)) pos_str = 'P' + str((ship[1][0], ship[1][1], ship[1][2]+1)) self.space_kb.tell(~logic.expr(pos_str)) pos_str = 'P' + str((ship[1][0], ship[1][1], ship[1][2]-1)) self.space_kb.tell(~logic.expr(pos_str)) if action[0] == "use" and action [1] == ship[0]: self.state = self.result(self.state, action) self.states.append(self.state) return action if action[0] == "calibrate" and action [1] == ship[0] and ship[2][1]==False: self.state = self.result(self.state, action) self.states.append(self.state) return action if ship[2][0] is None: if action[0] == "turn_on" and action[1] == ship[0]: need_for_weapon = False for tar in self.state[3]: if action[2] in tar[1]: need_for_weapon = True if need_for_weapon: self.state = self.result(self.state, action) self.states.append(self.state) return action fitness = -1 tmp_min_fit=None if observation.get(ship[0]) != -1: ntarget = best_next_target(ship, self.state) if ntarget != (): fitness = ntarget[0]+observation.get(ship[0])+1 if tmp_min_fit is None: tmp_min_fit = fitness next_target = ntarget if 0 < fitness < tmp_min_fit: tmp_min_fit = fitness next_target = ntarget if next_target != (): ship_missions.append((next_target,ship)) tmp_best = None for mission in ship_missions: if tmp_best is None: tmp_best = mission if 0<mission[0][0]<tmp_best[0][0]: tmp_best = mission '''if self.prev_fit is None: print (mission[0][0]) self.prev_fit = mission[0][0] elif self.prev_fit<mission[0][0]: self.prev_fit=None self.state = self.result(self.state, self.move_back) return self.move_back else: self.prev_fit=mission[0][0]''' if mission[1][2][0] not in mission[0][1][1]: next_action = ("turn_on", mission[1][0], mission[0][2][0]) self.state=self.result(self.state,next_action) return next_action next_action = self.next_move_to_mission(mission, self.state) if next_action is None: return self.move_back allow=logic.dpll_satisfiable(logic.to_cnf(logic.associate('&',self.space_kb.clauses + [logic.expr('P'+str(next_action[3]))]))) #print(allow) tmp_state = self.result(self.state, next_action) self.states.append(tmp_state) while allow != False: print('Achtung Laser') print(allow) next_action = self.next_move_to_mission(mission, self.state) tmp_state = self.result(self.state, next_action) self.states.append(tmp_state) if len(self.states)>6: self.states.clear() allow = logic.dpll_satisfiable( logic.to_cnf(logic.associate('&', self.space_kb.clauses + [logic.expr('P' + str(next_action[3]))]))) #print(allow) self.state=tmp_state self.move_back = (next_action[0], next_action[1], next_action[3],next_action[2]) return next_action @staticmethod def check_who_blocks(state, tmp_lst_min, tmp_lst_cali, all_occupied_pos): cali = [] target = [] tmp_block = [] for i in range(0,6): tmp_block.append(()) for pos in all_occupied_pos: if pos[1] == state[1] and pos[2] == state[2] and pos[0] != state[0]: if state[0]<pos[0]: if tmp_block[0]==(): tmp_block[0]=pos elif pos[0]<tmp_block[0][0]: tmp_block[0]=pos if state[0]>pos[0]: if tmp_block[1] == (): tmp_block[1] = pos elif pos[0]<tmp_block[1][0]: tmp_block[1] = pos if pos[0] == state[0] and pos[2] == state[2] and pos[1] != state[1]: if state[1] < pos[1]: if tmp_block[2] == (): tmp_block[2] = pos elif pos[1]<tmp_block[2][1]: tmp_block[2] = pos if state[1] > pos[1]: if tmp_block[3] == (): tmp_block[3] = pos elif pos[1]<tmp_block[3][1]: tmp_block[3] = pos if pos[0] == state[0] and pos[1] == state[1] and pos[2] != state[2]: if state[2] < pos[2]: if tmp_block[4] == (): tmp_block[4] = pos elif pos[2]<tmp_block[4][2]: tmp_block[4] = pos if state[2] > pos[2]: if tmp_block[5] == (): tmp_block[5] = pos elif pos[2]>tmp_block[5][2]: tmp_block[5] = pos tmp_block_lst=tuple(tmp_block) for i in range(0, 6): if tmp_lst_cali[i] == () or tmp_lst_min[i] == (): if tmp_lst_min[i] == (): if tmp_lst_cali[i] != (): if tmp_block_lst[i] == () or tmp_block_lst[i] == tmp_lst_cali[i][1]: cali.append(tmp_lst_cali[i]) if tmp_lst_cali[i] == (): if tmp_lst_min[i] != (): if tmp_block_lst[i] == () or tmp_block_lst[i] == tmp_lst_min[i][0]: target.append(tmp_lst_min[i]) elif tmp_lst_cali[i] == () and tmp_lst_min[i] == (): pass else: tmp_res_min = math.fabs(state[0] - tmp_lst_min[i][0][0]) + math.fabs( state[1] - tmp_lst_min[i][0][1]) + math.fabs(state[2] - tmp_lst_min[i][0][2]) tmp_res_cali = math.fabs(state[0] - tmp_lst_cali[i][1][0]) + math.fabs( state[1] - tmp_lst_cali[i][1][1]) + math.fabs(state[2] - tmp_lst_cali[i][1][2]) tmp_res_block = math.fabs(state[0] - tmp_block_lst[i][0])+math.fabs( state[1] - tmp_block_lst[i][1])+math.fabs(state[2] - tmp_block_lst[i][2]) if tmp_res_min < tmp_res_cali and tmp_res_min<=tmp_res_block: target.append(tmp_lst_min[i]) elif tmp_res_cali<tmp_res_min and tmp_res_cali<=tmp_res_block: cali.append(tmp_lst_cali[i]) return target, cali def actions(self, state): """Return the actions that can be executed in the given state. The result would typically be a tuple, but if there are many actions, consider yielding them one at a time in an iterator, rather than building them all at once.""" dim = state[0] allowed_lst = [] # Move section for ship in state[1]: if ship[1][0] != dim - 1 and (int(ship[1][0]) + 1, ship[1][1], ship[1][2]) not in state[4]: allowed_lst.append(("move", ship[0], ship[1], (int(ship[1][0]) + 1, ship[1][1], ship[1][2]))) if ship[1][1] != dim - 1 and (ship[1][0], int(ship[1][1]) + 1, ship[1][2]) not in state[4]: allowed_lst.append(("move", ship[0], ship[1], (ship[1][0], int(ship[1][1]) + 1, ship[1][2]))) if ship[1][2] != dim - 1 and (ship[1][0], ship[1][1], int(ship[1][2]) + 1) not in state[4]: allowed_lst.append(("move", ship[0], ship[1], (ship[1][0], ship[1][1], int(ship[1][2]) + 1))) if ship[1][0] != 0 and (int(ship[1][0]) - 1, ship[1][1], ship[1][2]) not in state[4]: allowed_lst.append(("move", ship[0], ship[1], (int(ship[1][0]) - 1, ship[1][1], ship[1][2]))) if ship[1][1] != 0 and (ship[1][0], int(ship[1][1]) - 1, ship[1][2]) not in state[4]: allowed_lst.append(("move", ship[0], ship[1], (ship[1][0], int(ship[1][1]) - 1, ship[1][2]))) if ship[1][2] != 0 and (ship[1][0], ship[1][1], int(ship[1][2]) - 1) not in state[4]: allowed_lst.append(("move", ship[0], ship[1], (ship[1][0], ship[1][1], int(ship[1][2]) - 1))) # Turn on for ship in state[1]: for inst in ship[3]: if inst != ship[2][0]: allowed_lst.append(("turn_on", ship[0], inst)) # Use & Cali for ship in state[1]: tmp_lst_min = [] tmp_lst_cal = [] # Maximum values for i in range(0, 6): tmp_lst_min.append(()) tmp_lst_cal.append(()) # if ship[2][1]: # Check if calibrated for target in state[3]: # Check for every target if closer to the state self.check_for_use(1, 2, 0, 0, 1, ship[1], target, tmp_lst_min) self.check_for_use(0, 2, 1, 2, 3, ship[1], target, tmp_lst_min) self.check_for_use(1, 0, 2, 4, 5, ship[1], target, tmp_lst_min) for cali in state[2]: self.check_for_cali(1, 2, 0, 0, 1, ship[1], cali, tmp_lst_cal) self.check_for_cali(0, 2, 1, 2, 3, ship[1], cali, tmp_lst_cal) self.check_for_cali(1, 0, 2, 4, 5, ship[1], cali, tmp_lst_cal) target, cali = self.check_who_blocks(ship[1], tmp_lst_min, tmp_lst_cal, state[4]) if ship[2][1]: # If the weapon is calibrated for item in target: if ship[2][0] in item[1] and ship[2][1]: allowed_lst.append(("use", ship[0], ship[2][0], item[0])) else: for item in cali: if ship[2][0] == item[0]: allowed_lst.append(("calibrate", ship[0], ship[2][0], item[1])) return tuple(allowed_lst) def result(self, state, action): """Return the state that results from executing the given action in the given state. The action must be one of self.actions(state).""" if action[0] == "move": all_ships = [] for ship in state[1]: if ship[1] == action[2]: new_ship = (ship[0], action[3], ship[2], ship[3]) all_ships.append(new_ship) else: all_ships.append(ship) tmp = list(state[4]) tmp.remove(action[2]) tmp.append(action[3]) state = (state[0], tuple(all_ships), state[2], state[3], tuple(tmp)) return state elif action[0] == "turn_on": all_ships = [] for ship in state[1]: if ship[0] == action[1]: new_ship = (ship[0], ship[1], (action[2], False), ship[3]) all_ships.append(new_ship) else: all_ships.append(ship) state = (state[0], tuple(all_ships), state[2], state[3], state[4]) return state elif action[0] == "use": all_targets = [] for target in state[3]: if target[0] == action[3]: tmp = list(target[1]) tmp.remove(action[2]) modified_target = (target[0], tuple(tmp)) all_targets.append(modified_target) else: all_targets.append(target) state = (state[0], state[1], state[2], tuple(all_targets), state[4]) return state elif action[0] == "calibrate": all_ships = [] for ship in state[1]: if ship[0] == action[1]: current_instrument = ship[2][0] new_ship = (ship[0], ship[1], (current_instrument, True), ship[3]) all_ships.append(new_ship) else: all_ships.append(ship) state = (state[0], tuple(all_ships), state[2], state[3], state[4]) return state @staticmethod def make_inst_on_ships(locations, inst_on_ships): tmp_lst = [] for k, v in locations.items(): for ship, inst in inst_on_ships.items(): if ship == k: tmp_lst.append((k, v, (None, False), inst)) return tuple(tmp_lst) @staticmethod def check_for_use(a, b, c, d, e, state, target, tmp_lst_min): if state[a] == target[0][a] and state[b] == target[0][b]: if state[c] < target[0][c]: if tmp_lst_min[d] == (): tmp_lst_min[d] = target elif tmp_lst_min[d][0][c] < target[0][c]: tmp_lst_min[d] = target elif state[c] > target[0][c]: if tmp_lst_min[e] == (): tmp_lst_min[e] = target elif tmp_lst_min[e][0][c] > target[0][c]: tmp_lst_min[e] = target # TODO: Check if < and > are set correct @staticmethod def check_for_cali(fixed_axis, second_fixed_axis, on_line_of_this_axis, first_dir, second_dir, state, cali, tmp_lst_cal): if state[fixed_axis] == cali[1][fixed_axis] and state[second_fixed_axis] == cali[1][second_fixed_axis]: if state[on_line_of_this_axis] < cali[1][on_line_of_this_axis]: if tmp_lst_cal[first_dir] == (): tmp_lst_cal[first_dir] = cali elif tmp_lst_cal[first_dir][1][on_line_of_this_axis] < cali[1][on_line_of_this_axis]: tmp_lst_cal[first_dir] = cali elif state[on_line_of_this_axis] > cali[1][on_line_of_this_axis]: if tmp_lst_cal[second_dir] == (): tmp_lst_cal[second_dir] = cali elif tmp_lst_cal[second_dir][1][on_line_of_this_axis] > cali[1][on_line_of_this_axis]: tmp_lst_cal[second_dir] = cali
def main(): cards = [['ProfessorPlum', 'MissScarlet', 'MissWhite'], ['Ballroom', 'Conservatory'], ['Knife', 'Wrench']] players = ['P1', 'P2'] sentences = [] # 'Player(P1)', # 'Player(P2)', # 'Player(NoOne)', # 'Player(x) ==> (Eq(x,P1) | Eq(x,P2) | Eq(x,NoOne))', # 'Card(c) ==> (Player(O(c)) & HasCard(O(c), c))', # '(HasCard(p,c) & HasCard(q,c)) ==> Eq(p,q)', # 'Eq(x,x)', # 'Eq(x,y) ==> Eq(y,x)', # '(Eq(x,y) & Eq(y,z)) ==> Eq(x,z)', # 'Eq(x,y) ==> Eq(O(x), O(y))', # '(Eq(w,y) & Eq(x,z)) ==> (HasCard(w,x) <=> HasCard(y,z))', # 'Eq(x,y) ==> (Player(x) <=> Player(y))'] #sentences = for group in cards: # Someone and only one person owns each card. for card in group: sentence = "" for player in players: sentence += 'HasCard(' + player + ',' + card + ') | ' sentence += 'HasCard(NoOne,' + card + ')' sentences.append(sentence) for player in (players + ['NoOne']): sentence = 'HasCard(' + player + ',' + card + ') ==> (' clauses = [] for otherplayer in (players + ['NoOne']): if (otherplayer != player): clauses.append('~HasCard(' + otherplayer + ',' + card + ')') sentence += ' & '.join(clauses) + ')' sentences.append(sentence) # In every category, NoOne owns one and only one card clauses = [] for card in group: clauses.append('HasCard(NoOne,' + card + ')') sentence = ' | '.join(clauses) sentences.append(sentence) for card in group: sentence = 'HasCard(NoOne,' + card + ') ==> (' clauses = [] for othercard in group: if (othercard != card): clauses.append('~HasCard(NoOne,' + othercard + ')') sentence += ' & '.join(clauses) + ')' sentences.append(sentence) testSentences = ['HasCard(P1,ProfessorPlum)', 'HasCard(P2,MissScarlet)'] # '~Eq(O(ProfessorPlum), P1)', # '~Eq(O(ProfessorPlum), P2)'] # kb = logic.FolKB() kb = logic.PropKB() for sentence in sentences: kb.tell(expr(sentence)) for sentence in testSentences: kb.tell(expr(sentence))