def test_scaled_apertures(self): """Test envelope_tool.plotter scaled apertures""" option = [{ "variable_type": 3, "first_var": 1, "plot_apertures": False }] canvas = ROOT.TCanvas("c", "d") my_plot = plotter.Plotter(option, canvas, [], [], self.field_list) self.assertEqual(len(my_plot.x_var), 0) self.assertEqual(len(my_plot.y_var), 0) option = [{"variable_type": 3, "first_var": 1, "plot_apertures": True}] my_plot = plotter.Plotter(option, canvas, [], [], self.field_list) self.assertEqual(len(my_plot.x_var), 2) self.assertEqual(len(my_plot.y_var), 2) my_plot = plotter.Plotter(option, canvas, [0.], [0.], self.field_list) self.assertEqual(len(my_plot.x_var), 2) self.assertEqual(len(my_plot.y_var), 2) self._test_graph(my_plot.x_var[0], [6.0, 15.0, 18.0, 6.0, 6.0]) self._test_graph(my_plot.x_var[1], [1.5, 10.5, 12.5, -0.5, 1.5]) for i in [0, 1]: self.assertAlmostEqual(my_plot.y_var[i][0], my_plot.y_var[i][1]) self.assertGreater(my_plot.y_var[i][2], my_plot.y_var[i][1]) self.assertAlmostEqual(my_plot.y_var[i][2], my_plot.y_var[i][3]) self.assertAlmostEqual(my_plot.y_var[i][0], my_plot.y_var[i][4])
def getGraph(df): KText = e1.get() if(len(KText)>0 and len(e4.get())==0 and len(e5.get())==0): if(len(e2.get())>0): csvUtils = cu.CSVUtilities() tupleToPrint = csvUtils.getTupleToPrint(df) cabeceras = csvUtils.getHeaders(df) minValue = csvUtils.getMin(df) maxValue = csvUtils.getMax(df) tags = csvUtils.getTags(df) K = int(e1.get()) step = float(e2.get()) plotter = msg.Plotter() plotter.plotKnnGraphic(*tupleToPrint, K=K, minValue=minValue, maxValue=maxValue, step=step, etiquetas=tags, x_label=cabeceras[0], y_label=cabeceras[1]) else: toplevel = Toplevel() label1 = Label(toplevel, text='Ocurrio un error', height=0, width=50) label1.pack() label2 = Label(toplevel, text='Debe ingresar el valor del Step', height=0, width=50) label2.pack() elif(int(e4.get())<=int(e5.get()) and len(e1.get())==0): if(len(e2.get())>0): aux=[] for k in range(int(e4.get()),int(e5.get())+1): csvUtils = cu.CSVUtilities() tupleToPrint = csvUtils.getTupleToPrint(df) cabeceras = csvUtils.getHeaders(df) minValue = csvUtils.getMin(df) maxValue = csvUtils.getMax(df) tags = csvUtils.getTags(df) K = int(k) step = float(e2.get()) plotter = msg.Plotter() Kk=K minValue=minValue maxValue=maxValue step=step etiquetas=tags x_label=cabeceras[0] y_label=cabeceras[1] aux.append([*tupleToPrint, Kk, minValue, maxValue, step, etiquetas, x_label, y_label,int(e4.get()),int(e5.get()),len(tags)]) plotter.variasGraficas(aux) else: toplevel = Toplevel() label1 = Label(toplevel, text='Ocurrio un error', height=0, width=50) label1.pack() label2 = Label(toplevel, text='Debe ingresar el valor del Step', height=0, width=50) label2.pack() else: toplevel = Toplevel() label1 = Label(toplevel, text='Ocurrio un error', height=0, width=50) label1.pack() label2 = Label(toplevel, text='Recuerde ingresar el K, o si usa Rangos, no ingrese el valor de K individual', height=0, width=100) label2.pack()
def averager(imgpaths, dest_filename=None, width=500, height=600, background='black', blur_edges=False, out_filename='result.png', plot=False): size = (height, width) images = [] point_set = [] for path in imgpaths: img, points = load_image_points(path, size) if img is not None: images.append(img) point_set.append(points) if len(images) == 0: raise FileNotFoundError('Could not find any valid work.' + ' Supported formats are .jpg, .png, .jpeg') if dest_filename is not None: dest_img, dest_points = load_image_points(dest_filename, size) if dest_img is None or dest_points is None: raise Exception('No face or detected face points in dest img: ' + dest_filename) else: dest_img = np.zeros(images[0].shape, np.uint8) dest_points = locator.average_points(point_set) num_images = len(images) result_images = np.zeros(images[0].shape, np.float32) for i in range(num_images): result_images += warper.warp_image(images[i], point_set[i], dest_points, size, np.float32) result_image = np.uint8(result_images / num_images) face_indexes = np.nonzero(result_image) dest_img[face_indexes] = result_image[face_indexes] mask = blender.mask_from_points(size, dest_points) if blur_edges: blur_radius = 10 mask = cv2.blur(mask, (blur_radius, blur_radius)) if background in ('transparent', 'average'): dest_img = np.dstack((dest_img, mask)) if background == 'average': average_background = locator.average_points(images) dest_img = blender.overlay_image(dest_img, mask, average_background) print('Averaged {} work'.format(num_images)) plt = plotter.Plotter(plot, num_images=1, out_filename=out_filename) plt.save(dest_img) plt.plot_one(dest_img) plt.show()
def morph(name, src_img, src_points, dest_img, dest_points, width=500, height=600, num_frames=20, fps=10, out_frames=None, plot=False, background='black'): """ Create a morph sequence from source to destination image :param src_img: ndarray source image :param src_points: source image array of x,y face points :param dest_img: ndarray destination image :param dest_points: destination image array of x,y face points :param video: facemorpher.videoer.Video object """ size = (height, width) stall_frames = np.clip(int(fps*0.15), 1, fps) # Show first & last longer plt = plotter.Plotter(plot, num_images=num_frames, out_folder=out_frames) num_frames -= (stall_frames * 2) # No need to process src and dest image plt.plot_one(src_img) # Produce morph frames! percent = np.linspace(1, 0, num=num_frames) points = locator.weighted_average_points(src_points, dest_points, percent[8]) src_face = warper.warp_image(src_img, src_points, points, size) end_face = warper.warp_image(dest_img, dest_points, points, size) average_face = blender.weighted_average(src_face, end_face, percent[8]) if background in ('transparent', 'average'): mask = blender.mask_from_points(average_face.shape[:2], points) average_face = np.dstack((average_face, mask)) if background == 'average': average_background = blender.weighted_average(src_img, dest_img, percent[8]) average_face = blender.overlay_image(average_face, mask, average_background) #plt.plot_one(average_face) #name = src_img[-11:-4]+"_"+dest_img[-11:-4]+".png" plt.save(average_face,name)
def __init__(self, getter, initial_resolution=1024): self.renderer = renderer.Renderer( initial_resolution=initial_resolution) self.renderer.show_fps = True self.getter = getter self.game_is_in_interpolating_mode = False self.saved_first_index_selected = -1 self.saved_second_index_selected = -1 self.counter_start = 0 self.latent_vector_size = 512 self.saved_already = 0 self.keep_p1 = False # special case for v0b self.toggle_save_frames_in_loop = False # network hacking self.multiplier_value = 1.0 self.target_tensor = 0 ##self.target_tensors = ["16x16/Conv0_up/weight", "32x32/Conv0_up/weight", "64x64/Conv0_up/weight", "128x128/Conv0_up/weight", "256x256/Conv0_up/weight"] self.target_tensors = [ "16x16/Conv0/weight", "32x32/Conv0/weight", "64x64/Conv0/weight", "128x128/Conv0/weight", "256x256/Conv0/weight" ] # << Pre-trained PGGAN has these self.convolutional_layer_reconnection_strength = 0.3 # plotting: self.plotter = plotter.Plotter(self.renderer, getter)
def morph(src_img, src_points, dest_img, dest_points, video, width=500, height=600, num_frames=20, fps=10, out_frames=None, out_video=None, alpha=False, plot=False): """ Create a morph sequence from source to destination image :param src_img: ndarray source image :param src_img: source image array of x,y face points :param dest_img: ndarray destination image :param dest_img: destination image array of x,y face points :param video: facemorpher.videoer.Video object """ size = (height, width) stall_frames = np.clip(int(fps*0.15), 1, fps) # Show first & last longer plt = plotter.Plotter(plot, num_images=num_frames, folder=out_frames) num_frames -= (stall_frames * 2) # No need to process src and dest image plt.plot_one(src_img) video.write(src_img, stall_frames) # Produce morph frames! for percent in np.linspace(1, 0, num=num_frames): points = locator.weighted_average_points(src_points, dest_points, percent) src_face = warper.warp_image(src_img, src_points, points, size) end_face = warper.warp_image(dest_img, dest_points, points, size) average_face = blender.weighted_average(src_face, end_face, percent) average_face = alpha_image(average_face, points) if alpha else average_face plt.plot_one(average_face, 'save') video.write(average_face) plt.plot_one(dest_img) video.write(dest_img, stall_frames) plt.show()
def main(): x_value = user_input("X coordinate") y_value = user_input("Y coordinate") # Call the read file function to get the x list by passing in index 1 and the y list by passing in index 2 x_list = usermain.read_file(1, "/polygon.csv") y_list = usermain.read_file(2, "/polygon.csv") x_float = usermain.conv_float(x_list) y_float = usermain.conv_float(y_list) point = Point(x_float, y_float) polygon_init = Polygon(point) polygon_lines = polygon_init.lines() x_input_float = usermain.conv_float(x_value) y_input_float = usermain.conv_float(y_value) input_points = Point(x_input_float, y_input_float) ray_casting = RayCasting(input_points, point, polygon_lines) contains = ray_casting.contains() unclassified_list = ray_casting.unclassified_list() ray_casting = ray_casting.ray_casting() print("your point is:", ray_casting) # Plot the figure showing the polygon outline and the classified points plot_polygon = plotter.Plotter() plot_polygon.add_polygon(x_float, y_float) plot_polygon.add_point(x_input_float, y_input_float, ray_casting) plot_polygon.show()
def plot(self, func, x, y, proj, c1, c2): # 'yzxt' '''Plots intensity of the field.''' proj = np.array(list(proj)) # Convert proj to list of chars temp = np.array([ord(c) - 120 if c != 't' else 3 for c in proj]) perm = np.empty_like(temp) perm[temp] = np.arange(len(temp)) m1, m2 = np.mgrid[y:x:5j, x:y:5j] # Create a meshgrid m3, m4 = np.full_like(m1, c1), np.full_like(m1, c2) grid = np.stack((m1, m2, m3, m4)) grid = grid[perm] if func == 'i': vecfunc = np.vectorize(self.i_alt) z = vecfunc(grid[0], grid[1], grid[2], grid[3]) elif 'e' in func: vecfunc = np.vectorize(self.e_alt) z = vecfunc(grid[0], grid[1], grid[2], grid[3], ord(func[1]) - 120) elif 'h' in func: vecfunc = np.vectorize(self.h_alt) z = vecfunc(grid[0], grid[1], grid[2], grid[3], ord(func[1]) - 120) func = func.capitalize() func = list(func) if len(func) > 1: func = '$' + func[0] + '_' + func[1] + '$' plotter = plt.Plotter() plotter.plot2dcmap(m2, m1, z, axnames=proj[:2][::-1], title=func)
def train_model(args): # We are using custom model and environment, which need to be registered in ray/rllib # Names can be anything. register_env("DuckieTown-MultiMap", lambda _: DiscreteWrapper(MultiMapEnv())) # Define trainer. Apart from env, config/framework and config/model, which are common among trainers. # Here is a list of default config keys/values: # https://docs.ray.io/en/master/rllib-training.html#common-parameters # For DQN specifically there are also additionally these keys: # https://docs.ray.io/en/master/rllib-algorithms.html#dqn trainer = DQNTrainer( env="DuckieTown-MultiMap", config={ "framework": "torch", "model": { "custom_model": "image-dqn", }, "learning_starts": 500, # Doing this allows us to record images from the DuckieTown Gym! Might be useful for report. # "record_env": True, "train_batch_size": 16, # Use a very small buffer to reduce memory usage, default: 50_000. "buffer_size": 1000, # Dueling off "dueling": False, # No hidden layers "hiddens": [], # Don't save experiences. # "output": None, # "compress_observations": True, "num_workers": 0, "num_gpus": 0.5, "rollout_fragment_length": 50, }) # Start training from a checkpoint, if available. if args.model_path: trainer.restore(args.model_path) plot = plotter.Plotter('dqn_agent') for i in range(args.epochs): # Number of episodes (basically epochs) print( f'----------------------- Starting epoch {i} ----------------------- ' ) # train() trains only a single episode result = trainer.train() print(result) plot.add_results(result) # Save model so far. checkpoint_path = trainer.save() print(f'Epoch {i}, checkpoint saved at: {checkpoint_path}') # Cleanup CUDA memory to reduce memory usage. torch.cuda.empty_cache() # Debug log to monitor memory. print(torch.cuda.memory_summary(device=None, abbreviated=False)) plot.plot('DQN DuckieTown-MultiMap')
def gen_output_files(self): pic_html = '' plot_element = plotter.Plotter(length=6.5, width=5) plot_element.set_x_label(u'日期') start_date_str = datetime.strftime(self.start_date, '%Y%m%d') end_date_str = datetime.strftime(self.end_date, '%Y%m%d') title_str = self.title + u' 月全島平面圖' + '\n' + start_date_str + ' ~ ' + end_date_str if self.unit != '': title_str += u' (單位:' + self.unit + u')' plot_element.set_title(title_str, fontsize=13) plot_element.set_bottom_blank_width(0.12) plot_element.set_legend(False) plot_element.set_shapefile('/pj1/cmf/config/TWN_MAP/', 'TWN_COUNTY', color="#DDDDDD") plot_element.set_shapefile('/pj1/cmf/config/TWN_MAP/', 'TWN_adm0', color="#111111") plot_element.read_station_position('../config/', 'SStationXY_dmos_108.dat') plot_element.read_station_value_position('../config/', 'station_text.yaml') values = {stn: self._get_values(self.data[stn]) for stn in self.data } plot_element.add_map(values, self.stations, 25.8, 21.5, 122.5, 119.5, color="blue") filename = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S') + str(random.randint(0,1000000)) plot_element.save_file('/pj1/cmf/www/htdocs/tmp/' + filename +'.png', dpi=150) pic_html += '<img src="../../tmp/' + filename + '.png" id="map_img"><br><br> ' return pic_html
def main(): # Call the read file function to get the x list by passing in index 1 and the y list by passing in index 2 x_list = read_file(1, "/polygon.csv") y_list = read_file(2, "/polygon.csv") x_list_input = read_file(1, "/input.csv") y_list_input = read_file(2, "/input.csv") x_float = conv_float(x_list) y_float = conv_float(y_list) point = Point(x_float, y_float) polygon_init = Polygon(point) polygon_lines = polygon_init.lines() x_input_float = conv_float(x_list_input) y_input_float = conv_float(y_list_input) input_points = Point(x_input_float, y_input_float) ray_casting = RayCasting(input_points, point, polygon_lines) contains = ray_casting.contains() unclassified_list = ray_casting.unclassified_list() ray_casting = ray_casting.ray_casting() # Write classification results to a csv file id_list_input = read_file(0, "/input.csv") file_creation = write_file(id_list_input, contains) # Plot the figure showing the polygon outline and the # points that have been clasified and plotted plt.figure() plot_polygon = plotter.Plotter() plot_polygon.add_polygon(x_float, y_float) plot_polygon.add_point(x_input_float, y_input_float, ray_casting) plot_polygon.show()
def __init__(self): #Local variables self._running = True self.trajectory_queue = queue.Queue() self.master_board = masterboard.MasterBoard() self.plotter = pltr.Plotter("balance") for i in range(config.N_SLAVES_CONTROLLED * 2): self.plotter.create_plot(f"Joint {i}, Position Set Point", "Position [rad]") current_position = self.master_board.get_state()[0] home = np.array([[0, 100], [0, 100], [0, 100], [0, 100]]) new_point = kinematics.simple_walk_controller( home, current_position, zero_config=kinematics.idle_zero_config, joint_polarities=kinematics.idle_joint_polarities, elbows=kinematics.idle_elbow) self.trajectory_queue.put(trj.Trajectory( (current_position, new_point))) self.initial_position = new_point
def __init__(self, parent): self.parent = parent self.parser = WeatherParser() # ---- self.upper = Frame(self.parent) self.lower_left = Frame(self.parent) self.lower_right = Frame(self.parent) self.plotter = plotter.Plotter(self.lower_right) self.b_create = Button(self.upper, text="Create Sample", command=self.press_create) self.file_view = Listbox(self.lower_left, width=15, height=24, font=("Helvetica", 12), selectmode=SINGLE) self.scrollbar = Scrollbar(self.lower_left, orient="vertical") self.scrollbar.config(command=self.file_view.yview) self.file_view.config(yscrollcommand=self.scrollbar.set) self.upper.grid(row="0") self.b_create.grid(row="0", column="0") self.lower_left.grid(row="1", column="0") self.file_view.pack(side=LEFT) self.scrollbar.pack(side=RIGHT, fill="y") self.lower_right.grid(row="1", column="1") self.file_view.bind("<Double-Button>", lambda event: self.plot_csv(event)) self.update_textbox()
def iterate(self): """Iterates applying transformations and plotting""" for k in range(self.max): newSegments = [] for t in self.transformations: t.printTransformation() for i in range(self.position, len(self.segments)): for t in self.transformations: ns = sg.Segment(self.segments[i], t.apply2segment(self.segments[i])) newSegments.append(ns) self.segments = self.segments + newSegments if (self.plotForEach): pt.Plotter(self.segments) if (not self.plotForEach): pt.Plotter(self.segments)
def alphaSensitivity(db=None, outdir="./"): """ Plot results with different values of alpha """ pr = plotter.Plotter(db=db) cursor = pr.cursor[0] refAlpha = 0 refExpid = None # Get expid and alpha values from "experiment" table expRaw = cursor.execute("SELECT id, args FROM experiment ") exp = {} for expid, args in expRaw: alpha = [float(x.rpartition("=")[2]) for x in args.split(",") if x.startswith(" alpha=")] exp[expid] = alpha[0] if alpha[0]>refAlpha: refExpid = expid refAlpha= alpha[0] asHegemonyRef = dict(cursor.execute("SELECT asn, hege FROM hegemony WHERE ts=0 AND scope=0 AND expid=?",(refExpid,))) # Remove AS with a score == 0.0 toremove = [asn for asn, score in asHegemonyRef.iteritems() if score==0.0] if not toremove is None: for asn in toremove: del asHegemonyRef[asn] minVal = min(asHegemonyRef.values()) y = [] x = [] for expid, alpha in exp.iteritems(): asHegemony = dict(cursor.execute("SELECT asn, hege FROM hegemony WHERE ts=0 AND scope=0 AND expid=?", (expid,))) if not len(asHegemony): continue # Remove AS with a score == 0.0 toremove = [asn for asn, score in asHegemony.iteritems() if score==0.0] if not toremove is None: for asn in toremove: del asHegemony[asn] # Set the same number of ASN for both distributions missingAS = set(asHegemonyRef.keys()).difference(asHegemony.keys()) if not missingAS is None: for asn in missingAS: asHegemony[asn] = minVal # Compute the KL-divergence dist = [asHegemony[asn] for asn in asHegemonyRef.keys()] kldiv = sps.entropy(dist, asHegemonyRef.values()) y.append(kldiv) x.append(alpha) sx, sy = zip(*sorted(zip(x,y))) plt.figure(figsize=(4,3)) plt.plot(sx, sy, "+-") plt.xlabel("$\\alpha$") plt.ylabel("KL divergence") plt.tight_layout() plt.savefig("results/alphaSensitivity/alphaSensitivity.pdf")
def setUp(self): x = np.arange(-5, 5, 0.2) y = np.arange(-3, 3, 0.2) Z = np.zeros((len(x), len(y))) for idx_x, val_x in enumerate(x): for idx_y, val_y in enumerate(y): Z[idx_x, idx_y] = val_x**2 + val_y**2 self.plotter = plotter.Plotter(x, y, Z)
def run(self): for timeseries in self.timeseries_batch: plot = plotter.Plotter(files=timeseries.files, title=timeseries.title, subtitle=timeseries.subtitle, save_path=timeseries.save_path, colors=self.colors, xmin=self.xmin, xmax=self.xmax, ymin=self.ymin, ymax=self.ymax, xlabel=self.xlabel, ylabel=self.ylabel, majorxticks=self.majorxticks, majoryticks=self.majoryticks, minorxticks=self.minorxticks, minoryticks=self.minoryticks, font=self.font, xlabel_font_size=self.xlabel_font_size, ylabel_font_size=self.ylabel_font_size, xtick_font_size=self.xtick_font_size, ytick_font_size=self.ytick_font_size, alter_xscale=self.alter_xscale, alter_yscale=self.alter_yscale, linewidth=self.linewidth, secondary_x=self.secondary_x, secondary_y=self.secondary_y, direction=self.direction) plot.timeseries()
def analysis_1_tab_init(self): self.analyzer = analysis.CPTanalyzer() analysis_plotter = plotter.Plotter(CPTdata()) self.analysis_plotter_widget = PlotterWidget(analysis_plotter) tab_idx = self.analysis_1_tab_idx self.analysis_data_dirs_qlist = QListWidget() # self.analysis_data_dirs_qlist.addItem( 'test' ) analysis_controls_box = QGroupBox('Choose Files for Analysis') analysis_controls_layout = QVBoxLayout() # tmp = QHBoxLayout() # tmp.addWidget( QLabel( 'Display Isolated Dataset' ) ) # self.analysis_display_isolated_dataset = 0 # self.isolated_dataset_checkbox = QCheckBox() # self.isolated_dataset_checkbox.setCheckState( self.analysis_display_isolated_dataset ) # self.isolated_dataset_checkbox.clicked.connect( self.toggle_isolated_dataset ) # tmp.addWidget( self.isolated_dataset_checkbox ) # analysis_controls_layout.addLayout( tmp ) analysis_controls_layout.addWidget(self.analysis_data_dirs_qlist) buttons = QHBoxLayout() add_button = QPushButton('Add') add_button.clicked.connect(self.add_button_clicked) delete_button = QPushButton('Delete') delete_button.clicked.connect(self.delete_button_clicked) buttons.addWidget(add_button) buttons.addWidget(delete_button) analysis_controls_layout.addLayout(buttons) analysis_controls_box.setLayout(analysis_controls_layout) # layout.addWidget( self.analysis_data_dirs_qlist ) # layout.addWidget( self.canvases[ tab_idx ] ) # self.analysis_tab.setLayout( layout ) # plotting # f, axarr = plt.subplots( 2, 2 ) # f.subplots_adjust( hspace = 0.5 ) # self.canvases[ tab_idx ] = FigureCanvas( self.analysis_plotter.f ) # self.tab_updaters[ tab_idx ] = [ self.analysis_plotter_widget.update ] layout = QHBoxLayout() layout.addWidget(analysis_controls_box) layout.addLayout(self.analysis_plotter_widget.grid_layout) # layout = QGridLayout() # layout.addWidget( analysis_controls_box, 0, 0, 0, 1, QtCore.Qt.AlignLeft ) # layout.setColumnStretch( 0, 0.5 ) # layout.addWidget( self.canvases[ tab_idx ], 0, 1, 1, 1 ) # layout.setColumnStretch( 1, 1 ) self.analysis_1_tab.setLayout(layout)
def main(): """ main function """ data = {'max': [1] * 15, 'min': [0] * 15, 'sigs': []} preprocessing(data) plter = plotter.Plotter(INTERVAL, 'static') plter.plot(data) plotter.waitforbuttonpress() print('Program quit')
def __init__(self, plane_pal, bot, **kwargs): self.plane_pal = plane_pal self.bot = bot self.plot_command_help = kwargs.get(self.PLOT_COMMAND_HELP_KEY, self.PLOT_COMMAND_HELP) self.path_parser = PathParser() self.plotter = plotter.Plotter() self.dynamo_db = dynamo_helper.DynamoHelper()
def localGraphTransitEvolution(scope, name, dbList=None, years=[2017], expid=1): if dbList is None: dbList = [] for ye in years: dbList.extend(listFiles("results", "sql", ye)) pr = plotter.Plotter(db=dbList) pr.hegemonyEvolutionLocalGraph(scope, fileDate=True, expid=expid) else: pr = plotter.Plotter(db=dbList) pr.hegemonyEvolutionLocalGraph(scope, expid=expid) # plt.title(name+"\n\n") # plt.tight_layout() plt.savefig(resultsDirectory + "fig/%s_AS%s_transitEvolution.pdf" % (name.replace(" ", "_"), scope))
def poll_queue(): if not self.data_queue.empty(): original, sinogram, filtered, rec, rms = self.data_queue.get() self.rms_label['text'] = str(rms) plt = plotter.Plotter((2,2)) plt.plot(original, 1, self.cfg.path.split("/")[-1]) plt.plot(rec, 2, 'reconstruction') plt.plot(sinogram, 3, 'sinogram') plt.plot(filtered, 4, 'filtered sinogram') self.figure = gui_utils.draw_figure(self.canvas, plt.figure) self.root.after(100, poll_queue)
def __init__(self, OutDir, tabdDir, argv0): self.outdir = OutDir self.tabdDir = tabdDir if not (os.path.exists(OutDir)): os.makedirs(OutDir) (head, tail) = os.path.split(argv0) shutil.copyfile(head + '/stylesheet.css', OutDir + '/stylesheet.css') shutil.copyfile(head + '/arrows.png', OutDir + '/arrows.png') self.htmldoc = open(OutDir + '/index.html', 'w') self.googlecharts = googlecharts.GoogleCharts() self.plotter = plotter.Plotter(self.outdir)
def gen_output_files(self): #for count, index_data in enumerate(self.data): pic_html = '' for stn in self.data: plot_element = plotter.Plotter() # format the date, for example, 10Jan2015 will become datetime(2015, 1, 10) y_values = [ 0 if np.isnan(i[1]) else float(i[1]) for i in self.data[stn] ] x_values = [i[0] for i in self.data[stn]] plot_element.set_x_label(u'日期') plot_element.set_title(stn + u'站 ' + self.title + u'日數 ' + self.time_unit_chn + u'柱狀圖') major_interval, minor_interval = plot_element.get_suitable_interval( len(x_values)) if self.time_unit == 'month': plot_element.set_time_formatter('%b%Y', major_interval, minor_interval, 'month') elif self.time_unit == 'year': plot_element.set_time_formatter('%Y', major_interval, minor_interval, 'year') plot_element.set_bottom_blank_width(0.15) plot_element.set_legend(True, 12) #plot_element.add_date_bars(x_values, y_values, u'日數', has_dot=True) plot_element.add_date_bars( x_values, y_values, u'日數', alpha=0.6, total_bars=data_length, first_last_left_blank=False, plus_minus_seperate_color=plus_minus_seperate_color) max_value = np.nanmax(y_values) min_value = np.nanmin(y_values) if self.value_type in ['raw']: min_value = 0 else: min_value -= 1 if max_value == 0: plot_element.ax.set_ylim(min_value, 5) else: plot_element.ax.set_ylim(min_value, max_value + 4) filename = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S') + str( random.randint(0, 1000000)) plot_element.save_file('/pj1/cmf/www/htdocs/tmp/' + filename + '.png') pic_html += '<img src="../../tmp/' + filename + '.png" width="90%" id="index' + '"><br><br> ' return pic_html
def initAll(self): self.deviceList = DL.DeviceList(self) self.menuBar = MN.Menu(self) self.btnGroup = SS.ButtonGroup(self) self.audioRecPlayer = RP.RecPlayer(self) self.plotter = PL.Plotter(self) XY = self.deviceList.XY self.labelFrame = GUI.LabelFrame(self.widget, text=u'【进度详情】') self.labelFrame.config(width=580, height=860) self.labelFrame.place(x=10, y=XY[1]) self.progressTxt = GUI.Message(self.labelFrame, width=580) self.progressTxt.place(x=0, y=0)
def TrainModel(trainInput, trainLabels, epochs): nx = trainInput.shape[0] w = np.random.random((nx, 1)) * 0.001 b = np.zeros((1, 1)) trainer = TrainMany(trainInput, trainLabels, w, b) plot = plotter.Plotter() plot.Start(epochs) for _w, _b, cost in itertools.islice(trainer, epochs): print("Cost: " + str(cost)) plot.Update(cost) return _w, _b
def localGraphNbnodeDist(): years = [2017] #range(2002,2018) if len(years) > 1: ccmap = mpl.cm.get_cmap('copper_r') # Using contourf to provide my colorbar info, then clearing the figure Z = [[0, 0], [0, 0]] CS3 = plt.contourf(Z, years, cmap=ccmap) plt.clf() for yidx, ye in enumerate(years): dbList = listFiles("results", "sql", ye) print dbList pr = plotter.Plotter(db=dbList) if len(years) > 1: contour = CS3 if ye != years[-1]: contour = None data = pr.nbNodeDistLocalGraph( 2, filename=resultsDirectory + "fig/localGraphNbNodesCDF_%s.pdf" % ye, labelNoZero=ye, color=ccmap(yidx / float(len(years)))) else: data = pr.nbNodeDistLocalGraph( 2, filename=resultsDirectory + "fig/localGraphNbNodesCDF_%s.pdf" % ye, labelNoZero=ye) print ye # print "\tMean number of nodes in local graphs: %s (std=%s, median=%s)" % (np.mean(data["all"].values()), np.std(data["all"].values()), np.median(data["all"].values())) print "\tMean number of nodes in local graphs (non-null hegemony): %s (std=%s, median=%s)" % ( np.mean(data["noZero"].values()), np.std( data["noZero"].values()), np.median(data["noZero"].values())) # ASN with no transit nodes notransit = [(k, v) for k, v in data["noZero"].iteritems() if v < 1] print "\t %s ASN with less than one transit nodes:" % len(notransit) for asn, nnode in notransit: print "\t\tAS%s %s transit node" % (asn, nnode) # ASN with many transit nodes manytransit = [(k, v) for k, v in data["noZero"].iteritems() if v > 25] print "\t %s ASN with more than 50 transit nodes:" % len(manytransit) for asn, nnode in manytransit: print "\t\tAS%s %s transit nodes" % (asn, nnode) print data["noZero"][15169]
def localGraphTransitEvolution(scope, name, dbList=None, outdir="./", expid=1): """ Plot the time evolution of AS hegemony scores for the local graph identified by the ASN scope""" pr = plotter.Plotter(db=dbList) pr.hegemonyEvolutionLocalGraph(scope, expid=expid) if name is None: plt.title("Transits towards AS%s\n\n" % scope) else: plt.title(name + "\n\n") plt.tight_layout() plt.savefig(outdir + "/AS%s_localHegemony.pdf" % scope)
def initPlotter(self): self.plotter = plotter.Plotter() # The ratio of stitched sensor input width to plotter point width, known to be > 1.0 self.COLUMN_SCALING_FACTOR = float(STITCHED_COLUMNS + 1) / (self.plotter.COLUMNS + 1) # The ratio of stitched sensor input height to plotter point height, known to be > 1.0 self.ROW_SCALING_FACTOR = float(STITCHED_ROWS + 1) / (self.plotter.ROWS + 1) typical_distance = self.calculateMergedDepth(self.plotter.COLUMNS / 2, self.plotter.ROWS / 2)[1] logging.debug("initial distance %s" % str(typical_distance)) logging.info("x,y sensor:display scaling factor %f,%f" % (self.COLUMN_SCALING_FACTOR, self.ROW_SCALING_FACTOR)) self.plotter.setAllCellDistances(typical_distance) self.COL_LIMIT = self.plotter.COLUMNS - 1
def gen_output_files(self): #for count, index_data in enumerate(self.data): pic_html = '' #for stn in self.data: plot_element = plotter.Plotter(length=5, width=10) # format the date, for example, 10Jan2015 will become datetime(2015, 1, 10) if self.station_display == 'last3nums': stns_ticks = [stn[2:5] for stn in self.stations] elif self.station_display == 'chinese': stns_ticks = [self.stn_names[stn[:5]]['chn_name'].decode('utf-8') for stn in self.stations] stns_grid = np.array(xrange(len(self.data))) dates = [i[0] for i in self.data.items()[0][1]] dates_ticks = self._get_date_ticks(dates) dates_grid = np.array(xrange(len(self.data.items()[0][1]))) x_values, y_values = np.meshgrid(dates_grid, stns_grid) stns = self.data.keys() z_values = [[ 0 if np.isnan(float(data[1])) else float(data[1]) for data in self.data[stn[:5]+'0'] ] for stn in self.stations] plot_element.set_x_label(u'日期') self.unit = self._get_unit() title_text = self.title + self.time_unit_chn + u'二維時序圖' if self.unit != '': title_text += u' (單位:' + self.unit + u')' plot_element.set_title(title_text) #major_interval, minor_interval = plot_element.get_suitable_interval(len(x_values)) #plot_element.set_time_formatter('%b%Y', major_interval, minor_interval, 'month') plot_element.set_bottom_blank_width(0.15) plot_element.set_legend(False) mymap = self._create_custom_map() plot_element.add_date_2d(x_values, y_values, z_values, stns_ticks=stns_ticks, dates_ticks=dates_ticks, cmap=mymap, time_unit=self.time_unit, value_type=self.value_type, colorbar_max=self.colorbar_max, colorbar_min=self.colorbar_min, colorbar_interval=self.colorbar_interval) filename = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S') + str(random.randint(0,1000000)) plot_element.save_file('/pj1/cmf/www/htdocs/tmp/' + filename +'.png') pic_html += '<img src="../../tmp/' + filename + '.png" id="img_2d"><br><br> ' return pic_html