def main(stdscr): if (curses.LINES < 50 or curses.COLS < 150): closeGame() return curses.start_color() curses.use_default_colors() initColors() loadgame = True while loadgame: # MAIN MENU LOOP choice = mainMenu() # do main menu everything selectedMap = 0 if (choice == 3): closeGame() return elif (choice == 1): # user has started a new game, go to first map selectedMap = maps[0] elif (choice == 2): selectedMap = mapSelect() loadgame = selectedMap is "BACK" filename = selectedMap.replace(" ","") + ".scn" mapx = (curses.COLS/2) - 10 mapy = 10 scenario = Scenario(filename,mapy,mapx) # Create the scenario mapPan = scenario.mapPan() mapPan.bottom() mapPan.move(mapy,mapx) curses.panel.update_panels() # START PLAYING! game = Game(scenario, mapPan) while 1: game.doNextTurn()
def loadScenFromFile(jsonFile): s = Scenario() with open(jsonFile, "r") as data_file: data = json.load(data_file) initial = data["Scenario"][0]["initial"] s.initial = str(initial) flavor = data["Scenario"][0]["flavorText"] s.flavorText = str(flavor) option1 = data["Scenario"][0]["option1"] s.option1 = str(option1) option2 = data["Scenario"][0]["option2"] s.option2 = str(option2) option3 = data["Scenario"][0]["option3"] s.option3 = str(option3) finish1 = data["Scenario"][0]["finish1"] s.finish1 = finish1 finish2 = data["Scenario"][0]["finish2"] s.finish2 = finish2 finish3 = data["Scenario"][0]["finish3"] s.finish3 = finish3 finished = data["Scenario"][0]["finished"] s.finished = bool(finished) #s.loadCreature() return s
def __init__(self, pl, sc_path): self.sc = Scenario(sc_path) self.pl = pl # Automatically print the -1 scenario print(self.sc.get_scenario_update(pl)) self.pl.direction = 0
def __init__(self): self.p = Player(savedPlayerJSON) #self.updatePlayer(self.p,True,0,0) if self.p.isDead(): self.p = Player("./json/newPlayerTemplate.json") self.trend = getTrend() #print self.trend self.scen = Scenario() self.scen.loadFromFile(savedScenJSON) if self.scen.finished: option = getReplies(self.p.lastID) self.followUpTweet(option) if option == 1: item = self.scen.finish1[1] exp = self.scen.finish1[2] health = self.scen.finish1[3] elif option ==2: item = self.scen.finish2[1] exp = self.scen.finish2[2] health = self.scen.finish2[3] else: item = self.scen.finish3[1] exp = self.scen.finish3[2] health = self.scen.finish3[3] self.updatePlayer(self.p,item,exp,health) tempEnviro = Environment(self.trend) tempEnviro.generateScenario(self.trend).saveScenario() self.scen = loadScenFromFile(savedScenJSON)
def loadCsv(file): rides = [] with open(file, 'rb') as f: lines = f.readlines() scenario = Scenario(lines[0]) # skip first line in file i = 0 iterlines = iter(lines) next(iterlines) for line in iterlines: ride = Ride(line, i) rides.append(ride) i += 1 return scenario, rides # example # loadCsv('data/a_example.in') # print(scenario) # print(len(rides)) # for ride in rides: # print(ride)
def __init__(self, queries, options, scenario_plan, samples=3): self._queries = queries self._samples = samples self._options = options self._scenario_plan = scenario_plan self._scenarios = [] self._results = [] self._stats = [] # TODO (djrut): Implement more sophisticated scenario plans, with # idioms such as: 'range(x..y) step z' for scenario in scenario_plan.split(','): self._scenarios.append(Scenario(threads=int(scenario), samples=self._samples, queries=self._queries, options=self._options)) for stat_name, stat_function in stats_cfg.items(): self._stats.append(Statistic(name=stat_name, function=stat_function))
def simulate_move(self, color): new_scenarios = [] index = 0 for scenario in self.scenarios: index = index + 1 acting_figures = [] for figure in scenario.get_figures(): if figure.color == color: acting_figures.append(figure) for figure in acting_figures: [x, y] = figure.get_position() possible_moves = figure.simulate_move(scenario.get_board()) for move in possible_moves: new_board = copy_board(scenario.get_board()) new_board[y][x] = "--" new_move = (columns[x] + str(8-y) + '->' + columns[move[0]] + str(8-move[1]) ) if figure.get_type() == 'p' and (move[1] == 7 or move[1] == 0): new_board[move[1]][move[0]] = (figure.get_color() + 'q' ) new_scenarios.append(Scenario(new_board, [], new_move, index)) new_scenarios[-1].update_figures(new_board) new_board[move[1]][move[0]] = (figure.get_color() + 'k' ) new_scenarios.append(Scenario(new_board, [], new_move, index)) new_scenarios[-1].update_figures(new_board) else: new_board[move[1]][move[0]] = (figure.get_color() + figure.get_type() ) new_scenarios.append(Scenario(new_board, [], new_move, index)) new_scenarios[-1].update_figures(new_board) new_scenarios.append(Scenario(scenario.get_board(), scenario.get_figures(), scenario.get_move(), index)) self.scenarios = new_scenarios.copy()
def create_scenario(): c = check_input(session.get('logged_in')) if c != '': return c scen = Scenario() scenario_id = db.add_scenario(scen) #add new scenario to db #redirect to new scenario main page return redirect(url_for('view_scenario', scenario_id=scenario_id))
def __init__(self, name: str="VR", debug: bool=False): """ コンストラクタ :param name: :param debug: """ self.isdebug = debug self.vrName = name self.log = Log() self.scenario = Scenario(debug=True)
def init_scenario(self): position = [] velocity = [] self.scenario = Scenario() self.scenario.set_cols(self.cols) self.scenario.set_rows(self.rows) for i in range(self.rows): tP = [] tV = [] for j in range(self.cols): tP.append(0) tV.append(0) position.append(tP) velocity.append(tV) self.slide.set_timing(0) self.slide.set_position(position) self.slide.set_velocity(velocity) self.scenario.set_slide(self.slide, 0) self.lblNumOfSlides.setText(str(self.scenario.get_num_of_slides()))
class Simulation: model = Model() driver = Driver() scanario = Scenario() env = Env() env = None # Find way to do vector<samples> for line below with correct import samples = np.array() results = Results() results = None def Simulation(self, model): self.model = model driver = Driver(model, "Driver", 25, float(1.0), float(1.0)) scenario = Scenario() env = Env(driver, scenario) # samples.add(recordSample(env)) # Find way for syncrhonized to work def synchronized_update(self): self.env.update() # samples.add (recordSample (env)) # analyze() defined below def getResults(self): self.results = analyze() return self.results def numSamples(self): return self.samples.size() def recordSample(self, env): s = Sample() s.time = env.time s.simcarPos = env.simcar.p.myclone() s.simcarHeading = env.simcar.h.myclone() s.simcarFracIndex = env.simcar.fracIndex s.simcarSpeed = env.simcar.speed s.simcarRoadIndex = env.simcar.roadIndex if(env.simcar.nearPoint == None): s.nearPoint = env.simcar.nearPoint.myclone() s.farPoint = env.simcar.farPoint.myclone() s.carPoint = env.simcar.carPoint.myclone() s.steerAngle = env.simcar.steerAngle s.accelerator = env.simcar.accelerator s.brake = env.simcar.brake s.autocarPos = env.autocar.p.myclone() s.autocarHeading = env.autocar.h.myclone() s.autocarFracIndex = env.autocar.fracIndex s.autocarSpeed = env.autocar.speed s.autocarBraking = env.autocar.braking
def run_scenario_menu(self): if None in [self.data.VR, self.data.RD, self.data.kf]: print(' ') print( 'Scenario not fully specified. Update scenario configuration and try again' ) print(' ') input("Press [Enter] to continue...") else: answers = self.setup_plot_rt_q() plot_rt = answers.get("plot_rt") scen = Scenario(self.data.VR, self.data.rxn_temp, self.data.rxn_time, self.data.XH2O2, self.data.mR, self.data.D_RD, self.data.P_RD, self.data.P_BPR, self.data.D_BPR, self.data.BPR_max_Cv, self.data.P0, self.data.kf, self.data.T0, self.data.Ux, self.data.AR, self.data.MAWP, self.data.max_rate, self.data.Kp, self.data.Ki, self.data.Kd, self.data.flow_regime, self.data.BPR, self.data.RD, self.data.cool_time, self.data.TF) ode1 = ODE.ODE(scen) ode1.initialize_heatup() print('Integrating Heatup...') print(' ') ode1.integrate(plot_rt) tc = ode1.termination_code() print(' ') print(tc) print(' ') if self.data.RD is True and ode1.tc == 1: print('Integrating ERS...') print(' ') ode1.initialize_vent(integrator='vode') ode1.integrate(plot_rt) tc = ode1.termination_code() print(' ') print(tc) print(' ') self.data.ode = ode1 self.summary_stats_menu()
def set_probability_for_each_scenario(ontology_manager): scenarios = __generate_scenarios(ontology_manager) # TODO trovare un modo migliore per gestire lo scenario vuoto scenarios.__next__() for scenario in scenarios: scenario = list(scenario) probability_to_assign_to_each_scenario = 1 for tm in scenario: probability_to_assign_to_each_scenario = probability_to_assign_to_each_scenario * tm.probability diff = __difference(scenario, ontology_manager.typical_members_list) for key in diff: typical_member = __get_typical_member(key, ontology_manager) probability_to_assign_to_each_scenario = probability_to_assign_to_each_scenario * ( 1 - typical_member.probability) ontology_manager.scenarios_list.append( Scenario(scenario, probability_to_assign_to_each_scenario))
def __update_raw_tests(self): self.raw_test.scenarios.append( Scenario(url=self.url, feature_name=self.feature_name, text="Example test scenario")) for choice in self.cases[0].selected_expands: self.raw_test.scenarios[0].steps.append( Step(step_type=choice.parent.step_type, feature_name=self.feature_name, x_path=choice.parent.xpath, input_type=choice.parent.input_type, cases=[], label="Element " + choice.parent.name + " has value <choice{}>".format(choice.parent.id))) for case in self.cases: for i, choice in enumerate(case.selected_expands): self.raw_test.scenarios[0].steps[i].cases.append(choice.choice)
def run_sensitivity_menu(self): if None in [self.data.VR, self.data.RD, self.data.kf]: print(' ') print( 'Scenario not fully specified. Update scenario configuration and try again' ) print(' ') input("Press [Enter] to continue...") elif None in [self.data.value]: print(' ') print( 'Sensitivity not specified. Update sensitivity configuration and try again' ) print(' ') input("Press [Enter] to continue...") else: scen = Scenario(self.data.VR, self.data.rxn_temp, self.data.rxn_time, self.data.XH2O2, self.data.mR, self.data.D_RD, self.data.P_RD, self.data.P_BPR, self.data.D_BPR, self.data.BPR_max_Cv, self.data.P0, self.data.kf, self.data.T0, self.data.Ux, self.data.AR, self.data.MAWP, self.data.max_rate, self.data.Kp, self.data.Ki, self.data.Kd, self.data.flow_regime, self.data.BPR, self.data.RD, self.data.cool_time, self.data.TF) print(' ') print('Starting Sensitivity Analysis for ' + str(self.data.name)) try: self.sensitivity(scen, self.data.value, self.data.ranges) self.stats_sensitivity() except: print('Something went wrong, please try again...') print(' ') input("Press [Enter] to continue...")
def main(algo_name, bound_name, scenario_name, setting_name): assert(setting_name == "bandit" or setting_name == "finite") scenario = Scenario(scenario_name) print("Running scenario", scenario_name, "with algorithm", algo_name, "and bound", bound_name) num_iterations = 100#1 algo = Algorithm.make(algo_name, bound_name, scenario) width_avg, sample_avg, correct_avg, UB_avg, mean_avg = run(scenario, algo, setting_name, algo_name, scenario_name, bound_name) for i in range(num_iterations - 1): algo = Algorithm.make(algo_name, bound_name, scenario) width_history, sample_history, correct_history, UB_history, mean_history = run(scenario, algo, setting_name, algo_name, scenario_name, bound_name) width_avg += width_history sample_avg += sample_history correct_avg += correct_history UB_avg += UB_history mean_avg += mean_history width_avg /= num_iterations sample_avg /= num_iterations correct_avg /= num_iterations UB_avg /= num_iterations mean_avg /= num_iterations save_data(setting_name, algo_name, scenario_name, bound_name, ["widths", "samples", "correct", "UB", "mean"], [width_avg, sample_avg, correct_avg, UB_avg, mean_avg])
def doc_to_scenario(doc): dialog_data = doc['dialog'] dialog = [] #create dialog list, but neighbor_ids is temporary for response_text, questions, neighbor_ids, points in dialog_data: dialog.append( Response_Node(response_text, questions, neighbor_ids, points)) for response in dialog: neighbors = [] neighbor_ids = response.get_neighbors() #indices of neighbors for neighbor_id in neighbor_ids: neighbors.append( dialog[neighbor_id]) #use indices to find neighbors response.set_neighbors( neighbors) #store actual neighbors for this response video_link = '' if 'video_link' in doc: video_link = doc['video_link'] return Scenario(doc['name'], doc['description'], doc['image'], Dialog(dialog), video_link)
def __init__(self, user_id): self.data = DataFromUser() self.scenario = Scenario() self.words = Words() self.menu(user_id)
class CommandInterpreter: # sc = None pl = None # All of our acceptable words sp_objects = ["inventory", "bag"] sp_targets = ["left", "right"] target = ["the", "at", "on", "around", "my"] actions = ["use", "exit", "look", "open", "take", "turn"] action_alt = { "utilize,operate": "use", "leave,go": "exit", "inspect,view,observe": "look", "grab,steal,borrow": "take", "check": "open", "rotate": "turn", } # Our escape characters for displaying terminal text bc_ylwbld = "\033[1;33;20m" bc_whtnrm = "\033[0;37;20m" bc_grnbld = "\033[1;32;40m" bc_lblnrm = "\033[1;34;20m" def __init__(self, pl, sc_path): self.sc = Scenario(sc_path) self.pl = pl # Automatically print the -1 scenario print(self.sc.get_scenario_update(pl)) self.pl.direction = 0 def update(self, inp): if inp.lower() == "exit": return False # Update will first parse the users # text into chunks, then remove useless words, # and finally push whats left as actions. inp = self.__parse(inp) # Remove Junk will return one array of three arrays # The first containing all the actions # One containing targets["on","the","at"] # The other containing Objects for the target command inp = self.__remove_junk(inp) # Change the environment based on text input self.__interpret(inp) # Print scenario response to action #print(self.sc.get_scenario_update(0,self.pl.direction,0)) # Continue the Game return True def get_challenge_text(self): return self.bc_grnbld + "What will you do? " + self.bc_whtnrm def __is_alternate(self, inp): return False if self.__get_alternative(inp) == None else True def __get_alternative_of(self, inp): # Go over the dictionary for key, val in self.action_alt.items(): # Split it up chunks = key.split(",") # Go over the splits for x in chunks: if x == inp: return self.action_alt.get(x) def __get_alternative(self, inp): for key, val in self.action_alt.items(): #Split it Up chunks = key.split(",") # If the word entered exists as an alternative in # the dictionary then cool beans. if inp.lower() in chunks: return val def __interpret(self, inp): if len(inp[0]) == 0: a = random.randint(1, 3) r = "" if a == 1: r = "Think..." elif a == 2: r = "If only it were that easy..." elif a == 3: r = "You are wasting time..." print(r) return # Looking for certain commands try: # Attempt to find an alternative first cmd = self.__get_alternative(inp[0][0]) # If there was no alternative for the word entered # use the original. if cmd == None: cmd = inp[0][0] # If the first index is a command # feed the rest of the list to the command if cmd in self.actions: getattr(self, cmd)(inp[1], inp[2]) else: print("Command {} not found".format(inp[0][0])) except (AttributeError, IndexError) as ae: print("Failed to parse command {}".format(ae)) def __parse(self, inp): # Return a Lowercased version of the input with no # new lines and split by spaces. return inp.lower().replace("\n", "").split(" ") def __remove_junk(self, inp): # arr = [] # Keep objects in the scenario sc_list = [] # If the Scenario has objects # that the input contains, do not remove them. for c in self.sc.objects: if c.name.lower() in inp: sc_list.append(c.name.lower()) for i in self.pl.inventory: if i.name.lower() in inp: sc_list.append(i.name.lower()) # Remove all words in the array that aren't # recognized by the targets and actions. for x in inp: # Allow for alternate versions of commands. is_cmd = False if x not in self.actions and not self.__is_alternate( x) else True # If the current word is a target word # or action(command) or an item in the scenario # keep it. if x in self.target or is_cmd or x in sc_list: # Now check the scenario for items in view arr.append(x) # Remove all entries from the scene list actions = [ a for a in arr if a in self.actions or self.__is_alternate(a) ] targets = [t for t in arr if t not in sc_list and t not in actions] objects = [o for o in arr if o not in targets and o not in actions] # Add on Special Objects if we use the 'open' command if self.__get_alternative_of(inp[0]) == "open" and ("inventory" in inp or "bag" in inp): objects.append("inventory") elif inp[0] == "turn" or self.__get_alternative_of(inp[0]) == "turn": for t in inp: for p in self.sp_targets: if t == p: targets.append(p) break # Return the original chunks with the useless words removed. return [actions, targets, objects] def open(self, tar, obj): if len(obj) > 0: # Special case for the word inventory if obj[0] == "inventory" and ("the" in tar or "my" in tar or len(tar) == 0): # Grab the inventory p_objs = self.pl.inventory # f = None # print(self.bc_whtnrm + "You " + self.bc_ylwbld + "Open" + self.bc_whtnrm + " your bag and see:") # Grab all the items from the player's inventory for x in p_objs: f = x print("A " + self.bc_lblnrm + x.name + self.bc_whtnrm) if f == None: print(self.bc_whtnrm + "Nothing but air." + self.bc_whtnrm) else: # Grab all the objects from the view v_objs = self.sc.get_objects_in_view(self.pl) else: print(self.bc_ylwbld + "Check" + self.bc_whtnrm + " what?") def turn(self, tar, obj): # Current player context # Turn only processes the first target if len(obj) == 0: if tar[0] == "left": self.pl.direction = 3 if self.pl.direction == 0 else self.pl.direction - 1 print(self.sc.get_scenario_update(self.pl)) elif tar[0] == "right": self.pl.direction = 0 if self.pl.direction == 3 else self.pl.direction + 1 print(self.sc.get_scenario_update(self.pl)) elif tar[0] == "around": self.pl.direction = (self.pl.direction + 2) % 4 print(self.sc.get_scenario_update(self.pl)) def take(self, tar, obj): # Eventually add context objects based on last successful command if len(obj) == 0: print(self.bc_ylwbld + "Take" + self.bc_whtnrm + " what?") return # Don't allow grabbing more than one item at a time. elif len(obj) > 1: print("You need more hands to grab all that at once.") return # Now Grab all those objects in our current view v_objs = self.sc.get_objects_in_view(self.pl) # Mull over the objects in the view for x in v_objs: # The item is in the state to be grabbed. (Implement Strength Values if RPG) if x.status == 0 and x.name.lower() == obj[0]: # Add the item to the player's inventory self.pl.add_item(x) # Play the Objects take text. print( str(self.bc_whtnrm + x.take + self.bc_whtnrm).format(self.bc_ylwbld + x.name + self.bc_whtnrm)) self.sc.remove_object_from_view(self.pl, x) break def look(self, tar, obj): # v_objs = self.sc.get_objects_in_view(self.pl) # No target objects and no targeting words. if len(obj) == 0 and len(tar) >= 1: # Around is a special case. if tar[0] == "around": # if len(v_objs) > 0: # print(self.bc_whtnrm + "You " + self.bc_ylwbld + "look" + self.bc_whtnrm + " around and see:" + self.bc_whtnrm) # for v in v_objs: print(self.bc_lblnrm + v.name + self.bc_whtnrm + " - '" + v.desc + "'") else: print(self.bc_whtnrm + "There is nothing to see here." + self.bc_whtnrm) else: print(self.bc_ylwbld + "Look" + self.bc_whtnrm + " at what?" + self.bc_whtnrm) elif len(obj) == 1 and len(tar) > 1: found = False for v in v_objs: if v.name.lower() == obj[0]: found = True print(self.bc_lblnrm + v.desc + self.bc_whtnrm) break if found == False: print("There is no " + self.bc_ylwbld + obj[0] + self.bc_whtnrm + " nearby.") def use(self, tar, obj): # Use only accepts two values # The object that is being used # and the object it is being used on if len(obj) == 0: print(self.bc_ylwbld + "Use" + self.bc_whtnrm + " what?") return if len(self.pl.inventory) == 0: print(self.bc_whtnrm + "You have nothing to " + self.bc_ylwbld + "Use" + self.bc_whtnrm) for o in self.pl.inventory: # Cool Beans, the player has the item if obj[0] == o.name.lower(): # Grab all the items in view v_objs = self.sc.get_objects_in_view(self.pl) # Two objects to act on if len(obj) == 2: # for v in v_objs: # The Scenario has the item we want to act on in view. if v.name.lower() == obj[1].lower(): # Boom, interact with each other. o.interact(v) else: print( str(self.bc_ylwbld + "Use" + self.bc_whtnrm + " the " + self.bc_lblnrm + o.name + self.bc_whtnrm + " on what?"))
distances = list() distances.append(1.2) distances.append(5.3) distances.append(6.6) distances.append(3.3) distances.append(9.7) distances.append(2.1) distances.append(7.5) distances.append(4.3) distances.append(7.7) distances.append(5.0) print 'Test 1:' try: scenario = Scenario(1, 5.0, '', '', '') scenario.calculateMetrics(list(), distances) print 'Test failed. Should throw an error if coreLogPath is empty' except (IndexError), e: print 'Empty coreLogPath error thrown successfully' print 'Test 2:' try: scenario = Scenario(1, 5.0, '', '', '') scenario.calculateMetrics(coreLogPath, list()) print 'Test failed. Should throw an error if distances is empty' except (IndexError), e: print 'Empty distances error thrown successfully' print 'Test 3:' try:
def run(config_file, args): """! Run fire based on configuartion file and command line arguments @param config_file Configuration file to read Scenario from @param args argparser to pass to Scenario @return None """ scenario = Scenario(config_file, args) had_output = scenario.is_current() ensure_dir(os.path.dirname(scenario.run_output)) sizes = None # try to find a perimeter and import it changed = False def clean_flag(): if os.path.exists(scenario.mapflag): os.remove(scenario.mapflag) def cleanup(): if os.path.exists(scenario.run_output): logging.error("Removing output after run failed for " + scenario.fire) shutil.rmtree(scenario.run_output, True) clean_flag() if scenario.force or not (had_output or os.path.exists(scenario.runflag)): # HACK: do this right away so that running more than once shouldn't do the same fire in both processes try: ensure_dir(scenario.run_output) write_file(scenario.run_output, "running", " ") stdout, stderr = runFire(scenario) write_file(scenario.run_output, "output.txt", '\n'.join(stdout.split('\r\n'))) os.remove(scenario.runflag) changed = True except KeyboardInterrupt: # this doesn't work for some reason cleanup() except Exception as e: logging.fatal("Error running " + scenario.fire) print(e) traceback.print_exc() cleanup() return # don't delete output if maps fail if (changed or scenario.force_maps or scenario.check_maps) and not (scenario.no_maps or os.path.exists(scenario.runflag)): t0 = timeit.default_timer() try: scenario.save_point_shp() from mxd import makeMaps pdf_out = makeMaps(scenario, scenario.run_output, scenario.force_maps or changed, scenario.hide) except Exception as e: logging.fatal(e) traceback.print_exc() cleanup() # run didn't work before so run it now run(config_file, args) try: if scenario.outbase == Settings.OUTPUT_DEFAULT: district_folder = os.path.join(Settings.FIRE_ROOT, FOLDER_BY_TLA[scenario.fire[:3]]) to_folder = os.path.join(district_folder, scenario.fire) to_file = os.path.join(to_folder, 'FireSTARR', os.path.basename(pdf_out)) if not os.path.exists(to_folder): print("*********************************************") print("Need to make fire folder for {}".format(scenario.fire)) print("*********************************************") cmd = r'C:\Windows\System32\cscript.exe' run_what = [cmd, os.path.join(district_folder, "CreateFireFolder.vbe"), str(int(scenario.fire[3:]))] logging.debug("Running: " + ' '.join(run_what)) finish_process(start_process(run_what, Settings.PROCESS_FLAGS, district_folder)) if not os.path.exists(to_folder): logging.fatal("MAKING FOLDER FAILED") sys.exit(-1) if not os.path.exists(to_file): try_copy(pdf_out, to_file) csv_out = os.path.splitext(pdf_out)[0] + "_assets.csv" csv_to = os.path.splitext(to_file)[0] + "_assets.csv" if not os.path.exists(csv_to): try_copy(csv_out, csv_to) except Exception as e: logging.fatal("Couldn't copy to file plan") print(e) traceback.print_exc() clean_flag() t1 = timeit.default_timer() logging.info("Took {}s to make maps".format(t1 - t0))
#Test 1 #Files: # - gps.log # - Corefile.log #Expected Results: # - To be filled out later import os.path, sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) from Scenario import Scenario s = Scenario(1, 8, 'gps.log', 'Corefile.log') s.run() s.export()
def Simulation(self, model): self.model = model driver = Driver(model, "Driver", 25, float(1.0), float(1.0)) scenario = Scenario() env = Env(driver, scenario)
class Panel(QWidget): def __init__(self): super().__init__() try: with open("styles.css", "r") as fh: self.setStyleSheet(fh.read()) except: pass self.lastPosEntered = 0 self.lastVelocityEntered = 0 self.scenario = None self.slide = Slide() self.rows = 5 self.cols = 10 self.currentSlide = 0 self.numOfSlides = 0 self.timingIncrement = 200 self.btnNew = QPushButton('NEW') self.btnOpen = QPushButton('OPEN') self.btnSave = QPushButton('SAVE') self.btnSaveAs = QPushButton('SAVE AS') self.lblNumOfRows = QLabel('0') self.lblNumOfCols = QLabel('0') self.btnSave.clicked.connect(self.save_clicked) self.btnOpen.clicked.connect(self.open_clicked) self.fileLayout = QHBoxLayout() self.fileLayout.addWidget(self.btnNew) self.fileLayout.addWidget(self.btnOpen) self.fileLayout.addWidget(self.btnSave) self.fileLayout.addWidget(self.btnSaveAs) self.fileLayout.addSpacing(10) self.fileLayout.addWidget(QLabel('ROWS:')) self.fileLayout.addWidget(self.lblNumOfRows) self.fileLayout.addSpacing(10) self.fileLayout.addWidget(QLabel('COLS:')) self.fileLayout.addWidget(self.lblNumOfCols) self.fileLayout.addSpacing(10) self.fileLayout.addWidget(QLabel('TYPE:')) self.fileLayout.addWidget(QLabel('SQUARE')) self.btnNew.clicked.connect(self.newScenarioClicked) self.btnPrevSlide = QPushButton("BACK") self.btnNextSlide = QPushButton("NEXT") self.txtCurSlide = QLineEdit(str(self.currentSlide)) self.txtCurSlide.setFixedWidth(100) self.lblNumOfSlides = QLabel(str(self.numOfSlides)) self.lblNumOfSlides.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.txtTimeIncrement = QLineEdit('0') self.txtTimeIncrement.setFixedWidth(100) self.txtTime = QLineEdit('0') self.txtTime.setFixedWidth(100) self.btnInsertSlide = QPushButton('Insert') self.btnAppendSlide = QPushButton('Append') self.btnAcceptSlide = QPushButton('Accept') self.btnDeleteSlide = QPushButton('Delete') self.txtCurSlide.editingFinished.connect(self.txtEditingFinished) self.txtTime.editingFinished.connect(self.time_change) self.btnPrevSlide.clicked.connect(self.prevSlideClicked) self.btnNextSlide.clicked.connect(self.nextSlideClicked) self.btnAppendSlide.clicked.connect(self.appendSlideClicked) self.btnAcceptSlide.clicked.connect(self.acceptSlideClicked) self.btnInsertSlide.clicked.connect(self.insert_clicked) self.btnDeleteSlide.clicked.connect(self.delete_clicked) self.controlBtnsLayout = QHBoxLayout() self.controlBtnsLayout.addWidget(self.btnPrevSlide) self.controlBtnsLayout.addWidget(self.btnNextSlide) self.controlBtnsLayout.addWidget(self.txtCurSlide) self.controlBtnsLayout.addWidget(QLabel('of')) self.controlBtnsLayout.addWidget(self.lblNumOfSlides) self.controlBtnsLayout.addStretch() self.controlBtnsLayout.addWidget(QLabel('timing inc')) self.controlBtnsLayout.addWidget(self.txtTimeIncrement) self.controlBtnsLayout.addWidget(QLabel('timing')) self.controlBtnsLayout.addWidget(self.txtTime) self.controlBtnsLayout.addStretch() self.controlBtnsLayout.addWidget(self.btnInsertSlide) self.controlBtnsLayout.addWidget(self.btnAppendSlide) self.controlBtnsLayout.addWidget(self.btnAcceptSlide) self.controlBtnsLayout.addWidget(self.btnDeleteSlide) self.mainLayout = QVBoxLayout() self.panelsLayout = QHBoxLayout() self.positionTable = QGridLayout() self.velocityTable = QGridLayout() self.positionLayout = QVBoxLayout() self.velocityLayout = QVBoxLayout() self.btnsPositionLayout = QHBoxLayout() self.btnsVelocityLayout = QHBoxLayout() self.txtPosition = QLineEdit('0') self.txtPosition.setFixedWidth(60) self.btnSetPosition = QPushButton('Set') self.btnSetPosition.clicked.connect(self.setPositionClicked) self.btnsPositionLayout.addWidget(self.txtPosition) self.btnsPositionLayout.addWidget(self.btnSetPosition) self.btnsPositionLayout.addStretch() self.txtVelocity = QLineEdit('0') self.txtVelocity.setFixedWidth(60) self.btnSetVelocity = QPushButton('Set') self.btnSetVelocity.clicked.connect(self.setVelocityClicked) self.btnsVelocityLayout.addWidget(self.txtVelocity) self.btnsVelocityLayout.addWidget(self.btnSetVelocity) self.btnsVelocityLayout.addStretch() self.positionLayout.addLayout(self.btnsPositionLayout) self.positionLayout.addLayout(self.positionTable) self.velocityLayout.addLayout(self.btnsVelocityLayout) self.velocityLayout.addLayout(self.velocityTable) self.panelsLayout.setProperty("gridLayout", "panelsLayout") self.panelsLayout.addLayout(self.positionLayout) self.panelsLayout.insertSpacing(1, 20) self.panelsLayout.addLayout(self.velocityLayout) #self.redrawPanels() self.btnDebug = QPushButton('Debug') self.btnDebug.clicked.connect(self.debug_clicked) self.btnProcess = QPushButton('Process') self.btnProcess.clicked.connect(self.generate_clicked) self.mainLayout.addLayout(self.fileLayout) self.mainLayout.addSpacing(5) self.mainLayout.addLayout(self.controlBtnsLayout) self.mainLayout.addSpacing(20) self.mainLayout.addLayout(self.panelsLayout) self.mainLayout.addSpacing(20) self.mainLayout.addWidget(self.btnDebug) self.mainLayout.addSpacing(20) self.mainLayout.addWidget(self.btnProcess) self.setLayout(self.mainLayout) self.setWindowTitle('Scenario generator panel') self.show() def delete_clicked(self): slideIndex = int(self.txtCurSlide.text()) - 1 self.currentSlide = slideIndex + 1 if slideIndex == 0 and self.scenario.get_num_of_slides() == 1: print('cant delete single slide') return elif slideIndex == 0: nextSlide = 1 else: nextSlide = slideIndex - 1 self.slide = self.scenario.get_slide(nextSlide) self.scenario.delete_slide(slideIndex) self.updateSlideNum() self.txtCurSlide.setText(str(slideIndex + 1)) self.lblNumOfSlides.setText(str(self.scenario.get_num_of_slides())) def insert_clicked(self): slideIndex = int(self.txtCurSlide.text()) slide = deepcopy(self.scenario.get_slide(slideIndex - 1)) self.scenario.insert_slide(slideIndex, slide) self.slide = slide self.nextSlideClicked() self.lblNumOfSlides.setText(str(self.scenario.get_num_of_slides())) def save_clicked(self): fileName, _ = QFileDialog.getSaveFileName( self, "QFileDialog.getSaveFileName()", "", "Scenario files (*.bsc)") if fileName: print(fileName) pickle.dump(self.scenario, open(fileName, "wb")) def open_clicked(self): fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "Scenario files (*.bsc)", ) if fileName: print(fileName) self.scenario = pickle.load(open(fileName, "rb")) if self.scenario.get_rows() < 1 or self.scenario.get_cols() < 1: print('Wrong Scenario') return else: self.scenario.print_info() self.rows = self.scenario.get_rows() self.cols = self.scenario.get_cols() self.redrawPanels() slideIndex = 1 slide = self.scenario.get_slide(slideIndex - 1) self.txtCurSlide.setText(str(slideIndex)) self.numOfSlides = self.scenario.get_num_of_slides() print("num os slides {0}".format(self.numOfSlides)) self.lblNumOfSlides.setText(str(self.numOfSlides)) if slide is not None: self.slide = slide self.slide.print() self.txtTime.setText(str(self.slide.get_timing())) for i in range(self.rows): for j in range(self.cols): self.listOfPos[i][j].setText( str(self.slide.get_position()[i][j])) self.listOfVel[i][j].setText( str(self.slide.get_velocity()[i][j])) def debug_clicked(self): self.scenario.print_info() def generate_clicked(self): print('generate clicked') fileName, _ = QFileDialog.getSaveFileName( self, "QFileDialog.getSaveFileName()", "", "txt scenario (*.txt)") if fileName: print(fileName) with open(fileName, 'w') as f: for slide in self.scenario.slides: msg = "" msg += str(slide.timing) msg += ":" for i in range(len(slide.get_position())): for j in range(len(slide.get_position()[0])): msg += str(slide.get_position()[i][j]) msg += "," msg += str(slide.get_velocity()[i][j]) if j != (len(slide.get_position()[0]) - 1): msg += ";" if i != (len(slide.get_position()) - 1): msg += '\n' f.write(msg) def acceptSlideClicked(self): pass def appendSlideClicked(self): slideIndex = self.scenario.get_num_of_slides() self.timingIncrement = int(self.txtTimeIncrement.text()) timing = self.scenario.get_slide(slideIndex - 1).get_timing() + self.timingIncrement self.slide = deepcopy(self.scenario.get_slide(slideIndex - 1)) self.slide.set_timing(timing) self.scenario.append_slide(self.slide) self.txtTime.setText(str(timing)) self.txtCurSlide.setText(str(slideIndex + 1)) self.lblNumOfSlides.setText(str(self.scenario.get_num_of_slides())) self.numOfSlides = self.scenario.get_num_of_slides() for i in range(self.rows): for j in range(self.cols): self.listOfPos[i][j].setText( str(self.slide.get_position()[i][j])) self.listOfVel[i][j].setText( str(self.slide.get_velocity()[i][j])) def time_change(self): slideIndex = int(self.txtCurSlide.text()) - 1 slideTiming = int(self.txtTime.text()) if slideIndex > 0: if slideTiming < self.scenario.get_slide(slideIndex - 1).get_timing(): print('wrong time') self.txtTime.setText( str(self.scenario.get_slide(slideIndex - 1).get_timing())) return prevSlideTiming = self.scenario.get_slide(slideIndex).get_timing() deltaTiming = slideTiming - prevSlideTiming self.scenario.get_slide(slideIndex).set_timing(slideTiming) self.scenario.update_timings(startindex=slideIndex + 1, delta=deltaTiming) def newScenarioClicked(self): dlg = CustomDialog(self) if dlg.exec_(): print("Success!") print(dlg.txtColsNumber.text()) print(dlg.txtRowsNumber.text()) try: self.rows = int(dlg.txtRowsNumber.text()) self.cols = int(dlg.txtColsNumber.text()) except: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Ошибка") msg.setInformativeText('Введите числовые значения') msg.setWindowTitle("Ошибка") msg.exec_() self.redrawPanels() self.init_scenario() else: print("Cancel!") def txtEditingFinished(self): self.currentSlide = int(self.txtCurSlide.text()) print(self.txtCurSlide.text()) def prevSlideClicked(self): self.currentSlide = int(self.txtCurSlide.text()) if self.currentSlide > 1: self.currentSlide -= 1 self.updateSlideNum() def nextSlideClicked(self): self.currentSlide = int(self.txtCurSlide.text()) if self.currentSlide < self.numOfSlides: self.currentSlide += 1 self.updateSlideNum() def updateNumOfSlides(self): self.lblNumOfSlides.setText(str(self.numOfSlides)) def updateSlideNum(self): self.txtCurSlide.setText(str(self.currentSlide)) #Достаем слайд из сценария и присваиваем его редактируемому слайду slideIndex = int(self.txtCurSlide.text()) - 1 slide = self.scenario.get_slide(slideIndex) if slide is not None: self.slide = slide self.slide.print() self.txtTime.setText(str(self.slide.get_timing())) for i in range(self.rows): for j in range(self.cols): self.listOfPos[i][j].setText( str(self.slide.get_position()[i][j])) self.listOfVel[i][j].setText( str(self.slide.get_velocity()[i][j])) else: print('Получен пустой слайд') def redrawPanels(self): self.listOfPos = [] self.listOfVel = [] self.lblNumOfRows.setText(str(self.rows)) self.lblNumOfCols.setText(str(self.cols)) self.clearLayout(self.positionTable) self.clearLayout(self.velocityTable) for i in range(self.rows): tP = [] tV = [] for j in range(self.cols): lableP = QLineEdit('0') # lableP.classes = "cssPanelLabel" lableP.setProperty('cssPanelLabel', 'position') lableP.setFixedSize(40, 20) lableP.editingFinished.connect( lambda: self.position_updated(i, j)) #lableP.mouseDoubleClicked.connect(lambda: self.panel_double_click(i, j, 'pos')) lableV = QLineEdit('100') lableV.setProperty('cssPanelLabel', 'velocity') lableV.setFixedSize(40, 20) lableV.editingFinished.connect(self.updatePanels) tP.append(lableP) tV.append(lableV) self.listOfPos.append(tP) self.listOfVel.append(tV) for i in range(self.rows): for j in range(self.cols): self.positionTable.addWidget(self.listOfPos[i][j], i + 1, j) self.velocityTable.addWidget(self.listOfVel[i][j], i + 1, j) self.currentSlide = 0 self.txtCurSlide.setText(str(self.currentSlide + 1)) def panel_double_click(self, row, col, panel): if panel == 'pos': self.listOfPos[row][col].setText(str(self.lastPosEntered)) def position_updated(self, row, col): self.lastPosEntered = int(self.listOfPos[row][col].text()) self.updatePanels() def init_scenario(self): position = [] velocity = [] self.scenario = Scenario() self.scenario.set_cols(self.cols) self.scenario.set_rows(self.rows) for i in range(self.rows): tP = [] tV = [] for j in range(self.cols): tP.append(0) tV.append(0) position.append(tP) velocity.append(tV) self.slide.set_timing(0) self.slide.set_position(position) self.slide.set_velocity(velocity) self.scenario.set_slide(self.slide, 0) self.lblNumOfSlides.setText(str(self.scenario.get_num_of_slides())) def setPositionClicked(self): for i in range(self.rows): for j in range(self.cols): self.listOfPos[i][j].setText(self.txtPosition.text()) self.updatePanels() def setVelocityClicked(self): for i in range(self.rows): for j in range(self.cols): self.listOfVel[i][j].setText(self.txtVelocity.text()) self.updatePanels() def updatePanels(self): print("updating panels") try: self.slide.set_timing(int(self.txtTime.text())) for i in range(self.rows): for j in range(self.cols): self.slide.position[i][j] = int( self.listOfPos[i][j].text()) self.slide.velocity[i][j] = int( self.listOfVel[i][j].text()) except: print("error in updating") currentSlideIndex = int(self.txtCurSlide.text()) - 1 self.scenario.set_slide(self.slide, currentSlideIndex) self.slide.print() def clearLayout(self, layout): while layout.count() > 0: item = layout.takeAt(0) if not item: continue w = item.widget() if w: w.deleteLater()
class App: def __init__(self): if not DEBUG: sys.stdout = None # True : GPS # False : Beacon self.mode = True self.initBtnLed() self.initGPS() self.initBLE() self.initScenario() def initBtnLed(self): # Init GPIOs GPIO.setmode(GPIO.BCM) GPIO.setup(PIN_BTN, GPIO.IN) # Tell the button is an input GPIO.setup(PIN_PWR_LED, GPIO.OUT) # Tell the led is an output # Send an high level to the 5V pin of the led GPIO.output(PIN_PWR_LED, True) # Start up the led # Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, # LED_INVERT, LED_BRIGHTNESS) self.led = Adafruit_NeoPixel(1, PIN_LED, 800000, 5, False, 100) self.led.begin() # This var is set False once the user shutdown the system self.led.active = True self.updateLed(COLOR_BOOT) def initGPS(self): self.gps = GPS() self.gps.updatePosition() self.latitude = self.gps.getLatitude() self.longitude = self.gps.getLongitude() def initBLE(self): self.actualBeacon = None self.validNewBeacon = 0 self.validNoBeacon = 0 self.ble = BLE() def initScenario(self): self.scenario = Scenario() def main(self): # Starting threads threading.Thread(target=self.checkBtn).start() threading.Thread(target=self.updateGPS).start() threading.Thread(target=self.updateBLE).start() def checkBtn(self): while True: durationPress = 0 while GPIO.input(PIN_BTN) > 0 and durationPress <= LONG_PRESS: durationPress += 0.1 time.sleep(0.1) # If it's a long press if durationPress >= LONG_PRESS: self.updateLed(COLOR_SHUTDOWN) self.led.active = False # Use subprocess instead of sys.os() to avoid the waiting of the return of the cmd subprocess.Popen(['shutdown', 'now']) # Use this instead of sys.exit() cause it will kill the thread only os._exit(1) # If it's a short press elif durationPress >= SHORT_PRESS: self.updateLed(COLOR_RESET) self.scenario.resetScenario() self.actualBeacon = None time.sleep(0.1) def updateLed(self, color): if self.led.active: # Setting the new color of the led self.led.setPixelColor(0, color) # Update the led self.led.show() def updateGPS(self): while True: time.sleep(0.5) # if no beacon is detected if self.mode: self.updateLed(COLOR_GPS) self.gps.updatePosition() _latitude = self.gps.getLatitude() _longitude = self.gps.getLongitude() # If GPS position has been found if _latitude is None or _longitude is None: self.updateLed(COLOR_NOGPS) continue # Avoid some bugs when for example longitude is -1.2983687 # and the next time is 1.2983687 if int(self.latitude) != int(_latitude) or int( self.longitude) != int(_longitude): continue self.latitude = _latitude self.longitude = _longitude print('Latitude : ', self.latitude) print('Longitude : ', self.longitude) self.scenario.calculGps(self.latitude, self.longitude) def updateBLE(self): while True: # scan(timeout in seconds, UUID) - Here b9407f30f5f8466eaff925556b57fe6d is the default Estimote UUID beaconsScanned = self.ble.scan(TIME_SCAN_BLE, 'b9407f30f5f8466eaff925556b57fe6d') if beaconsScanned: self.updateLed(COLOR_BEACON) self.mode = False self.validNoBeacon = 0 closestBeacon = None # Get the closest beacon scanned (RSSI is the power receive indice) for beacon in beaconsScanned: if not closestBeacon: closestBeacon = beacon if beacon['RSSI'] > closestBeacon['RSSI']: closestBeacon = beacon # Check if there is a new beacon is detected closer, and start a new scan to be sure if so if self.actualBeacon is not None and not closestBeacon[ 'MACADDR'] == self.actualBeacon[ 'MACADDR'] and self.validNewBeacon < 1: self.validNewBeacon += 1 print('New beacon :', closestBeacon['MACADDR'], '(', self.validNewBeacon, 'try)') continue self.actualBeacon = closestBeacon self.validNewBeacon = 0 print('-------------') print(self.actualBeacon['MACADDR'], ':') print('Major :', self.actualBeacon['MAJOR']) print('Minor :', self.actualBeacon['MINOR']) print('RSSI :', self.actualBeacon['RSSI']) # uid is the concat of major + minor in the scenario.xml uid = int( str(self.actualBeacon['MAJOR']) + str(self.actualBeacon['MINOR'])) self.scenario.calculBeacon(uid) else: # If no beacon is detected, we check 5 times to be sure if self.actualBeacon is not None and self.validNoBeacon < 5: self.validNoBeacon += 1 print('No beacon detected,', self.validNoBeacon, 'try') continue self.validNoBeacon = 0 self.actualBeacon = None self.mode = True time.sleep(0.5)
class VR(object): doexit: bool = False BUFSIZ: int = 1024 logseq: int = 0 loglimit: int = 255 isdebug: bool = False vrName: str = "" scenario: Scenario = None log: Log = None def dp(self, log): if self.isdebug: pprint(log) def __init__(self, name: str="VR", debug: bool=False): """ コンストラクタ :param name: :param debug: """ self.isdebug = debug self.vrName = name self.log = Log() self.scenario = Scenario(debug=True) def loadscenario(self, data): self.dp("VR loadscenario() ") self.scenario.read(data) def send(self, s): """ 新規入力受付時の処理。 :param s: :return: """ self.dp("VR.send(): vrName[{0}] recv: {1}".format(self.vrName, s)) ret = self.scenario.send(s) if ret.get("match", False): print("match") responseStr = "match" else: responseStr = False return responseStr def doCmd(self, key, p, args): # 動作モードの確認 action = p.get("action", "writebuffer") # exit: 即座にtelnet sessionを切断する if action == "exit": self.doexit = True # writebuffer バッファリストからデータを取得 elif action == "writebuffer": # 応答リストをfetchする liStr = p.get("res", []) # curargsにlocal変数を入れる curargs = val # curargsに「コマンドから取得した応答」を更新する curargs.update(args) # 応答文字列内の{value}を適切に変換する s = liStr[0].format(**curargs) # リストに後続がある場合はshift(pop)する # 後続がない場合はそのまま=最後の応答候補をそのまま返す if len(liStr) > 1: p["res"] = liStr[1:] self.curBuffer[key] = p # 応答を返す self.write(s) print(liStr)
class Driver: p = None #the player trend = "" #the Trending topic scen = None #the scenerio to do next """ Constructor """ def __init__(self): self.p = Player(savedPlayerJSON) #self.updatePlayer(self.p,True,0,0) if self.p.isDead(): self.p = Player("./json/newPlayerTemplate.json") self.trend = getTrend() #print self.trend self.scen = Scenario() self.scen.loadFromFile(savedScenJSON) if self.scen.finished: option = getReplies(self.p.lastID) self.followUpTweet(option) if option == 1: item = self.scen.finish1[1] exp = self.scen.finish1[2] health = self.scen.finish1[3] elif option ==2: item = self.scen.finish2[1] exp = self.scen.finish2[2] health = self.scen.finish2[3] else: item = self.scen.finish3[1] exp = self.scen.finish3[2] health = self.scen.finish3[3] self.updatePlayer(self.p,item,exp,health) tempEnviro = Environment(self.trend) tempEnviro.generateScenario(self.trend).saveScenario() self.scen = loadScenFromFile(savedScenJSON) def updatePlayer(self,player,item,exp,health): #print item , exp, health if item: player.item = Items(None) player.giveExperiencePoints(int(exp)/int(player.level)) if health>0: player.giveHealth(int(health)) else: player.removeHealth(int(health)) player.savePlayer() """ Method to post the Announce Tweet using API """ def announceTweet(self): msg = "The trend for this encounter is {}! Prepare for adventure!" msg = msg.format(self.trend) print msg #api.update_status(status = msg) time.sleep(sleepTime) """ Method to post the Scenario Tweet using API """ def scenarioTweet(self): msg = self.scen.getInitial() print msg #api.update_status(status = msg) time.sleep(sleepTime) """ Method to post the Status Tweet using API """ def statusTweet(self): msg = "You have {0.currentHealth} Health, {0.experiencePoints} XP, and are level {0.level}." if self.p.item.name != "": msg+=" You currently have the {0.item.name} Item." msg = msg.format(self.p) print msg #api.update_status(status = msg) time.sleep(sleepTime) """ Method to post the Option Tweet using API """ def optionsTweet(self): temp = self.scen.getEncounterText() msg = "" if self.scen.option1 == "Fight": msg+= "A {} attacks! ".format(self.scen.creature.getCreatureType()) msg += "Follow and reply with #1 to {0.option1}" if self.scen.option2 != "": msg+=", #2 to {0.option2}" if self.scen.option3 != "": msg+=" , or #3 to {0.option3}" msg+= "! {}".format(self.trend) msg = msg.format(self.scen) self.scen.finished = True print temp print msg api.update_status(status = temp) time.sleep(sleepTime) return api.update_status(status = msg) def followUpTweet(self, option): msg = "{}" temp = self.scen.getFinished(option)[0] msg = msg.format(temp) msg2 = " You have {0.currentHealth} Health, {0.experiencePoints} XP, and are level {0.level}." if self.p.item.name != "": msg2+=" You currently have the {0.item.name} Item." msg2 = msg2.format(self.p) msg += msg2 print msg api.update_status(status = msg) time.sleep(sleepTime)
def main(): parser = argparse.ArgumentParser(prog='TRACES GENERATOR') #abs params parser.add_argument('--providers', type=int, help="Number of local telco providers" ) parser.add_argument('--intermidiaries', type=int, help="Number of intermidiary providers" ) parser.add_argument('--calls', type=int, help="Number of calls" ) parser.add_argument('--hops', type=int, help="Numer of hops per call" ) #percentage params parser.add_argument('--fraudsters', type=float, help="Percentage of fraudolent intemidiaraies" ) parser.add_argument('--frauds', type=float, help="Percentage of fraud calls. " ) parser.add_argument('--pcoop', type=float, help="Percentage of cooperation provider " ) parser.add_argument('--icoop', type=float, help="Percentage of cooperation intermidiaries. " ) parser.add_argument('--cycles', type=int, help="Number of traces to simulate" ) parser.add_argument('--scenario', help="Name of the simulation directory" ) parser.add_argument('--useblacklist', dest='blacklist', action='store_true') parser.add_argument('--no-useblacklist', dest='blacklist', action='store_false') parser.set_defaults(blacklist=True) args = parser.parse_args() #create an istance of TraceGenerator with the params from cli scenario = Scenario(n_providers=int(args.providers), n_intermidiaries=int(args.intermidiaries), n_calls=int(args.calls), l_chain = int(args.hops), fraudsters_percentage=float(args.fraudsters), frauds_percentage=float(args.frauds), provider_participation = int(args.pcoop), intermidiaries_participation = int(args.icoop), cycles = int(args.cycles), blacklist=args.blacklist) print('\n\nstart simulation: ' + args.scenario +'\n') N = scenario.n_providers + scenario.n_intermidiaries cycles = int(args.cycles) sources = [x for x in range(0,scenario.n_providers,10)] step = 1 targets = [(x+scenario.n_providers) for x in range(0,scenario.n_intermidiaries,step)] for f in range(scenario.n_fraudsters): targets[scenario.n_intermidiaries//step-f-1] = N-f-1 results = np.zeros((cycles,len(targets))) revenues = np.zeros((3,cycles)) days=0 blacklist_history = [] for c in range(cycles): scenario_directory = 'simulation/' + args.scenario trace_file = scenario_directory + '/' + str(c) + '/traces.csv' result_file = scenario_directory + '/results/result.txt' dataset = Dataset(N, scenario_directory, c) dataset.destroy() dataset.create() if (c)%4 == 0 and scenario.use_blacklist: scenario.reset_blacklist() traceGenerator = TraceGenerator(scenario=scenario) traceGenerator.createCsv(file=trace_file) manager = TrustMan(scenario=scenario, dataset=dataset) manager.createFeedbackMatrix(infile=trace_file) manager.updateFeedbackMatrix(scenario_directory=scenario_directory, cycle=c) result = Result(scenario=scenario,dataset=dataset, manager=manager) days+=result.calcDelay() print("\n\nPERIOD: "+str(days)) print("Blacklisted operators are:") blacklist_history.append(scenario.blacklist[:]) print(scenario.blacklist) trust = TNSLA(scenario=scenario, dataset=dataset) for i in range(len(targets)): Tools.printProgress( i, len(targets)) for j in range(len(sources)): if scenario.isCoopProvider(sources[j]): results[c][i] = trust.computeTrust2(sources[j], targets[i]) #print("\nTrust from "+str(sources[j])+" to "+str(targets[i])+" at period "+str(c)+"th is "+str(results[c][i])) res = result.fraudsterClassifier2(targets[i], results[c][i]) if res and scenario.use_blacklist: #is Fraudster scenario.push_in_blacklist(targets[i]) result.printRes() scenario.revenue_termin += manager.revenue_termin scenario.revenue_transit += manager.revenue_transit scenario.revenue_fraudster += manager.revenue_fraudster revenues[0][c]=scenario.revenue_termin revenues[1][c]=scenario.revenue_transit revenues[2][c]=scenario.revenue_fraudster plot = Plot(scenario=scenario) #plot.plotDetectResult(blacklist_history, result.getFraudBehaviour()) plot.plotPie(result) '''
from GameScraper import GameScraper from Scenario import Scenario def _smallandfew(items): return items["Size"] == "Small" and items["Number of Enemies"] == "Few" def _levelover7000(items): return items["Enemy LV"] > 7000 and items["Main Object"] == "Grass" if __name__ == "__main__": from Scenario import Scenario import dolphininput import time smallandfew = Scenario(("Number of Enemies", "Size"), _smallandfew) levelover7000 = Scenario( ("Enemy LV", "Size", "Floor Number", "Main Object", "Number of Enemies", "Main Enemy", "EXP"), _levelover7000) gameScraper = GameScraper("randomdungeon", levelover7000) for i in xrange(50): gameScraper.scrape() dolphininput.tap(dolphininput.B, .1) time.sleep(.1) dolphininput.tap(dolphininput.A, .1) gameScraper.exit()
def initScenario(self): self.scenario = Scenario()
from Scenario import Scenario from DQNAgent import DQNAgent import numpy as np EPISODES = 2000 if __name__ == "__main__": env = Scenario() state_size = env.state_size action_size = env.action_size agent = DQNAgent(state_size, action_size) done = False batch_size = 32 for e in range(EPISODES): state = env.reset() print("Size: " + str(state.shape)) state = np.reshape(state, [1, state_size]) time = 0 done = 0 while not done: action = agent.act(state) next_state, reward, done = env.step(action) next_state = np.reshape(next_state, [1, state_size]) agent.remember(state, action, reward, next_state, done) state = next_state if done: agent.update_target_model() print("episode: {}/{}, score: {}, e: {:.2}" .format(e, EPISODES, time, agent.epsilon)) break time = time + 1
coreLogPath.append(Coordinate(23*3600 + 31*60 + 22.000, 3,0,0,0,0)) #23:31:22.000 coreLogPath.append(Coordinate(23*3600 + 34*60 + 22.000, 5,0,0,0,0)) #23:34:22.000 distances = list() distances.append(1.2) distances.append(5.3) distances.append(6.6) distances.append(3.3) distances.append(9.7) distances.append(2.1) distances.append(7.5) distances.append(4.3) distances.append(7.7) distances.append(5.0) scenario = Scenario(1, 5.0, '', '', '') scenario.calculateMetrics(coreLogPath, distances) print 'Overall Results' print 'Start Time: ', scenario.timeToString(scenario.totalResult.startTime) #expected: 230000.000 print 'End Time: ', scenario.timeToString(scenario.totalResult.endTime) #expected: 233422.000 print 'Detection percent: ', scenario.totalResult.detectionPercent, '%' #expected: 100% print 'ID changes: ', scenario.totalResult.idChanges #expected: 9 print 'Min distance', scenario.totalResult.minPositonalAccuracy #expected: 1.2 print 'Max distance', scenario.totalResult.maxPositionalAccuracy #expected: 9.7 print 'Average postional Accuracy', scenario.totalResult.averagePositionalAccuracy #expected: 5.27 print 'Percent within ', scenario.maxRadius, 'm: ', scenario.totalResult.percentWithinMaxRadius, '%' #expected: 50% #20 minute segments print '\nNumber of 20 minute segments: ', len(scenario.twentyMinuteResults) for i in range(0, len(scenario.twentyMinuteResults)): #expected: two 20 minute segments
contents_per_slot_per_user = OrderedDict() rzs_per_slot_per_user = OrderedDict() contact_len_mean = OrderedDict() contact_mean = OrderedDict() nodes_in_zoi = OrderedDict() probabilities = OrderedDict() c = 1 # Slot number a_per_content = OrderedDict() replicas = OrderedDict() a_per_content_only_value = OrderedDict() num_users = density_users num_zois = density_zois # CREATION OF SCENARIO With num_zois number of zois scenario = Scenario(radius_of_replication, max_area, delta, radius_of_tx, channel_rate, num_users, num_zois, traces_folder, num_slots, algorithm, max_memory, max_time_elapsed, gamma, statis, alp) # From here on, start printing out to an external file called 'out' orig_stdout = sys.stdout f = open('results/' + str(uid) + '/out.txt', 'w') sys.stdout = f ################## Parse traces in case we are using them if "Paderborn" in traces_folder: scenario.parsePaderbornTraces(traces_folder, traces_file) if traces_folder == "Rome": scenario.parseRomaTraces(traces_folder, traces_file) if traces_folder == "SanFrancisco":
usr_list = [] # list of users in the entire scenario availabilities_list_per_slot = [] nodes_in_zoi = OrderedDict() attempts = [] a_per_model = OrderedDict() a_per_obs = OrderedDict() models_contributions = OrderedDict() models_freshness = OrderedDict() nodes_future = OrderedDict() c = 1 # CREATION OF SCENARIO scenario = Scenario(radius_of_interest, radius_of_replication, max_area, min_speed, max_speed, delta, radius_of_tx, channel_rate, num_users, num_zois, traces_folder, num_slots, list_of_static_nodes, computing_time, num_landmarks, merging_time) scenario.max_memory = num_models * model_size ################## Parse traces in case we are using them if traces_folder == "Rome": scenario.parseRomaTraces(traces_folder, traces_file) if traces_folder == "Luxembourg": scenario.parseLuxembourgTraces(traces_folder, traces_file) if traces_folder == "none": for i in range(0, scenario.num_users): user = User(i, np.random.uniform(-max_area, max_area), np.random.uniform(-max_area, max_area), scenario, num_models_node * model_size) scenario.usr_list.append(user)
from Verifier import SPRT from Property import MCIProperty '''Input generation''' fireFighterPr = 0.8 numOfFireFighters = 3 CSs = [FireFighter(str(i), fireFighterPr) for i in range(numOfFireFighters)] mapSize = 20 MCIMap = [0 for i in range(mapSize)] MCISoS = SoS(CSs, MCIMap) MCIEvents = [] numOfPatients = 20 for i in range(numOfPatients): MCIEvents.append( Event(PatientOccurrence('patient +1', MCIMap), ConstantTimeBound(0))) MCIScenario = Scenario(MCIEvents) '''Simulation''' simulationTime = 15 MCISim = Simulator(simulationTime, MCISoS, MCIScenario) repeatSim = 2000 MCILogs = [] for i in range(repeatSim): MCILog = MCISim.run() MCILogs.append(MCILog) ''' print('log print (only last log)') for log in MCILogs: print(log[-1], sum(log[-1][0]), sum(log[-1][1])) ''' '''
response = Response_Node( "because that is the solution we have been looking for", questions, [], 4) responses.append(response) questions = [] questions.append('What would you see as the ideal solution?') questions.append('What is the best solution in your eyes') questions.append('What would you like the outcome to be?') neighbors = [] neighbors.append(response) response = Response_Node("The ideal solution", questions, neighbors, 5) responses.append(response) questions = [] questions.append('why') response = Response_Node("because it is", questions, [], 6) responses.append(response) questions = [] questions.append('what color is the sky') questions.append('is the color of the sky green?') neighbors = [] neighbors.append(response) response = Response_Node("the sky is blue", questions, neighbors, 7) responses.append(response) dialog = Dialog(responses) scenario = Scenario("mike", "test description", None, dialog) db.add_scenario(scenario)
def __init__(self, board): self.board = board self.scenarios = [Scenario(board, [], "", 0)] self.scenarios[0].update_figures(board)