def main(): s = input("please enter a string of a's and b's: ") strm = streamreader.StreamReader(io.StringIO(s)) q0 = state.State(0) q1 = state.State(1) q2 = state.State(2, True) #can be any value except None classes = {"a": frozenset("a"), "b": frozenset("b")} q0.setClasses(classes) q1.setClasses(classes) q2.setClasses(classes) q0.addTransition("a", 2) q0.addTransition("b", 1) q1.addTransition("a", 2) q1.addTransition("b", 1) q2.addTransition("b", 2) states = {0: q0, 1: q1, 2: q2} dfa = FiniteStateMachine(states, 0, classes) dfa.accepts(strm)
def main(): q0 = state.State(0) q1 = state.State(1,1) q2 = state.State(2) classes = {"zero":frozenset("0"), "one":frozenset("1")} q0.addTransition("zero", 0) q0.addTransition("one", 1) q1.addTransition("zero", 0) q1.addTransition("one",2) q2.addTransition("zero",2) q2.addTransition("one",1) dfa = FiniteStateMachine({0:q0, 1:q1, 2:q2}, 0, classes) done = False while not done: s = input("Please enter a string of zeros and ones: ").strip() if len(s) == 0: done = True else: strm = streamreader.StreamReader(io.StringIO(s)) if dfa.accepts(strm): print("The string is accepted by the finite state machine.") else: print("The string is not accepted.") print("Program Completed.")
def add_keyword(self, keywords, sid): """Adds the keyword in the tree""" ## for key in keywords.split(' '): j = 0 current = self.root key = keywords.upper() ## start = 0 while j < len(key): char = key[j] j = j + 1 child = current.get_transition(char) if child != None: current = child else: self.newstate = self.newstate + 1 node = state.State(self.newstate, char) current.transition_List.append(node) current = node while j < len(key): self.newstate = self.newstate + 1 node2 = state.State(self.newstate, key[j]) current.transition_List.append(node2) current = node2 j = j + 1 break tupl = key, sid current.string_id = sid current.output_set.add(tupl)
def a_star_search(stateInitial): frontier = PriorityQueue() #use priority queue as frontier for a-star explored = set() #use set for explored states initstate = state.State(stateInitial,0,None,None,True) frontier.put(initstate) explored.add(initstate) nodesExpanded = 0 max_search_depth = 0 moves = ["Up","Down","Left","Right"] #moves to be referenced later when exploring children while(frontier): currentS = frontier.get() #get from priority queue max_search_depth = max(max_search_depth,currentS.searchDepth) if(currentS.solved): path_to_goal = [] while currentS.path[0]: path_to_goal.insert(0,currentS.path[1]) currentS.path = currentS.path[0].path ###############STATISTIC OUTPUT###################### sys.stdout = open('output.txt',"w") print("path_to_goal:",path_to_goal) print("cost_of_path:",currentS.searchDepth) print("nodes_expanded:",nodesExpanded) print("search_depth:",currentS.searchDepth) print("max_search_depth:",max_search_depth) sys.stdout.close() ##################################################### return nodesExpanded += 1 #increment nodes expanded for i in range(4): #loop through 4 numbers representing each possible direction nextChild = currentS.children[i] if(nextChild): #same process as all other searches nextState = state.State(nextChild,currentS.searchDepth+1,currentS,moves[i],True) if(not(nextState in explored)): frontier.put(nextState) explored.add(nextState)
def observe_clean_app(dev, app, prop): import watchdog wd = watchdog.Watchdog(100000) import observer ob = observer.Observer("../err/") ob.set_app(app) ob.load("../model/", "../guis/", "../guis-extra/", config.extra_screens, config.extra_element_scrs) import testlib tlib = testlib.collect_pieces("../tlib/") tlib.set_app(app) tlib.assume_reached('signin', 'login', 'main') tlib.assume_reached('welcome', 'skip sign in / sign up', 'main') ob.tlib = tlib import microtest tlib.add_test(microtest.init_test(appdb.get_app(app))) init = tlib.find_test('meta', 'start app') logger.info("start once first") init.attempt(dev, ob, state.State(), tlib, None) st = state.State({'loggedin': '1', prop: '1'}) ob.update_state(dev, st) tlib.mark_succ(init, state.init_state, st) most_reached = tlib.get_reached(init) logger.info("start -> %s", most_reached) smgr = StateMgr(tlib, None, dev, ob, wd) logger.info("ready") ret = smgr.observe_and_clean(prop, st) if ret: logger.info("prop %s is clean now" % prop) else: logger.info("observe/clean error")
def breadth_first_search(stateInitial): frontier = collections.deque() #use deque as the frontier explored = set() #set for all explored states initstate = state.State(stateInitial,0,None,None) frontier.append(initstate) explored.add(initstate) nodesExpanded = 0 max_search_depth = 0 moves = ["Up","Down","Left","Right"] #moves to be referenced later when exploring children while(frontier): currentS = frontier.popleft() #pop left of deque to make it FIFO if(currentS.solved): #solution check path_to_goal = [] #initiate path array while currentS.path[0]: #trace back parent nodes until null is reached adding each move at each point path_to_goal.insert(0,currentS.path[1]) currentS.path = currentS.path[0].path ###############STATISTIC OUTPUT###################### sys.stdout = open('output.txt',"w") print("path_to_goal:",path_to_goal) print("cost_of_path:",currentS.searchDepth) print("nodes_expanded:",nodesExpanded) print("search_depth:",currentS.searchDepth) print("max_search_depth:",max_search_depth) sys.stdout.close() ##################################################### return nodesExpanded += 1 #increment nodes expanded for i in range(4): #loop through 4 numbers representing each possible direction nextChild = currentS.children[i] if(nextChild): #if next state exists, generate it and add to frontier and explored lists nextState = state.State(nextChild,currentS.searchDepth+1,currentS,moves[i]) max_search_depth = max(max_search_depth,nextState.searchDepth) if(not(nextState in explored)): #might cause inefficiency since state is generated before it is checked for membership in frontier but didn't affect performance in test cases frontier.append(nextState) explored.add(nextState)
def depth_first_search(stateInitial): frontier = collections.deque() #use deque as a frontier explored = set() #set for all explored states initstate = state.State(stateInitial,0,None,None) frontier.append(initstate) explored.add(initstate) nodesExpanded = 0 max_search_depth = 0 moves = ["Up","Down","Left","Right"] #moves to be referenced later when exploring children while(frontier): currentS = frontier.pop() #pop from right side to make it FILO max_search_depth = max(max_search_depth,currentS.searchDepth) if(currentS.solved): path_to_goal = [] while currentS.path[0]: path_to_goal.insert(0,currentS.path[1]) currentS.path = currentS.path[0].path ###############STATISTIC OUTPUT###################### sys.stdout = open('output.txt',"w") print("path_to_goal:",path_to_goal) print("cost_of_path:",currentS.searchDepth) print("nodes_expanded:",nodesExpanded) print("search_depth:",currentS.searchDepth) print("max_search_depth:",max_search_depth) sys.stdout.close() ##################################################### return nodesExpanded += 1 #increment nodes expanded for i in range(4): #loop through 4 numbers representing each possible direction nextChild = currentS.children[3-i] #index (3-i) to go through list in reverse so stack retrives in UDLR order if(nextChild): #if next state exists, generate it and add to frontier and explored lists nextState = state.State(nextChild,currentS.searchDepth+1,currentS,moves[3-i]) if(not(nextState in explored)): frontier.append(nextState) explored.add(nextState)
def draw(): curr_state = state.State() ix, iy, cpy = COORD(curr_state) line = pygame.Surface((10, 80)) line.fill(BLACK) circle = pygame.Surface((10, 10)) circle.fill((0, 0, 0)) pygame.draw.circle(circle, RED, (5, 5), 5, 0) circle.set_colorkey((0, 0, 0)) rects = {'line': line.get_rect(), 'circle': circle.get_rect()} #24 rects['line'].centery = cpy rects['line'].left = PADDLE_YX rects['circle'].centerx = ix rects['circle'].centery = iy while True: for event in pygame.event.get(): if event.type == pygame.locals.QUIT: pygame.quit() sys.exit() curr_state = TrainSmall.get_agent_state(curr_state) if curr_state.reward == -1: curr_state = state.State() c_bx, c_by, c_pyr = COORD(curr_state) for rect in rects: if rect == 'line': rects['line'].centery = c_pyr rects['line'].left = PADDLE_YX elif rect == 'circle': rects['circle'].centerx = c_bx rects['circle'].centery = c_by window.fill(WHITE) window.blit(line, rects['line']) window.blit(circle, rects['circle']) pygame.time.Clock().tick(FPS) pygame.display.update()
def main(): q0 = state.State(0, 1) q1 = state.State(1, 1) q2 = state.State(2, 1) q3 = state.State(3, 1) q4 = state.State(4) classes = {"a": frozenset("a"), "b": frozenset("b")} q0.addTransition("a", 1) q0.addTransition("b", 0) q1.addTransition("a", 2) q1.addTransition("b", 1) q2.addTransition("a", 3) q2.addTransition("b", 2) q3.addTransition("a", 4) q3.addTransition("b", 3) q4.addTransition("a", 4) q4.addTransition("b", 4) dfa = FiniteStateMachine({0: q0, 1: q1, 2: q2, 3: q3, 4: q4}, 0, classes) # You must complete the main function here but you can # create a stream over a string s by writing # strm = streamreader.StreamReader(io.StringIO(s)) s = raw_input("Please enter a string of a's and b's: ") # apparently I'm using python 2.7 instead of 3.x, so I need to use raw_input() instead of input() # REMEMBER TO CHANGE AFTER UPDATING PYTHON!! while s != "": strm = streamreader.StreamReader(io.StringIO(s)) print(dfa.accepts(strm)) s = raw_input("Please enter a string of a's and b's: ")
def setUp(self): # Players: self.p0 = state.State() self.p1 = state.State() self.p0.opponent = self.p1 self.p1.opponent = self.p0 self.cmd = command.Command(self.p0)
def main(): q1 = state.State(1) q2 = state.State(2) q3 = state.State(3) q4 = state.State(4) q5 = state.State(5) q6 = state.State(6) q7 = state.State(7, True) q8 = state.State(8, True) q9 = state.State(9, True) q10 = state.State(10) classes = {} classes["a"] = set(["a"]) classes["b"] = set(["b"]) q1.addTransition("a", 2) q1.addTransition("b", 1) q2.addTransition("a", 3) q2.addTransition("b", 1) q3.addTransition("a", 4) q3.addTransition("b", 1) q4.addTransition("a", 5) q4.addTransition("b", 4) q5.addTransition("a", 6) q5.addTransition("b", 4) q6.addTransition("a", 7) q6.addTransition("b", 4) q7.addTransition("a", 10) q7.addTransition("b", 8) q8.addTransition("a", 9) q8.addTransition("b", 8) q9.addTransition("a", 7) q9.addTransition("b", 8) q10.addTransition("a", 10) q10.addTransition("b", 10) s = input("Please enter a string of a's and b's:") while s: dfa = FiniteStateMachine( { 1: q1, 2: q2, 3: q3, 4: q4, 5: q5, 6: q6, 7: q7, 8: q8, 9: q9, 10: q10 }, 1, classes) strm = streamreader.StreamReader(io.StringIO(s)) dfa.accepts(strm) s = input("Please enter a string of a's and b's:") print('Program Completed.')
def __call__(self, g, s, indexList, i): sum = 0 for j in indexList: sum += s[j].x if s[i].x == 0 and sum >= self.kup: return state.State(1, 2) elif s[i].x == 1 and sum < self.kdown: return state.State(0, 2) else: return s[i]
def majority(g, s, indexList, i): """Boolean parity function (sum modulo 2)""" sum = 0 for k in indexList: sum += s[k].x if sum >= 0.5 * len(indexList): return state.State(1, 2) else: return state.State(0, 2)
def main(): s = input("please enter a string of 0's and 1's:") strm = streamreader.StreamReader(io.StringIO(s)) q0 = state.State(0, True) q1 = state.State(1, True) q2 = state.State(2) classes = {} classes["0"] = set(["0"]) classes["1"] = set(["1"]) q0.addTransition("0",1) q0.addTransition("1",2) q1.addTransition("0",1) q1.addTransition("1",2) q2.addTransition("0",2) q2.addTransition("1",0) q0.setClasses(classes) q1.setClasses(classes) q2.setClasses(classes) accepted = False states = {0:q0, 1:q1, 2:q2} stateId = 0 c = strm.readChar() while not strm.eof(): print(c, stateId) # process character q = states[stateId] stateId = states[stateId].onGoTo(c) #state.NoTransition? Handle this? if stateId == state.NoTransition: print("rejected") return c = strm.readChar() if states[stateId].isAccepting(): print("accepted") else: print("rejected")
def main(): q0 = state.State(0, True) q1 = state.State(1, True) q2 = state.State(2, True) q3 = state.State(3, True) q4 = state.State(4) classes = {} classes["a"] = set(["a"]) classes["b"] = set(["b"]) q0.addTransition("a", 1) q0.addTransition("b", 0) q1.addTransition("a", 2) q1.addTransition("b", 1) q2.addTransition("a", 3) q2.addTransition("b", 2) q3.addTransition("a", 4) q3.addTransition("b", 3) q4.addTransition("a", 4) q4.addTransition("b", 4) q0.setClasses(classes) q1.setClasses(classes) q2.setClasses(classes) q3.setClasses(classes) q4.setClasses(classes) states = {0: q0, 1: q1, 2: q2, 3: q3, 4: q4 } dfa = FiniteStateMachine(states, 0, classes) while True: s = input("Please enter a string of a's and b's: ") if len(s) > 0: strm = streamreader.StreamReader(io.StringIO(s)) if dfa.accepts(strm): print("That string is accepted by this finite state machine.") else: print("That string is not accepted.") else: print("Program Completed.") break
def EFL1(self, g, s, indexList, i): i = indexList if (s[i[0]].x == 0): image = 1 else: image = 0 return state.State(int(image), 2)
def __init__(self, trade_pair, time_frame, size=500): self.trade_pair = trade_pair self.size = size self.state = state.State(trade_pair, time_frame) self.history = candlestick.CandleHistory(trade_pair, time_frame, size) self.stgy1 = strategy.StrategyOne() self.stgy2 = strategy.StrategyTwo()
def search(self): timestamp = 1 self.initial_state.f = self.get_heuristic(self.initial_state) + self.initial_state.cost_so_far self.frontier.append(self.initial_state) while len(self.frontier): state_closed = self.frontier.pop() self.visited.append(state_closed) # self.visited_coor.append((state_closed.x,state_closed.y)) if self.env.is_goal(state_closed): # self.frontier.sort(key=lambda state:(state.f,state.timestamp),reverse=True) return state_closed, self.frontier, self.visited available_moves = self.env.available_moves(state_closed) moves = state_closed.moves_so_far for i in available_moves: move, (x, y) = available_moves[i] timestamp += 1 new_state = state.State(x, y) if new_state not in self.visited: moves.append(move) new_state.moves_so_far = copy.deepcopy(moves) new_state.cost_so_far = self.get_cost(state_closed, new_state) new_state.f = self.get_heuristic(new_state) + new_state.cost_so_far new_state.timestamp = timestamp if new_state in self.frontier: frontier_index = self.frontier.index(new_state) if new_state.f < self.frontier[frontier_index].f: self.frontier.pop(frontier_index) # remove the state with larger f self.frontier.append(new_state) # add the new one elif new_state not in self.frontier: if new_state.cost_so_far <= self.env.energy_budget: self.frontier.append(new_state) moves.pop() self.frontier.sort(key=lambda state:(state.f, state.timestamp), reverse=True) # sort by f, timestamp return [], self.frontier, self.visited
def prepare_input_state(self, curr_state): input_state = state.State() if curr_state is not None: for key in config.cleanup_dep_keys: if util.unequal(curr_state.get(key, ''), ''): input_state.set(key, curr_state.get(key)) return input_state
def run_console(): if len(sys.argv) > 1: serial = sys.argv[1] else: serial = None dev = device.create_device(serial) if dev.kind == 'adb': appdb.collect_apps("../apks/") elif dev.kind == 'web': appdb.load_urls("../etc/urls.txt") ob = observer.Observer("../err/") init_state = state.State() env = environ.Environment() tlib = testlib.collect_pieces("../tlib/") tlib.assume_reached('signin', 'login', 'main') tlib.assume_reached('welcome', 'skip sign in / sign up', 'main') ob.tlib = tlib init_env = {'dev': dev, 'ob': ob, 'state': init_state, 'env': env, 'tlib': tlib} if len(sys.argv) > 2: app = sys.argv[2] load_app(app, ob, tlib, init_env) cons = console.Console(handle_console_cmd, prompt="op> ", after_cb=update_prompt, init_env=init_env) cons.start() cons.wait()
def cleanup_from_full_synth(self, prop, init_state, curr_state, try_count, lead): target_state = state.State({prop: ''}) self.add_dep_keys(curr_state, target_state) methods = self.tlib.query_cache(init_state, target_state) if len(methods) < try_count: methods += self.tlib.synthesis(target_state, init_state, try_count - len(methods)) for method in methods: logger.info("way to cleanup %s: %s", prop, method) self.watchdog.kick() curr_state = self.observe() if not lead.replay(self.dev, curr_state, self.observer, self.tlib): continue if not method.replay(self.dev, curr_state, self.observer, self.tlib): logger.info("cleanup of %s error!", prop) else: logger.info("== prop %s cleaned ==", prop) curr_state.set(prop, '') self.tlib.record_route_succ(init_state, target_state, method) return True logger.info("== no method works! ==") return False
def get_target(s_real, discount, max_reward=[999999, 0], depth=0): """returns the optimal target given a state""" if depth == depth_to_check: return 1, s_real.reward() p = policy.Policy() for i in range(8): s = state.State( p, ev_profile=s_real.EV_PROFILE, time=s_real.time, house_demand=s_real.house_demand, ev_at_home=s_real.ev_at_home, ev_charge=s_real.ev_charge, bat_charge=s_real.bat_charge, flexi_charge=s_real.flexi_charge, ev_capacity=s_real.EV_CAPACITY, battery_capacity=s_real.BATTERY_CAPACITY, variable_load_power_req=s_real.VARIABLE_LOAD_POWER_REQ, solar_generation_capacity=s_real.SOLAR_GENERATION_CAPACITY, solar_generated=s_real.solar_generated) p.manual_update(i) s.update(p) reward = s.reward() + get_target(s, discount, max_reward, depth + 1)[1] * discount if reward < max_reward[0]: max_reward = [reward, i] result = [0 for i in range(8)] result[max_reward[1]] = 1 return result, max_reward[0]
def newState(): ''' Add a new state to the map of stateIds to states in the state map. Return the new state id.''' new_State = state.State(self.numStates) self.numStates += 1 return new_State.getId()
def newState(): # Add a new state to the map of stateIds to states in the state map. # Return the new state id. newState = state.State(self.numStates) self.states[self.numStates] = newState self.numStates += 1 return self.numStates - 1
def __init__(self): self.fixated_keys = ["cup", "one_handle", "two_handles", "lid", "clear_liquid", "light_", "brown_liquid", "carton", "open", "closed", "packet", "foil", "paper", "torn", "untorn", "spoon", "teabag", "sugar"] self.held_keys = self.fixated_keys + ["nothing"] # Prefixes to avoid having to worry about duplicate keys self.fixated_keys = ['f_' + key for key in self.fixated_keys] self.held_keys = ['h_' + key for key in self.held_keys] self.fixate_action_keys = ["fixate_cup", "fixate_teabag", "fixate_coffee_pack", "fixate_spoon", "fixate_carton", "fixate_sugar", "fixate_sugar_bowl"] self.do_action_keys = ["pick_up", "put_down", "pour", "peel_open", "tear_open", "pull_open", "pull_off", "scoop", "sip", "stir", "dip", "say_done"] self.actions_keys = self.fixate_action_keys + self.do_action_keys self.hidden_state_keys = ["sugar_bowl_open", "coffee_packet_torn", "sugar_packet_torn", "carton_open", "how_full", "clear_liquid", "brown_liquid", "light_", "sugar_bowl", "coffee_poured", "cream_poured", "sugar_poured", "coffee_stirred", "cream_stirred", "sugar_stirred", "tea_dipped", "bad_taste", "disaster", "done", "reward"] self.hidden_state_keys = ['s_' + key for key in self.hidden_state_keys] self.observable_keys = self.fixated_keys + self.held_keys self.all_keys = self.actions_keys + self.observable_keys + self.hidden_state_keys assert len(self.all_keys) == len(set(self.all_keys)) # Check that there are no duplicates self.state = state.State(self.all_keys, self.observable_keys) self.state.str_func = self.state_to_string
def add_initial_state(self, model, sess, P, iterative_pw=False): """ Add an empty initial state to the beam. This is used once before the initial beam search begins. Parameters ========== model : Model The language model to use for the transduction process sess : tf.session The tensorflow session of the loaded model. pitch_wise : boolean True to use iterative pitchwise processing (and save only a single hidden_state per State). False (default) otherwise. """ if model.pitchwise and not iterative_pw: single_state = model.get_initial_state(sess, 1)[0] # We have to get 88 initial states, one for each pitch initial_state = [copy.copy(single_state) for i in range(P)] else: initial_state = model.get_initial_state(sess, 1)[0] prior = np.ones(P) / 2 if not iterative_pw else np.array([0.5]) new_state = state.State(P, model.with_onsets) new_state.update_from_lstm(initial_state, prior) self.beam.append(new_state)
def test(loader, agent): # Set up agent state space current_state = state.State((1, 1, CROP_SIZE, CROP_SIZE), MOVE_RANGE) # Obtain image data from loader raw_x, maxIntensity, imgName, imgAffine = loader.load_testing_data() # Reset state values to input image intensities current_state.reset(raw_x) # Iterate through episode steps for t in range(0, EPISODE_LEN): # Sample and execute action action, inner_state = agent.act(current_state.tensor) current_state.step(action, inner_state) # Halt iteration agent.stop_episode() # Normalize image and write to disk outputImg = normalizedImage(current_state.image, maxIntensity, imgAffine) nib.save(outputImg, os.path.join(OUTPUT_PATH, '%s_output.nii' % imgName)) sys.stdout.flush()
def CDK4(self, g, s, indexList, i): i = indexList if ((s[i[0]].x == 0) and (s[i[1]].x == 0) and (s[i[2]].x == 0)): image = 1 else: image = 0 return state.State(int(image), 2)
def main(): #if len(sys.argv) != 2: # print("Usage: python3 main.py <SUDOKU_FILE>") # sys.exit(-1) f = open('board.txt', 'r') games = f.readlines() gameCount = 0 for game in games: count = 0 board = state.State() for row in range(0, 9): for col in range(0, 9): c = game[count] count += 1 if not c: break board.setupSquare(c, col, row) works = board.constraintSearch() g = open('solvelist.txt', 'w') if works == False or works == None: solvedBoard = backTrack(board) solvedBoard.printBoard() solveList = solvedBoard.solveList for x in solveList: g.write(str(x[0]) + " " + str(x[1]) + " " + str(x[2]) + "\n") else: solveList = board.solveList for x in solveList: g.write(str(x[0]) + " " + str(x[1]) + " " + str(x[2]) + "\n") board.printBoard()
def LIN12m(self, g, s, indexList, i): i = indexList if (((s[i[0]].x <= 1) or (s[i[1]].x == 1))): image = 1 else: image = 0 return state.State(int(image), 2)