def __init__(self, maze_dim): ''' Use the initialization function to set up attributes that your robot will use to learn and navigate the maze. Some initial attributes are provided based on common information, including the size of the maze the robot is placed in. ''' self.heading = start_heading self.maze_dim = maze_dim self.map = Map(self.maze_dim) self.start = start self.location = self.start self.goal = [[maze_dim - 1, maze_dim - 1]] self.goal_changed = False self.finishing = False self.finish_count = len(self.goal) self.values = [[99 for row in range(self.maze_dim)] for col in range(self.maze_dim)] self.record = [] self.run = 1 self.step = 0 self.path = [] self.path_previous = [] self.goto_start = False self.shortest = [] self.shortest_previous = [] # drawing if ifdraw: self.draw = Visual(maze_dim)
def cloud(bot, update, args): st = Stats() c = st.get_counter(st, update.message.chat_id) c = st.delete_stops(st, c) vs = Visual() image = vs.cloud(vs, dict(c), args[0]) bot.send_photo(update.message.chat_id, photo=image)
def __init__(self, args): np.random.seed(int(time.time())) self.store = Store() self.visual = Visual(self.store) self.image_shape = [28, 28, 1] # 28x28 pixels and black white self.batch_size = args.batch_size self.lr = args.learning_rate self.train_epoch = args.train_epoch self.dropout_keep_probability = tf.placeholder("float") self.mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=[]) self.is_training = tf.placeholder(dtype=tf.bool) self.x = tf.placeholder(tf.float32, shape=(None, 64, 64, 1), name="X_Input") self.z = tf.placeholder(tf.float32, shape=(None, 1, 1, 100), name="Z") self.G_z = define_generator(self.z, self.is_training) D_real, D_real_logits = define_discriminator(self.x, self.is_training) D_fake, D_fake_logits = define_discriminator(self.G_z, self.is_training, reuse=True) D_loss_real = init_loss(D_real_logits, tf.ones, self.batch_size) D_loss_fake = init_loss(D_fake_logits, tf.zeros, self.batch_size) self.G_loss = init_loss(D_fake_logits, tf.ones, self.batch_size) self.D_loss = D_loss_real + D_loss_fake self.sess = None
def f(screen): def g(screen): return HighScores(self.screen, self.father, self.total_points) music.play_gameover() return Visual(screen, [utils.load_image(GAMEOVER)], [3], g)
def f(screen): def g(screen): return HighScores(self.screen, self.father, self.total_points) music.play_music(WINMUSIC) return Visual(screen, utils.load_image(WIN), -1, g)
def describe_all(bot, update): st = Stats() c = st.get_counter(st, update.message.chat_id) vs = Visual() image1 = vs.word_dist(vs, c) bot.send_photo(update.message.chat_id, photo=image1) image2 = vs.word_lens(vs, c) bot.send_photo(update.message.chat_id, photo=image2)
def __init__(self): self.root= Tkinter.Tk() self.vis= Visual(self.root) self.relief= Relief() self.figure= None self.stand_latter= False self.root.after_idle(self.tick) self.root.bind('<KeyPress>', self.press_key) self.root.mainloop()
def charts(): translate = Translate() words_to_translate = request.args['words'] count_words = translate.count_words(words_to_translate) words = translate.sort_words(count_words) visual = Visual(dict_words=words, file_name="line") return render_template('chart.html', title='Analysis', chart=visual.mkPie())
def __init__(self, dim_x=30, dim_y=30, initial_pos=(3, 3), final_pos=(25, 25), n_population=100, dead_turn=120): self.map = Map(dim_x, dim_y, initial_pos, final_pos, n_population, dead_turn) self.v = Visual() self.dim_x = dim_x self.dim_y = dim_x
def describe_word(bot, update, word): st = Stats() c = st.get_counter(st, update.message.chat_id) vs = Visual() image1 = vs.word_rank(vs, c, word) bot.send_photo(update.message.chat_id, photo=image1) text = 'Most common words after {}\n'.format(word) words_n = st.words_near(st, update.message.chat_id, word) for i, item in enumerate(words_n): a, b = item text += '{}. {} {}\n'.format(i, a, b) update.message.reply_text(text) d = st.dist_by_sentence(st, update.message.chat_id, word) image2 = vs.dist_by_sentence(vs, d, word) bot.send_photo(update.message.chat_id, photo=image2)
def index(): """Homepage.""" results_dict = dd.disaster_dict() visual = Visual(results_dict) visual_dict = visual.create("state", "incident", "date") us_plot_div = visual_dict["us_plot_div"] incident_plot_div = visual_dict["incident_plot_div"] time_plot_div = visual_dict["time_plot_div"] return render_template("index.html", states=dd.get_categories("state"), incidents=dd.get_categories("incidentType"), us_map=Markup(us_plot_div), incident_map=Markup(incident_plot_div), time_map=Markup(time_plot_div), states_counties=results_dict["state_county"])
def get_search_results(): """Get search results.""" state = request.args.get("state") incident = request.args.get("incident") start_date = request.args.get("start_date") end_date = request.args.get("end_date") results_dict = dd.disaster_dict(state=state, incident_type=incident, start_date=start_date, end_date=end_date) visual = Visual(results_dict) visual_dict = visual.create("state", "incident", "date") us_plot_div = visual_dict["us_plot_div"] incident_plot_div = visual_dict["incident_plot_div"] time_plot_div = visual_dict["time_plot_div"] return render_template("index.html", states=dd.get_categories("state"), incidents=dd.get_categories("incidentType"), us_map=Markup(us_plot_div), incident_map=Markup(incident_plot_div), time_map=Markup(time_plot_div), states_counties=results_dict["state_county"])
def main(): #Initialize pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption(WINDOW_TITLE) icon = utils.load_image(ICON, (0,0,0)) pygame.display.set_icon(icon) #Introduction images = [utils.load_image(image) for image in INTRO_IMAGES] visual = Visual(screen, images, INTRO_TIMES) music.play_music(INTROMUSIC, 1) visual.loop() music.stop_music() #Shooter opcion opcion = menu while opcion is not exit: change = opcion(screen).loop() if change: opcion = change opcion() #Exit
def __init__(self): self.activeObjects = [] self.dimentions = (1200, 600) # (640, 480) self.game = game.Game('Fran y Manu', self.dimentions) self.activeObjects.append(self.game.createThorman()) self.visual = Visual(self.dimentions, self.game) self.loadImages() self.mapArray = [] self.collisions = [] self.thormanMoving = True self.firstFlip = True # --------- THREADS ----------- self.bombsTimeThread = bombsThread.bombTimeCounter(daemon=True) self.bombsThreadRun = threading.Thread(target=self.bombsTimeThread.run) self.bombsThreadRun.start() self.explotionNumber = 0 self.bombsExplotionThreadList = [] self.thormanStandingThreadRun = thormanStandingThread.standingStill( daemon=True) self.thormanStandingThreadRun.start() self.thormanStandingThreadStarted = False # ----------------------------- dispatcher.connect(receiver=self.explodeBomb, signal='Exploded', sender='bombsThread') dispatcher.connect(receiver=self.reloadExplotionSprite, signal='Change Explotion Sprite', sender='bombsExplotionThread') dispatcher.connect(receiver=self.delExplotionSprite, signal="Delete Explotion", sender='bombsExplotionThread') dispatcher.connect(receiver=self.reloadThorman, signal="Stand Still", sender='thormanStandingThread') dispatcher.connect(receiver=self.flip, signal='Finished') self.mainLoop() self.bombs = None
import sys from visual import Visual from main_loop import run_example vis = Visual(True) # Commands to be implemented after running this file if __name__ == "__main__": delay = None episodes = 111 #grid = [(4, 5), (3, 3), [(2, 4)]] grid = [(10, 12)] stop_at_goal = False for a in sys.argv[1:]: if a == '-h' or a == '--help': print( '\nusage: python(3) main.py [delay=d][episodes=e][grid=RxC]\n') sys.exit() if a == '-s' or a == '--stop': stop_at_goal = True continue opt, val = a.split('=') if opt == '-d' or opt == '--delay': delay = float(val) if opt == '-e' or opt == '--episodes': episodes = int(val) if opt == '-g' or opt == '--grid': grid = [tuple(map(int, val.split('x')))] run_example(grid, episodes, vis=vis)
def story(screen): bg = utils.load_image(STORYBG) text = utils.load_image(STORY, (0,0,0)) bg.blit(text, (0,0)) return Visual(screen, bg, -1, menu)
def help(screen): bg = utils.load_image(HELPBG) text = utils.load_image(HELP, (0,0,0)) bg.blit(text, (0,0)) return Visual(screen, bg, -1, menu)
def __init__(self, screen, father, level, total_points): self.screen = screen self.father = father self.level = level self.background = utils.load_image(levels[level]['background']) #parameters self.energy_leap = levels[level]['energy_leap'] self.mold_density = levels[level]['mold_density'] self.mold_velocity = levels[level]['mold_velocity'] self.max_time = levels[level]['max_time'] #menu control self.options = [("Yes", self.father), ("No", None)] self.exit = False #Create the game clock self.clock = pygame.time.Clock() self.mm = MoldsManager(self.mold_density, self.mold_velocity) self.bm = BottleManager(*levels[self.level]['bottle_density']) self.bm.mm = self.mm self.total_points = total_points self.pointsCounter = Points(self.total_points) self.levelIndicator = LevelIndicator(self.level) self.mm.level = self self.tics = 0 self.snow_slim = pygame.sprite.Group() self.snow_fat = pygame.sprite.Group() for x in range(75): sprite = Wheather(1, 2) self.snow_slim.add(sprite) for x in range(75): sprite = Wheather(3, 5) self.snow_fat.add(sprite) self.energy_bar = EnergyBar(self.energy_leap) self.bm.energy_bar = self.energy_bar self.mm.energy_bar = self.energy_bar self.level_time = LevelTime(self.max_time) self.gadgets = pygame.sprite.RenderUpdates() self.gadgets.add(self.pointsCounter) self.gadgets.add(self.energy_bar) self.gadgets.add(self.level_time) self.gadgets.add(self.levelIndicator) self.hero = Hero() self.bm.hero = self.hero self.mm.hero = self.hero self.explotion = Explotion() self.control_down = -1 self.control_up = -1 self.control_left = -1 self.control_right = -1 self.control_tiempo = 5 self.next_scream = random.randrange(400, 500) #Show level image Visual(self.screen, [utils.load_image(levels[self.level]['img'])], [2], None).loop()
print('\n', '*' * 50, '\n') ####################################################### def make_dir(_dir): """ make directory if doesn't exist param _dir: directory string """ if not os.path.exists(_dir): os.mkdir(_dir) # Program driver if __name__ == '__main__': make_dir(db_dir) make_dir(anim_dir) if solve: sv = Solver(db_dir, db_name, table, drop, t, R, t0, tf, dt) sv.propogate() sv.close() if visualise: vz = Visual(db_dir, db_name, table, anim_dir, save_anim) if solve and drop: sv.db.drop()
yy) #string lab for addressing each crossroad, xx ~ [1,grid_x] #Initialization cross_ = crossing(car_nums=np.array([0, 0, 0, 0]), light_state=0, q_states=q_states[xx][yy]) cross[lab] = cross_ return cross step_set = [] reward_set = [] if args.train: #Initializing cross = crossroads_map(x, y) visual = Visual() obs = [] for xx in x: for yy in y: lab = str(xx) + str(yy) obs = np.concatenate( (obs, cross[lab].car_nums, cross[lab].light_state), axis=None) #Training steps for steps in range(200000): visual.visual_before(cross, x, y, times, b, bias, bias_t) action = RL.choose_action(obs) action_set = [[0 for i in range(grid_y + 1)] for j in range(grid_x + 1)]
def main(doc, gui, opcao, id_jogador, tela): print('Chaves Logicas') Jogo(doc, Visual(doc, gui, opcao, tela), opcao, id_jogador, tela)
def visualize(): """ Visualize route """ if request.method == "GET": choose_data = config.get_datafiles() return render_template("visualize.html", choose_data=choose_data) elif request.method == "POST": try: shutil.rmtree("static/visualize") print(">>> Removed folder: visualized") except Exception as e: print("No such folder: ", e) data_for_timeline = collections.OrderedDict() month_names = [] hotspots = [] hotspot = {} conflevel = request.form["setupConfidenceLevel"] months = calendar.month_name dates = [ "", "2014-01", "2014-02", "2014-03", "2014-04", "2014-05", "2014-06", "2014-07", "2014-08", "2014-09", "2014-10", "2014-11", "2014-12" ] empty_hotspots = [] splitted_months = functions.split_csv(request.form["setupData"]) for mon in range(1, 13): hotspot = Visual(request.form["setupData"], months[mon], conflevel, units) hotspot.getis, hotspot.conf_levels = functions.calculate_hotspot( hotspot, splitted_months[mon - 1]["data"], "getis") data_for_timeline[months[mon]] = hotspot.getis functions.save_csv(hotspot.getis, "static/visualize/", hotspot.title, ".csv") # Creates the getis hotspot getis_hotspot = functions.create_hotspot(hotspot, "getis_visual", hotspot.pvalue) # Save getis hotspot as png functions.save_figure(getis_hotspot, "static/visualize/", hotspot.title, ".png") month_names.append(months[mon]) # hotspots.append(hotspot) # Timeline takes a list of dataFrames timeline = Timeline(data_for_timeline) timeline.calculate_total() timeline.calculate_percentage() timeline_result = timeline.create_timeline() functions.save_figure(timeline_result, "static/visualize/", "timeline", ".png") return render_template("visualize.html", months=month_names, csvfile=request.form["setupData"], conf=conflevel, time="?" + str(time.time()))
top_mean_feats(X, features, None, 0.1, 10)) #Data classification: #Applying Mini-KMeans because the dataset is large. clf = MiniBatchKMeans(n_clusters=3, init_size=1000, batch_size=500, max_iter=100) clf.fit(X) labels = clf.fit_predict(X) #Data visualisation: #Graphs by calling class Visual. dv = Visual(X, labels, features, clf) dv.raw_plot() dv.cluster_plot() dv.bargraph() #Insights: print( "\nThe names PHILLIP and JOHN have come up numerous times, and thus it can be assumed that they had a strong relation with the workings of the company, and thus might have known about/orchestrated the fraud.\n" ) #Querying on the insights: print("Querying Phillip:\n") #Instantiating class EmailData.
def _store_game_parameters(game_params): controllers = game_params["controllers"] controller_parameters = ( controllers["rocket_active_controller"], controllers["turret_active_controller"], controllers["rocket_raise_errors"], controllers["turret_raise_errors"], controllers["rocket_check_execution_time"], controllers["turret_check_execution_time"], ) visual = game_params["visual"] visual_obj = Visual( visual["fps"], visual["barrel_length_turret_radius_ratio"], visual["rocket_length_engine_bridge_width_ratio"], visual["rocket_length_max_thrust_length_ratio"], visual["thrust_cone_angle"], visual["game_over_alpha"], visual["default_title"], visual["rocket_colour"], visual["thrust_cone_colour"], visual["turret_colour"], visual["projectile_colour"], visual["obstacle_colour"], visual["not_ready2fire_colour"], visual["ready2fire_colour"], ) environment = game_params["environment"] obstacles = ([ ObstacleParameters(Coordinate(obstacle["location"]), obstacle["radius"]) for obstacle in environment["obstacles"] ] if environment["obstacles"] else []) environment_obj = EnvironmentParameters(environment["width"], environment["height"], obstacles) time = game_params["time"] time_obj = TimeParameters(time["timestep"], time["max_game_time"]) rocket_params = game_params["rocket"] rocket_params_obj = RocketParameters( rocket_params["mass"], rocket_params["length"], rocket_params["max_main_engine_force"], rocket_params["max_thruster_force"], ) turret_params = game_params["turret"] turret_location = Coordinate(turret_params["location"]) turret_params_obj = TurretParameters( turret_params["radius"], turret_location, turret_params["max_rotation_speed"], turret_params["projectile_speed"], turret_params["min_firing_interval"], ) parameters = Parameters(environment_obj, time_obj, rocket_params_obj, turret_params_obj) rocket_history_obj = RocketHistory( [Coordinate(rocket_params["start_location"])], [rocket_params["start_angle"]]) turret_history_obj = TurretHistory([turret_params["start_angle"]]) history = History(rocket_history_obj, turret_history_obj) return controller_parameters, visual_obj, parameters, history
def main(): svm_params = dict(svm_type=cv2.SVM_C_SVC, kernel_type=cv2.SVM_LINEAR, degree=None, gamma=5.383, C=1) # Creates visual platrorm vis = Visual() # User input ################################################################ ans = '1' # raw_input("Would like to create model (1) or to view outputs (2) : ") if ans == '1': print "Reading data set : " raw_img, raw_lbl = MyMnist.read() print "Done \n" lbl_img = zip(raw_lbl, raw_img) lbl_img = shuffle(lbl_img) raw_lbl = np.asarray([t[0] for t in lbl_img]) raw_img = np.asarray([t[1] for t in lbl_img]).reshape( (raw_lbl.size, config.height * config.width)) print "Now lets start training : \n" # User input ################################################################ is_hog = 'y' # raw_input("Would you like to use Hog (y/n) : ") if (is_hog == 'y'): hog_scale_w = int(raw_input("What width would you like to use : ")) hog_scale_h = int( raw_input("What height would you like to use : ")) hog_degrees = int( raw_input("What amount of degrees would you like to use : ")) hog_data = np.zeros([ raw_lbl.size, config.height * config.width / hog_scale_h / hog_scale_w * hog_degrees ], 'float32') for i in range(0, raw_lbl.size): hog_data[i] = Hog.getimghog( raw_img[i].reshape((config.height, config.width)), [[1, 0, -1], [2, 0, -1], [1, 0, -1]], [[1, 2, 1], [0, 0, 0], [-1, -2, -1]], hog_scale_h, hog_scale_w, hog_degrees) raw_img = hog_data # User input ################################################################ out = 2 # int(raw_input("Would you like to use Linear (1) or Kernel (2) :")) svm_params['C'] = float(raw_input("Please enter C parameter : ")) if out == 1: svm_params['kernel_type'] = cv2.SVM_LINEAR else: svm_params['kernel_type'] = cv2.SVM_POLY svm_params['degree'] = int( 2) # float(raw_input("Please enter SVM degree parameter : ")) svm_params['gamma'] = float(raw_input("Please enter gamma : ")) name = "HOG " + str(hog_scale_h) + "x" + str(hog_scale_w) + " d" + str( hog_degrees) + " C" + str(svm_params['C']) + " G" + str( svm_params['gamma'] ) #raw_input("How would you like to name your model : ") step = int(round(raw_lbl.size * 0.1)) - 1 test_lbls = list() pred_lbls = list() for i in range(0, 10): print "Start " + str(i) + " training ", train_img = np.concatenate((raw_img[:i, :], raw_img[i + step:, :])) train_lbl = np.append(raw_lbl[:i], raw_lbl[i + step:]) test_img = raw_img[i:i + step, :] test_lbl = raw_lbl[i:i + step] test_lbls.append(test_lbl) svm = cv2.SVM() svm.train(train_img, train_lbl, params=svm_params) print "=> Predicting", pred_lbls.append(svm.predict_all(test_img)) print "=> Done" s = SvmOutput(name, svm_params, svm, np.array(test_lbls).ravel(), np.array(pred_lbls).ravel()) s.save() s.showdata() else: ans = raw_input( "Would you like to view a specific model (1) \nor the roc curve of a few models (2) :" ) models_dir = os.walk(config.default_path).next()[1] if ans == '1': print "Available models : " for i in range(1, len(models_dir) + 1): print "\t(" + str(i) + ") " + models_dir[i - 1] ans = int(raw_input("Which model would you like to view : ")) model = SvmOutput(name=models_dir[ans - 1], readfile=True) model.showdata() else: roc_models = list() ans = 'y' while (ans == 'y') & (len(models_dir) > 0): print "Available models : " for i in range(1, len(models_dir) + 1): print "\t(" + str(i) + ") " + models_dir[i - 1] model_add = int( raw_input("Which model would you like to view : ")) roc_models.append( SvmOutput(name=models_dir[model_add - 1], readfile=True)) ans = raw_input( "Would you like to choose another model (y/n) : ") models_dir.pop(model_add - 1) vis.showROC(roc_models)