def main(): plotter = Plotter() print("read polygon.csv") read_polygon() # get the input point print("Insert point information") x = float(input("x coordinate: ")) y = float(input("y coordinate: ")) point=[x,y,'location'] print("categorize point") mbr() #Classify the test points outside and inside the MBR. xmax = mbr()[0][0] xmin = mbr()[0][1] ymax = mbr()[1][0] ymin = mbr()[1][2] if x< xmin or x > xmax or y < ymin or y > ymax: point[2] = 'outside' else: point[2] = 'inside' # Classfily all the points outside,inside and on the boundary point_polygon = read_polygon()[1:] crosstime = 0 for n in range(len(point_polygon[0]) - 1): x1 = point_polygon[0][n] y1 = point_polygon[1][n] x2 = point_polygon[0][n + 1] y2 = point_polygon[1][n + 1] # check whether the point coincides with the vertex of the polygon if y1 == y2 == y and x1 == x2 == x: point[2] = 'boundary' elif (x1 == x and y == y1) or (x2 == x and y2 == y): point[2] = 'boundary' # check whether the point is on horizontal segments elif x == x1 == x2 and (y1 < y < y2 or y2 < y < y1): point[2] = 'boundary' # check whether the point is on vertical segments elif y == y1 == y2 and (x1 < x < x2 or x2 < x < x1): point[2] = 'boundary' # check the common situation elif y1 <= y < y2 or y2 <= y < y1: inter = (y - y1) * (x2 - x1) / (y2 - y1) + x1 if inter == x: point[2] = 'boundary' elif inter > x: crosstime += 1 if crosstime % 2 == 0 and point[2] != 'boundary': point[2] = 'outside' elif crosstime % 2 != 0 and point[2] != 'boundary': point[2] == 'inside' #draw polygon and points print("plot polygon and point") m = mbr() p = read_polygon() plotter.add_polygon(p[1], p[2]) plt.plot(m[0], m[1]) plotter.add_point(x,y,point[2]) plotter.show()
def main(self, cities=['austin']): print('!# Begin') for city in cities: print('! ' + city.capitalize()) print('! Read flow') here = Here() traffic_flow = here.read_flow(city) print('! Format flow') formatted_flow, info_flow = here.format_flow(traffic_flow) print('! Read network') osm = OSM() road_network = osm.read_network(city) if not osm.verify_correlated(city): print('! Correlate') osm.correlate(formatted_flow, road_network, city) print('! Read ids') #ids_mapped, ids_sumo = osm.read_id_file() mapped = osm.read_mapped(city) plotter = Plotter() for folder in os.listdir('./routing/flows/{0}'.format(city)): if not 'scenario' in folder: for file in os.listdir('./routing/flows/{0}/{1}'.format( city, folder)): print('! Read here files') print('! File: {0}'.format(file)) traffic_flow = here.read_flow( city, file_name='{0}/{1}'.format(folder, file)) formatted_flow, info_flow = here.format_flow( traffic_flow) print('! Plot map') # plotter.plot_map(formatted_flow, file_name='flow') # plotter.plot_map(road_network, file_name='network') # plotter.plot_overlap_map(formatted_flow, road_network, file_name='overlap') # plotter.plot_map(formatted_flow, file_name='consider_flow', consider=ids_mapped) # plotter.plot_map(road_network, file_name='consider_network', consider=ids_sumo) plotter.plot_info_traffic(road_network, info_flow, mapped, city, folder, file_name=file.split('.')[0]) print('!# End')
def qjump_once(*args, **kwargs): dirname = make_results_dir(kwargs.get("dir", DEFAULT_RESULTS_DIR)) kwargs["dir"] = dirname update_qjump_args(kwargs) log_arguments(*args, **kwargs) ping_times = qjump(*args, **kwargs) if ping_times: plotter = Plotter() plotter.plotCDF(ping_times, dir=dirname, figname="pingCDF") print("Results saved to " + dirname)
def plot_graph(self, index): gpx = self.get_gpx(index) points = gpx.track.track_segment plot = Plotter(points) result = plot.setup() if result: plot.plot() else: self.show_warning("Нехватает данных о высоте!")
def create_csv_file(self): csv_name = CSVCreation(self.layers).output_csv() plt = Plotter(csv_name) png_name = plt.getLayers() self.lb = QLabel(self) pixmap = QPixmap(png_name) self.lb.resize(300, 500) self.lb.setPixmap(pixmap.scaled(self.lb.size(), Qt.IgnoreAspectRatio)) self.lb.move(self.width()/2, self.height()/2) self.show()
def test_13_use_colors_instead_of_colormap_stacked_bar(self): image_filename = get_filename_from_frame(inspect.currentframe()) my_plot = Plotter(self.data['bar-data']) my_plot.stacked_bar( x_column='year', y_column='quantity', y_labels='product_name', title='Stacked bars example', colors=['red', 'blue', 'yellow', 'magenta', 'gray']) my_plot.save(image_filename)
def main(): transforms = load_transforms() titles = ['Barnsley', 'von Koch'] N = [3000, 2000] for transform, title, n in zip(transforms, titles, N): xy = ifs(0, 0, transform, n) plotter = Plotter(xy, title, incr=20) savepath = get_savepath(title) plotter.animate(savepath)
def main(): thread = threading.Thread(target=recv_package) thread.start() ### Leer cuantos sensores hay conectados para poder realizar el handshake(malloc mágico) ### Crear barrera con contador = cuantos sensores hay ### Crear cola para cada thread ### Crear semaforo para cada cola de rocolectores ### Crear threads recolectores (se envía de parámetro su cola y su identificador respectivo) #abre el archivo csv en modo lectura interface_queue = queue.Queue(queue_size) collectors = Collectors() collectors_info = collectors.initializer(interface_queue) memoryManager = MemoryManager() plotter = Plotter() #Por cuestiones de comodidad se inicializa acá pero no se usa posteriormente. interface = Interface() #plotter.initializer(interface) interface.initializer(interface_queue, collectors_info, memoryManager, plotter) while True: with open('identificadores.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') next(csv_reader) next(csv_reader) semaphore.acquire() #cierra el mutex, saca el paquete respectivo de la cola, y lo vuelve a abrir lock.acquire package = packet_queue.get() lock.release #Si hubo un timeout, el servidor termina su ejecución; si no, imprime el paquete. timeout = package[5] if (timeout == 0): #Multiplexor: Envia el paquete a su cola correspondiente #print(package) for line in collectors_info: plot_data = [package[0], package[4]] #print(plot_data) """print(line[0], package[1]) print(line[1], package[2]) print(line[2], package[3])""" if (line[0] == package[1] and line[2] == package[2] and line[1] == package[3]): #print("entre") line[4].acquire() line[3].put(plot_data) line[4].notify() line[4].release() else: print("cliente caido") break
def __init__(self, master, UDP_conn_gui, UDP_conn_plot): print("Init Plotter") self.plotter = Plotter() pandas.read_csv("obstacles_100m_above_sea_level.csv").to_numpy() obstacles = coordinate_convertions.obstacles_ex( pandas.read_csv("obstacles_100m_above_sea_level.csv").to_numpy()) m_line = LineString([(config.start_pos.x, config.start_pos.y), (config.goal_pos.x, config.goal_pos.y)]) self.plotter.plot_static(obstacles=obstacles, m_line=m_line) print("Init GUI") self.UDP_conn_gui = UDP_conn_gui # UDP connection object self.UDP_conn_plot = UDP_conn_plot self.master = master self.master.geometry('400x250') self.master.title("Drone GUI") self.master.bind("<q>", self.q_pressed) self.master.bind("<t>", self.t_pressed) # always on top self.always_on_top = tk.IntVar() self.always_on_top.set(1) self.master.wm_attributes("-topmost", 1) # Add GUI elements # Add quit button tk.Button(self.master, text="Quit <q>", command=self.quit_all).grid(row=0, column=0, pady=0, sticky="W") # Add always on top checkbox tk.Checkbutton(self.master, text="Always on top <t>", variable=self.always_on_top, command=self.always_on_top_toggle).grid(row=1, column=0, pady=0, sticky="W") # Add status self.status_text = tk.StringVar() # Create new StringVar self.status_text.set( "waiting for status update") # Update the StringVar (label's) text # Create the lable itself and assign a text self.label = tk.Label(master=self.master, textvariable=self.status_text, font="Consolas 20", anchor="w", justify=tk.LEFT) self.label.grid(row=2, column=0, sticky="W") self.master.after(10, self.get_new_status_msg)
def main(): colors = 'bgcmy' pltr = Plotter() # obstacles = [1,1,(5,4)] obstacles = [] print "Case 1: A-star" time = Time(0.01) robot_1 = Robot(1, [2, 2, 0], [8, 6, 0], colors[0]) robot_2 = Robot(2, [8, 2, 0], [2, 6, 0], colors[1]) # robot_1 = Robot(1, [5, 9, 0], [5, 1, 0], colors[1]) # robot_2 = Robot(2, [1, 6, 0], [7, 6, 0], colors[2]) my_world = World([robot_1, robot_2], time, obstacles) plan(my_world, pltr, "a-star") # execute_with_collision(my_world) execute_wo_collision(my_world) print '----------------\n' del robot_1 del robot_2 del my_world pltr = Plotter() print "Case 2: RRT" time = Time(0.01) robot_1 = Robot(1, [2, 2, 0], [8, 6, 0], colors[0]) robot_2 = Robot(2, [8, 2, 0], [2, 6, 0], colors[1]) # robot_1 = Robot(1, [5, 9, 0], [5, 1, 0], colors[1]) # robot_2 = Robot(2, [1, 6, 0], [7, 6, 0], colors[2]) my_world = World([robot_1, robot_2], time, obstacles) plan(my_world, pltr, "rrt") # execute_with_collision(my_world) execute_wo_collision(my_world)
def __init__(self): self.interval = 0.5 # seconds self.case_count = 500 self.candle_group_count = 6 self.time_before_after_bk_candle = 30000 # milliseconds self.threshold = 0.0005 self.period = 5 self.scraper = SqueezeScraper() self.analyser = Analyzer() self.plotter = Plotter()
def main(): plotter = Plotter() print("read polygon.csv") print("Insert point information") x = float(input("x coordinate: ")) y = float(input("y coordinate: ")) print("categorize point") print("plot polygon and point") plotter.show()
def on_graphClicked(self, row, col): print "graph clicked", row, col #check if is a valid spot if col is not 3: return found = False for k, s in sensors.items(): for c, pos in zip(s["canales"], range(len(s["canales"]))): #Check if clicked row is on of the stored rows if c["counterPos"][0] == row: self.p = Plotter(self.conn, k, s, pos) break
def main(): plotter = Plotter() print("read polygon.csv") print("read input.csv") print("categorize points") print("write output.csv") print("plot polygon and points") plotter.show()
def test_15_a_figure_with_a_lot_of_subplots(self): image_filename = get_filename_from_frame(inspect.currentframe()) my_plot = Plotter(self.data['bar-data'], rows=2, cols=2) my_plot.linear(ignore=['product_name', 'year'], title='Linear plot') my_plot.scatter(x_column='quantity', title='Scatter plot') my_plot.stacked_bar(x_column='year', y_column='quantity', y_labels='product_name', title='Stacked bars plot', x_rotation=45) my_plot.bar(count='year', x_rotation=45, title='Bar plot') my_plot.save(image_filename)
def execute(start, end, units): clients = {"binance": Binance(), "bitmex": Bitmex()} data = {} for unit in units: exchange = unit["exchange"] market = unit["market"] client = clients[exchange] trades = client.get_trades_for_period(symbol=market, start_time=start, end_time=end) data[f"{exchange}_{market}"] = (client.get_price_dataset(trades)) Plotter().plot(data)
def pwm_raw(): raw = Plotter("pwm_output_09_02/N=100-no_optoswitch09_feb.txt") plt.rcParams.update({'font.size': 20}) plt.title("Pi PWM board raw output") plt.xlabel("Duty cycle [%]") plt.ylabel("Voltage [V]") plt.plot(raw.x(), 3.3 * raw.y() / 2**15, "bo-") plt.legend(loc=1) plt.show()
def pwm_low(): raw = Plotter("optoswitch_output_16_02/100_16_02_0.txt") plt.rcParams.update({'font.size': 20}) plt.title("Average smoother circuit output, input 3.9V") plt.xlabel("Duty cycle [%]") plt.ylabel("Voltage [V]") plt.plot(raw.x(), raw.y(), "go-") plt.legend(loc=1) plt.show()
def setUp(self): self.plotter = Plotter() self.functions = ['', 'x', 'log(x)', '1+x^2+x^3', '1/x', 'tan(x)', 'exp(1/x)', '0', '4', 'abs(x)']
def __init__(self, ui_file, parent=None): super(DiceRoller, self).__init__(parent) #load ui file ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) loader = QUiLoader() self.window = loader.load(ui_file) ui_file.close() #startup self.plotter = Plotter(parent=self) self.window.mainLayout.addWidget(self.plotter) self.setup_ui() self.window.show()
def __init__(self, export=False, exportMiser=False, exportDir=None): """ Initialize visualization :param export: bool Export figures or not? (exports in .emf via inkscape, modify function if need be) :param exportMiser: bool Export png images or not? (It's a trap...) :param exportDir: str Export directory """ self.export = export self.exportMiser = exportMiser self.exportDir = exportDir if export or exportMiser: self.plotter = Plotter()
def algorithm(self, operand): data = [] # bias x y out if operand == 'AND': data = [[1.0, 1.0, 1.0, 1.0], [1.0, -1.0, 1.0, -1.0], [1.0, 1.0, -1.0, -1.0], [1.0, -1.0, -1.0, -1.0]] elif operand == 'XOR': data = [[1.0, 1.0, 1.0, -1.0], [1.0, -1.0, 1.0, 1.0], [1.0, 1.0, -1.0, 1.0], [1.0, -1.0, -1.0, -1.0]] weights = np.random.rand(len(data[0]) - 1, 1) error_min = len(data) * 2 error_this_epoch = 1 w_min = weights error_per_epoch = [] plotter = Plotter() for epoch in range(self.iterations): # COTA del ppt if error_this_epoch > 0: total_error = 0 #if (epoch % 100 == 0): # weights = np.random.rand(len(data[0]) - 1, 1) for i in range( len(data)): # tamano del conjunto de entrenamiento sumatoria = self.get_sum( data[i][:-1], weights ) # dame toda la fila menos el ultimo elemento => x_i => x0, x1, x2, ... activation = self.get_activation(sumatoria) error = data[i][ -1] - activation # y(1,i_x) - activacion del ppt fixed_diff = self.alpha * error for j in range(len(weights)): weights[j] = weights[j] + (fixed_diff * data[i][j]) total_error += error**2 error_this_epoch = self.error_function(total_error) error_per_epoch.append(error_this_epoch) if self.adaptive and epoch % 10 == 0: self.adjust_learning_rate(error_per_epoch) if error_this_epoch < error_min: error_min = error_this_epoch w_min = weights else: break print('Linear data post analysis:') print('epochs: {}'.format(epoch + 1)) print('Initial alpha: {}'.format(self.initial_alpha)) print('End alpha: {}'.format(self.alpha)) print('Best ever error: {}'.format(error_min)) if len(w_min) != 0 or w_min != None: plotter.create_plot_ej1(data, w_min, operand) else: plotter.create_plot_ej1(data, weights, operand) return
def prep_video(data_dict, batch_size, device): train_dl = torch.utils.data.DataLoader(SyntheticCalciumVideoDataset(traces= data_dict['train_fluor'], cells=data_dict['cells'], device=device), batch_size=args.batch_size) valid_dl = torch.utils.data.DataLoader(SyntheticCalciumVideoDataset(traces= data_dict['valid_fluor'], cells=data_dict['cells'], device=device), batch_size=args.batch_size) num_trials, num_steps, num_cells = data_dict['train_fluor'].shape num_cells, width, height = data_dict['cells'].shape input_dims = (num_steps, width, height) TIME = torch._np.arange(0, num_steps*data_dict['dt'], data_dict['dt']) train_truth = {} if 'train_latent' in data_dict.keys(): train_truth['latent'] = data_dict['train_latent'] valid_truth = {} if 'valid_latent' in data_dict.keys(): valid_truth['latent'] = data_dict['valid_latent'] plotter = {'train' : Plotter(time=TIME, truth=train_truth), 'valid' : Plotter(time=TIME, truth=valid_truth)} return train_dl, valid_dl, input_size, plotter
def main(): config = "end" num = 5 remove_peg = 11 examples = make_state_space() default_state_space = examples[num] a = Plotter('fig/remove_peg' + str(remove_peg) + '_' + config + '_state_' + str(num) + '.png') action_space = ActionSpace(default_state_space) end_state = action_space.remove_convex(default_state_space, remove_peg) if config == "end": a.plot(end_state) else: a.plot(default_start_state)
def plot_result(self, plot_style, data_to_plot_index_list=None, data_labels_index=None, latex=False): to_plot = self.get_to_plot(plot_style, data_to_plot_index_list, data_labels_index) if to_plot != None: cmap = plt.cm.YlOrRd cmap = plt.get_cmap("autumn_r") pl = Plotter([to_plot], cmap=cmap, latex=latex) pl.show() else: print( "Error: unable to generate something to plot in plot_result()")
def Main(): rows = 4 cols = 2 fig, ax_array = plt.subplots(rows, cols, sharey='row', sharex='col') # dataname = 'sarmad_t0,012_complete' dataname = 'axisdata_t0,5_20088' # dataname = 'axisdata_t0,1_7296' # dataname = 'axisdata_t0,5_9576' rsDataPath = '../../rs-testscenario/trajectories/' + dataname + '.json' rsSolvedPath = '../../rs-testscenario/trajectories/' + dataname + '_solved.json' plotter_raw.plotter_raw(ax_array, rsDataPath, 0) Plotter(ax_array).plot_optimized(rsSolvedPath, 1) plt.show()
def main(): logging.basicConfig( format='[%(asctime)s][%(levelname)s] %(name)s: %(message)s', level=logging.INFO) client = StreamClient('wss://localhost:10000/websocket') recorder = Recorder() plotter = Plotter() printer = Printer() recorder.add_recording_listener(client) recorder.add_recording_listener(plotter) client.add_decoding_listener(printer) recorder.record() tornado.ioloop.IOLoop.current().start()
def main(): """ Main function which automatically draws some plots. This can be used as an entry point for a python package later on. """ # Paths where the output files are located. # test_outputs2 is fictive, I only changed the total energy by one order # with respect to test_outputs to quickly test the functionality. paths = ["test_outputs/best_su_best_tm/", "test_outputs2/best_su_best_tm/"] # Instantiate a plotter object plotter = Plotter(paths[0]) # Call the three energy plots of varying detail plotter.plot_design_space(paths)
def main(): time = Time(0.01) colors = 'bgrcmyk' pltr = Plotter() robot_1 = Robot(1, [2, 2, 0], [8, 6, 0], colors[0]) robot_2 = Robot(2, [8, 2, 0], [2, 6, 0], colors[1]) # robot_1 = Robot(1, [5, 8, 0], [4, 4, 0], colors[0]) # robot_2 = Robot(2, [1, 6, 0], [7, 6, 0], colors[1]) my_world = World([robot_1, robot_2], time) plan(my_world, pltr) execute_with_collision(my_world)
def newDataset(self, path, dsIndex): dsHandle = ServerHandle(self.dvName, self, isListening=False) yield dsHandle('cd', path) fullPath, name = yield dsHandle('open', dsIndex) plotter = Plotter(name, fullPath, dsHandle, self) plotter.initDefer.addCallback(lambda _: plotter.show()) plotter.initDefer.addErrback(self.catchError) delTimer = QtCore.QTimer(self) delTimer.setSingleShot(True) delTimer.setInterval(cacheTime) plotter.finished.connect(lambda result: delTimer.start()) delTimer.timeout.connect(plotter.deleteLater) self.datasets[(tuple(path), dsIndex)] = plotter, delTimer delTimer.timeout.connect(lambda: self.datasets.pop( (tuple(path), dsIndex)))