def start(): app = Flask(__name__) display = Display() viz = visualize.Visualizer() @app.route('/display/<string:name>', methods=['POST']) def show(name): img = cv2.imdecode(numpy.frombuffer(request.get_data(), dtype='uint8'), cv2.IMREAD_COLOR) display.push((name, img)) return flask.make_response("", HTTPStatus.NO_CONTENT) @app.route('/display', methods=['POST']) def show_root(): img = cv2.imdecode(numpy.frombuffer(request.get_data(), dtype='uint8'), cv2.IMREAD_COLOR) display.push(('', img)) return flask.make_response("", HTTPStatus.NO_CONTENT) @app.route('/visualize/<string:name>', methods=['POST']) def visualize_face(name): data = json.loads(request.form['result']) img_buf = request.files['image'] img = cv2.imdecode(numpy.frombuffer(img_buf.read(), dtype='uint8'), cv2.IMREAD_COLOR) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) viz.add(name, video_width=img.shape[1], video_height=img.shape[0]*1.5, panel_count=3) viz.push_data(name, image=img, info=data) return flask.make_response("", HTTPStatus.NO_CONTENT) @app.route('/static/<path:path>') def serve_static(path): return flask.send_from_directory('static', path) app.run(host='0.0.0.0', port=9555)
def visualizeRun(boardingStrategy): # strategies = ['random', 'backFirst', 'frontFirst'] p = { 'planeType': Plane, 'passengerType': DefaultPassenger, 'boardingStrategy': boardingStrategy } sim = Simulator(params=p) viz = visualize.Visualizer(sim) res = sim.run() # print(res) print('time needed for {} strategy was {}:{}'.format( boardingStrategy, *toMinutesAndSeconds(res)))
def saveDotFile(self, queryName, rootID, blackSet, redSet=None): # Create DOT-file visualizer = visualize.Visualizer(self.connector, self.noDetails) dotFile = visualizer.generateDotFile(blackSet, redSet) # Print DOT-file to user defined file if self.filename is not None: query = open(self.filename + str(rootID) + queryName + ".dot", "w") query.write(dotFile) query.close() # Print DOT-file to std-out else: print(dotFile)
def watch(self, repeat_count=1): self.robot.x = self.initial_state[0] self.human.x = self.initial_state[1] if self.viewer is None: self.viewer = visualize.Visualizer(0.1, magnify=1.2) self.viewer.main_car = self.robot self.viewer.use_world(self.world) self.viewer.paused = True for _ in range(repeat_count): self.viewer.run_modified( history_x=[self.robot_history_x, self.human_history_x], history_u=[self.robot_history_u, self.human_history_u]) self.viewer.window.close() self.viewer = None
mode='markers') t4 = go.Scatter(x=test.df[ratio_mask].index, y=test.df[ratio_mask]['GHI'], name='NN', mode='markers') t5 = go.Scatter(x=test.df[both_mask].index, y=test.df[both_mask]['GHI'], name='Both', mode='markers') iplot([t1, t2, t3, t4, t5]) # In[64]: cm = metrics.confusion_matrix(test.df['sky_status'], pred) vis = visualize.Visualizer() vis.plot_confusion_matrix(cm, labels=['cloudy', 'clear']) # In[ ]: ground = cs_detection.ClearskyDetection.read_pickle('abq_ground_1.pkl.gz', 'MST') # ground.df.index = ground.df.index.tz_convert('MST') test = cs_detection.ClearskyDetection(ground.df, 'MST') # In[ ]: test.df['tfn'].plot() # In[71]:
th.config.allow_gc = False if __name__ == '__main__': name = sys.argv[1] if len(sys.argv) > 2 and sys.argv[2] == 'fast': th.config.optimizer = 'fast_compile' if len(sys.argv) > 2 and sys.argv[2] == 'FAST': th.config.mode = 'FAST_COMPILE' world_to_use = getattr(world, name)() if len(sys.argv) > 3 or (len(sys.argv) > 2 and sys.argv[2] not in ['fast', 'FAST']): ctrl = eval(sys.argv[-1]) for car in world.cars: if isinstance(car, UserControlledCar): print 'User Car' car.fix_control(ctrl) vis = visualize.Visualizer(0.1, name=name) vis.use_world(world_to_use) vis.main_car = world_to_use.cars[0] vis.run() del vis del world_to_use #gc.collect() print("HERE!") world_to_use = getattr(world, name)() vis = visualize.Visualizer(0.1, name=name) vis.use_world(world_to_use) vis.main_car = world_to_use.cars[0] vis.run() print("HERE AGAIN!")
if __name__ == "__main__": field_size = (30, 30) generation_size = 10 surviver_count = 5 #the amount of fittest selected to breed the next generation child_per_survivor = generation_size // surviver_count mutation = 1 generation = 1 generations = [] for i in range(generation_size): game = snake.Game( field_size, snake.Snake(snake.Vector(14, 14), snake.Vector.UP, 3)) model = ai.create_model(field_size) generations.append((model, game)) vis = visualize.Visualizer((600, 450), "Snake", 5, (255, 0, 0), (0, 255, 0)) last_update = 0 update_frequency = 200 max_ticks = 50 tick_count = 0 dead = 0 while vis.running: vis.begin_frame() for i in range(len(generations)): #display fields x = i % 4 y = i // 4 vis.draw_field(generations[i][1].field, (x * field_size[0] * 5, y * field_size[1] * 5)) vis.end_frame()
frame_dir_suffix += '/' if args.save_interaction_data_dir is not None: frame_dir = (constants.INTERACTION_DATA_DIR + args.save_interaction_data_dir + frame_dir_suffix) elif args.load_interaction_data_dir is not None: frame_dir = (constants.INTERACTION_DATA_DIR + args.load_interaction_data_dir + frame_dir_suffix) # create visualizer vis = visualize.Visualizer(this_world, dt=constants.DT, name=this_world.name, iters=iters, save_interaction_data=save_interaction_data_dir is not None, save_interaction_data_dir=save_interaction_data_dir, save_frames=args.save_frames, frame_dir=frame_dir, manual=args.manual, plan_show=args.plan, heatmap_show=args.heatmap is not None, heatmap_name=args.heatmap, heat_val_show=args.heat_val_show) vis.main_car = this_world.main_human_car # Start the simulation if args.no_vis: print('Starting simulation without visualization.') cont = True # if True, continue the control loop while cont: cont = vis.control_loop() else:
world.cars.append( car.Car(dyn, [0., 0.1, math.pi / 2. + math.pi / 5, 0.], color='yellow')) world.cars.append( car.Car(dyn, [-0.13, 0.2, math.pi / 2. - math.pi / 5, 0.], color='yellow')) world.cars.append( car.Car(dyn, [0.13, -0.2, math.pi / 2., 0.], color='yellow')) #world.cars.append(car.NestedOptimizerCar(dyn, [0.0, 0.5, math.pi/2., 0.3], color='yellow')) return world if __name__ == '__main__': world = playground() #world.cars = world.cars[:0] vis = visualize.Visualizer(0.1, magnify=1.2) vis.main_car = None vis.use_world(world) vis.paused = True @feature.feature def zero(t, x, u): return 0. r = zero #for lane in world.lanes: # r = r+lane.gaussian() #for fence in world.fences: # r = r-3.*fence.gaussian() r = r - world.cars[0].linear.gaussian() #vis.visible_cars = [world.cars[0]]
clf = ensemble.RandomForestClassifier(**these_params, n_jobs=-1) # In[109]: clf.fit(X_train, y_train) # # Test on ground data # ## SRRL ground = cs_detection.ClearskyDetection.read_pickle('srrl_ground_1.pkl.gz')ground.df.index = ground.df.index.tz_convert('MST')ground.trim_dates('10-01-2011', '10-08-2011')ground.scale_model('GHI', 'Clearsky GHI pvlib', 'sky_status pvlib')ground.time_from_solar_noon('Clearsky GHI pvlib', 'tfn') ground.scale_by_irrad('Clearsky GHI pvlib')test = groundpred = test.iter_predict_daily(feature_cols, 'GHI', 'Clearsky GHI pvlib', clf, 61, by_day=True, multiproc=True) pred = pred.astype(bool)vis = visualize.Visualizer()vis.add_line_ser(test.df['GHI'], 'GHI') vis.add_line_ser(test.df['Clearsky GHI pvlib'], 'GHI_cs') vis.add_circle_ser(test.df[(test.df['sky_status pvlib'] == 0) & (pred)]['GHI'], 'ML clear only') vis.add_circle_ser(test.df[(test.df['sky_status pvlib'] == 1) & (~pred)]['GHI'], 'PVLib clear only') vis.add_circle_ser(test.df[(test.df['sky_status pvlib'] == 1) & (pred)]['GHI'], 'ML+PVLib clear only') # vis.add_line_ser(test.df['abs_ideal_ratio_diff'] * 100)vis.show()probas = clf.predict_proba(test.df[feature_cols].values) test.df['probas'] = 0 test.df['probas'] = probas[:, 1] visualize.plot_ts_slider_highligther(test.df, prob='probas') # In[64]: ground = cs_detection.ClearskyDetection.read_pickle('srrl_ground_1.pkl.gz') # In[65]:
train.df['sky_status_km'] = 0 train.df['sky_status_km'] = kmeans.labels_ pd.unique(train.df['sky_status_km'])train.df['sky_status_km'] = (train.df['sky_status_km'] == 0) | (train.df['sky_status_km'] == 0) x = train.df.index trace1 = go.Scatter(x=x, y=train.df['GHI']) trace2 = go.Scatter(x=x, y=train.df['Clearsky GHI pvlib']) # trace3 = go.Scatter(x=train.df[train.df['sky_status']].index, # y=train.df[train.df['sky_status']]['GHI'], name='NSRBD', mode='markers') trace3 = go.Scatter(x=train.df[train.df['sky_status'] & ~train.df['sky_status_km']].index, y=train.df[train.df['sky_status'] & ~train.df['sky_status_km']]['GHI'], name='NSRBD', mode='markers') trace4 = go.Scatter(x=train.df[~train.df['sky_status'] & train.df['sky_status_km']].index, y=train.df[~train.df['sky_status'] & train.df['sky_status_km']]['GHI'], name='km', mode='markers') trace5 = go.Scatter(x=train.df[train.df['sky_status'] & train.df['sky_status_km']].index, y=train.df[train.df['sky_status'] & train.df['sky_status_km']]['GHI'], name='both', mode='markers') iplot([trace1, trace2, trace3, trace4, trace5])vis = visualize.Visualizer() vis.plot_corr_matrix(train.df[feature_cols].corr(), feature_cols) # In[9]: train = cs_detection.ClearskyDetection(nsrdb.df, scale_col=None) train.trim_dates(None, '01-01-2015') test = cs_detection.ClearskyDetection(nsrdb.df, scale_col=None) test.trim_dates('01-01-2015', None) # In[10]: utils.calc_all_window_metrics(train.df, 3, meas_col='GHI', model_col='Clearsky GHI pvlib', overwrite=True) clf.fit(train.df[feature_cols].values, train.df[target_cols].values.flatten())
def main(): args = parse_args() # Set the GPU to use torch.cuda.set_device(args.gpu) transform = transforms.Compose([ transforms.Resize(256), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) vqa_loader = dataset.get_train_dataloader(osp.expanduser(args.annotations), osp.expanduser(args.questions), args.images, args, raw_images=args.raw_images, transforms=transform) # We always use the vocab from the training set vocab = vqa_loader.dataset.vocab maps = { "vocab": vocab, "word_to_wid": vqa_loader.dataset.word_to_wid, "wid_to_word": vqa_loader.dataset.wid_to_word, "ans_to_aid": vqa_loader.dataset.ans_to_aid, "aid_to_ans": vqa_loader.dataset.aid_to_ans, } val_transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) val_loader = dataset.get_val_dataloader(osp.expanduser( args.val_annotations), osp.expanduser(args.val_questions), args.val_images, args, raw_images=args.raw_images, maps=maps, vocab=vocab, shuffle=False, transforms=val_transform) arch = Models[args.arch].value model = arch(len(vocab), output_dim=args.top_answer_limit, raw_images=args.raw_images) if args.resume: state = torch.load(args.resume) model.load_state_dict(state["model"]) model.cuda() criterion = nn.CrossEntropyLoss().cuda() optimizer = optim.Adam(model.parameters(), lr=args.lr, betas=tuple(args.betas), weight_decay=args.weight_decay) scheduler = lr_scheduler.StepLR(optimizer, step_size=args.decay_interval, gamma=args.lr_decay) if args.visualize: vis = visualize.Visualizer(args.port) else: vis = None print("Beginning training") print("#" * 80) for epoch in range(args.start_epoch, args.epochs): scheduler.step() trainer.train(model, vqa_loader, criterion, optimizer, epoch, args, vis=vis) trainer.evaluate(model, val_loader, criterion, epoch, args, vis=vis) print("Training complete!")
model = fcnn.build(val_ds.num_classes) stream = fake_stream() if not os.path.exists("model.h5"): model.fit_generator(stream, steps_per_epoch=200, epochs=1) model.save_weights("model.h5") else: model.load_weights("model.h5") x, y = next(stream) pred = model.predict(x) vis = visualize.Visualizer(val_ds.num_classes) for xx, yy, pp in zip(x, y, pred): image = cv2.cvtColor((xx * 255).astype("uint8"), cv2.COLOR_BGR2RGB) gt = vis.colorify_mask(xx, yy) dt = vis.colorify_mask(xx, pp) fig, (l, r) = plt.subplots(1, 2, figsize=(9, 6)) l.imshow(image) l.imshow(gt, alpha=0.5) r.imshow(image) r.imshow(dt, alpha=0.5) l.set_title("Ground Truth") r.set_title("Detection")
by_day=False) pred = train.iter_predict_daily(feature_cols, 'GHI', 'Clearsky GHI pvlib', clf, 3, multiproc=True, by_day=True) # In[35]: probas = clf.predict_proba(train.df[feature_cols].values) # In[36]: vis = visualize.Visualizer() vis.add_line_ser(train.df['GHI']) vis.add_line_ser(train.df['Clearsky GHI pvlib']) vis.add_circle_ser(train.df[pred]['GHI']) vis.add_line(train.df.index, probas[:, 1] * 1000, label='prob') vis.show() # In[37]: test_pred = test.iter_predict_daily(feature_cols, 'GHI', 'Clearsky GHI pvlib', clf, 3, multiproc=True, by_day=True).astype(bool)
name = "world6" name = "world_kex" #name = "irl_ground" #name = sys.argv[1] # if len(sys.argv)>2 and sys.argv[2]=='fast': # th.config.optimizer = 'fast_compile' # if len(sys.argv)>2 and sys.argv[2]=='FAST': # th.config.mode = 'FAST_COMPILE' world = getattr(world, name)() # if len(sys.argv)>3 or (len(sys.argv)>2 and sys.argv[2] not in ['fast', 'FAST']): # ctrl = eval(sys.argv[-1]) # for car in world.cars: # if isinstance(car, UserControlledCar): # print 'User Car' # car.fix_control(ctrl) vis = visualize.Visualizer(1.0, name=name) vis.use_world(world) vis.main_car = world.cars[0] vis.run() if __name__ == '__main__1': name = sys.argv[1] if len(sys.argv) > 2 and sys.argv[2] == 'fast': th.config.optimizer = 'fast_compile' if len(sys.argv) > 2 and sys.argv[2] == 'FAST': th.config.mode = 'FAST_COMPILE' world = getattr(world, name)() if len(sys.argv) > 3 or (len(sys.argv) > 2 and sys.argv[2] not in ['fast', 'FAST']): ctrl = eval(sys.argv[-1]) for car in world.cars:
def main(): args = parse_args() # Set the GPU to use torch.cuda.set_device(args.gpu) annotations = osp.expanduser(args.annotations) questions = osp.expanduser(args.questions) vqa_loader = dataset.get_train_dataloader(annotations, questions, args.images, args) # We always use the vocab from the training set vocab = vqa_loader.dataset.vocab maps = { "word_to_wid": vqa_loader.dataset.word_to_wid, "wid_to_word": vqa_loader.dataset.wid_to_word, "ans_to_aid": vqa_loader.dataset.ans_to_aid, "aid_to_ans": vqa_loader.dataset.aid_to_ans, } val_loader = dataset.get_val_dataloader(osp.expanduser( args.val_annotations), osp.expanduser(args.val_questions), args.val_images, args, maps=maps, vocab=vocab, shuffle=False) arch = Models[args.arch].value model = arch(len(vocab), output_dim=args.top_answer_limit) if torch.cuda.is_available(): model.cuda() criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=args.lr, betas=tuple(args.betas), weight_decay=args.weight_decay) scheduler = lr_scheduler.StepLR(optimizer, step_size=args.decay_interval, gamma=args.lr_decay) vis = visualize.Visualizer(args.port) print("Beginning training") print("#" * 80) for epoch in range(args.start_epoch, args.epochs): scheduler.step() trainer.train(model, vqa_loader, criterion, optimizer, epoch, args, vis=vis) trainer.evaluate(model, val_loader, criterion, epoch, args, vis=vis) print("Training complete!")
def __init__(self, music_path, sample_rate, frame_rate, least_energy, pin_list, response_time, speed=2, on_tft=False, screen=None): keyboard.key_initiate(pin_list) self.pin_list = pin_list self.frame_rate = frame_rate self.time_interval = 1.0 / frame_rate self.least_energy = least_energy self.sample_rate = sample_rate self.music_path = music_path self.visualizer = visualize.Visualizer( music_path, int(speed * frame_rate * response_time), speed, on_tft, screen) stats_file = "{}.npz".format(os.path.splitext(music_path)[0]) # if the music has not been processed before if not os.path.isfile(stats_file): print("Loading Essentia module...") import essentia.standard as ess_std print("Loading music...") loader = ess_std.MonoLoader(filename=music_path) audio = loader() pool = multiprocessing.Pool() num_process = multiprocessing.cpu_count() segment_length = int(len(audio) / num_process) / 1024 * 1024 onset_collector = [] self.num_frames = len(audio) print("Calculating onsets...") processing_start = time() results = [None] * num_process for i in range(num_process): results[i] = pool.apply_async( detect_onset, args=(audio[segment_length * i:min(segment_length * (i + 1), len(audio))], i)) pool.close() pool.join() for i in range(num_process): onsets = results[i].get( ) + i * float(segment_length) / self.sample_rate onset_collector += onsets.tolist() onset_collector.append( np.finfo(float).max ) # so that read_onset will never reach len(self.onsets) self.onsets = np.array(onset_collector) print("Onset detection finished. Elapsed time: {:.2f}s".format( time() - processing_start)) np.savez(os.path.splitext(music_path)[0], num_frames=np.array([self.num_frames]), onsets=self.onsets) else: stats = np.load(stats_file) self.num_frames = stats["num_frames"][0] self.onsets = stats["onsets"] print("Pre-processing skipped")
clf.fit(train.df[feature_cols], train.df[target_cols]) # In[11]: pred = clf.predict(test.df[feature_cols]).flatten() # In[12]: cm = metrics.confusion_matrix(test.df['sky_status'].values, pred) vis = visualize.Visualizer() vis.plot_confusion_matrix(cm, labels=['cloudy', 'clear']) # In[13]: vis = visualize.Visualizer() # In[14]: vis.add_line_ser(test.df['GHI'], 'GHI') vis.add_line_ser(test.df['Clearsky GHI'], 'GHI_cs') vis.add_circle_ser(test.df[(test.df['sky_status'] == 1) & (~pred)]['GHI'], 'NSRDB only')
# In[5]: ground.trim_dates('01-01-2009', '02-01-2009') # # Measured vs modeled values # ## NSRDB # In[6]: vis = visualize.Visualizer() # In[7]: vis.add_line_ser(nsrdb.df['GHI'], 'GHI') vis.add_line_ser(nsrdb.df['Clearsky GHI'], 'Clearsky GHI') vis.add_line_ser(nsrdb.df['Clearsky GHI pvlib'], 'Clearsky GHI pvlib') # vis.add_line_ser(nsrdb.df['Clearsky GHI stat'], 'Clearsky GHI stat') vis.add_circle_ser(nsrdb.df[nsrdb.df['sky_status'] == 1]['GHI'], 'NSRDB clear') # In[8]:
lr_decay_epoch = set(config.lr_decay_epoch) lr_decay = config.lr_decay epoch = config.epoch batch_size = config.batch_size use_cuda = net.use_cuda if use_cuda: net = net.cuda() learning_rate = 0.01 optimizer = optim.SGD(net.parameters(), lr=learning_rate, momentum=0.9) visualizer = visualize.Visualizer('AudioNet') prev_loss_list = PrevLoss() prev_loss = float('inf') for e in range(epoch): need_save = False start_time = time.time() net.train() train_dataset = utils.Dataset(root, train_df, input_length, num_class=num_class, label_dct=label_dct) test_dataset = utils.Dataset(root, test_df, input_length,
for tx in range(T): for sx in range(S): image = visualizer.getImageAt(tx,sx) saveBinaryImage(image,patient_id,original_dir,sx,tx) print "Saved all binary images for patient: {}".format(patient_id) # Details if event.key == 'd': print "Slice, Time : ({},{})".format(s,t) array_img = getBinaryImages(patient_id, original_dir) print "Patient: {}".format(patient_id) visualizer = vz.Visualizer(array_img) visualizer.connect('motion_notify_event',cursor) visualizer.connect('button_press_event',click) visualizer.connect('key_press_event',press) visualizer.show()