def __init__(self, dialog): Ui_Form.__init__(self) self.setupUi(dialog) self.solver = Solver() self.plotter = Plotter(self.plot_widget, self.solver) self.trajectory_plot = Plotter(self.plot_trajectory, self.solver) self.filt_plot = Plotter(self.plot_filt, self.solver) # Connect "add" button with a custom function (addInputTextToListbox) self.plot_btn.clicked.connect(self.plot) self.start_btn.clicked.connect(self.start) # Set functions self.read_ro_btn.clicked.connect(self.read_ro) self.read_s_btn.clicked.connect(self.read_s) self.read_z_btn.clicked.connect(self.read_z) self.ro_a.setValidator(QDoubleValidator(self.beta_end)) self.ro_b.setValidator(QDoubleValidator(self.beta_end)) self.x0.setValidator(QDoubleValidator(self.beta_end)) self.y0.setValidator(QDoubleValidator(self.beta_end)) self.T.setValidator(QDoubleValidator(self.beta_end)) self.beta_start.setValidator(QDoubleValidator(self.beta_end)) self.beta_end.setValidator(QDoubleValidator(self.beta_end))
def __init__(self): plott = Plotter() QtGui.QMainWindow.__init__(self) self.setWindowIcon(QtGui.QIcon('phyton.ico')) self.setupUi(self) self.fit = Fitter() self.gen = Generator() self.plot = Plotter() self.fitted_args = [] self.chi2 = None self.chi2Error = 0.5
def __init__(self, args): input_path = args['input'] if not os.path.exists(input_path): raise FileNotFoundError(f'{input_path} does not exist') # get capture object self.cap = self.get_video(input_path) # get total number of frames self.total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) # get buffer size self.buffer_size = args['buffer'] # handle size parameter self.handle_size(args['size']) # get name of file filename = self.get_filename(input_path) # get output output = args['output'] # get final dir self.output_dir = output + filename + '/' # create dictionary of video writers self.input_videos = {} self.video_writers = {} # determine options for program self.handle_option(args['option'], args['read']) # initiate average and edit class self.stabiliser = Stabiliser(self.total_frames, self.size) self.ma = MovingAverage(self.size, False, False, args['buffer']) self.fe = FrameEditor() self.plt = Plotter(self.output_dir) # creates background model class using mixture of gradients self.backSub = cv2.createBackgroundSubtractorMOG2()
def __init__(self) : possible_years = [int(i) for i in os.listdir(os.getcwd() + "\\logs\\")] self.plotter = Plotter(possible_years) self.window = Tk() self.window.title("Reading Process Progress") self.window.configure(background=self.COLOR2) # self.window.grid_rowconfigure(1, minsize=20) self.window.grid_rowconfigure(4, minsize=10) self.window.grid_columnconfigure(2, minsize=100) self.label1 = Label(self.window, text="Aggregate:", bg=self.COLOR2, fg=self.COLOR1) self.label1.grid(column=1, row=0) btnCompareAverage = Button(self.window, text="average year by year", command=self.plotter.compareAverages) btnCompareAverage.grid(column=2, row=1) self.label2 = Label(self.window, text="Year specific:", bg=self.COLOR2, fg=self.COLOR1) self.label2.grid(column=1,row=2) self.selectedYear = StringVar(self.window) self.selectedYear.set(possible_years[-1]) # default value yearSelection = OptionMenu(self.window, self.selectedYear, *possible_years, command = self.yearEntered) yearSelection.grid(column=1, row=3) btnTimeline = Button(self.window, text="timeline of reading", command=self.plotter.plotTimeLine) btnTimeline.grid(column=2, row=3) btnAllTrajectories = Button(self.window, text="all trajectories", command=self.plotter.plotTrajectories) btnAllTrajectories.grid(column=3, row=3) btnplotAverageTrajectories = Button(self.window, text="average trajectories", command=self.plotter.plotAverageTrajectories) btnplotAverageTrajectories.grid(column=4, row=3)
def testing(self, dataset, testing_x, testing_y, widget): testing_x = testing_x label_testing = numpy.argmax(testing_y, axis=1) batch_size = 200 plotter = Plotter(dataset) predict = numpy.zeros((10000, 10)) predict_label = numpy.zeros(10000) completed = 0 for start in range(0, len(testing_x), batch_size): print(start) completed = completed + 2 widget.progress_bar.setValue(completed) x_batch = testing_x[start:start + batch_size] predict[start:start + batch_size] = self.test(x_batch) predict_out = self.output(predict) pandas.DataFrame(predict).to_csv("../output_testing.csv") pandas.DataFrame(predict_out).to_csv("../output_testing_2.csv") accuracy = numpy.mean(predict_out == label_testing) print(accuracy) plotter.plot_testing(x_batch, predict[start:start + batch_size], widget.list_result) widget.acc_label.setText(str(accuracy))
def __init__(self, infoRun, data = ''): self.infoRun = infoRun self.SetEnvironment(self.infoRun) self.data = data counter = 0 # Apply selection cut for bck in self.backgrounds: self.listOfSelectors.append(Selector(bck, self.savepath)) counter += 1 if (self.data != ''): self.dataSelector = Selector(self.data, self.savepath) # == Draw histograms # Parse selectors and other parameters to the Plotter class p = Plotter(self.listOfSelectors, self.dataSelector, self.Histos, self.colors) p.SetSavePath(self.savepath) p.SetAnnotations(self.Annotations) p.DrawHistos() # ===== Compute the cross-section # == Set attributes and parameters and compute the final result self.SetParameters('MuonPt') self.PrintXsection('MuonPt') return
def process(path=None, save_path=None): if path is None: path = filedialog.askopenfilename(filetypes=[("Excel files", ".xlsx .xls")]) save_path = ".".join(path.split(".")[:-1]) + "/" os.makedirs(save_path, exist_ok=True) fsc = FuelSystemConfigCreator(path).create() fc = FormulaCreator(fsc) for tank_name in fsc: os.makedirs(save_path + r"/" + tank_name, exist_ok=True) for virtual_dut in fsc[tank_name]["virtual_duts_table"]: liters = list(virtual_dut.V_DUT_LITERS) liters = [liters[0]] + liters + [liters[-1]] dut_values = list(virtual_dut.DUT_VALUES) dut_values = [dut_values[0] - 1 ] + dut_values + [dut_values[-1] + 1] df = pd.DataFrame({ "values": dut_values, "liters": liters, }) with open(save_path + r"/" + tank_name + r"/wialon formula.txt", "w") as f: f.write(fc.wialon_formula[tank_name]) df.to_csv(save_path + r"/" + tank_name + f"//V{virtual_dut.V_DUT_NUMBER}.csv", sep=";", header=False, index=False) Plotter().get_fx(fsc, fc.latex_formula_full, save_path=save_path)
def compareDistancesWithSignalStrength(self): (Distances, Xs, Ys) = self.calculateDistanceFromCenterPointsToEachPoseReturningXYs() """ [ [Grid0 to P1, Grid0 to P2, Grid0 to P3, ... , Grid0 to Pn] [Grid1 to P1, Grid1 to P2, Grid1 to P3, ... , Grid1 to Pn] ... [Gridn to P1, Gridn to P2, Gridn to P3, ... , Gridn to Pn] ] """ global R RSSIofEachPoint = R """ [ RSSI of P1, RSSI of P2, RSSI of P3, ... , RSSI of Pn ] """ coefficientMatrix = [] for gridPoint in Distances: coefficientMatrix.append(self.calculateSimilarityScoreOfAGridPoint(gridPoint, RSSIofEachPoint)) PL = Plotter() #PL.printCompleteMapInColor([Xs, Ys, coefficientMatrix]) maximumCoefficient = coefficientMatrix.index(max(coefficientMatrix)) coefficientMatrix[maximumCoefficient] = 900 Xs.extend(X) Ys.extend(Y) coefficientMatrix.extend(R) PL.printCompleteMapInColor([Xs, Ys, coefficientMatrix])
def display_vwpc(df, symbol, metric, ws=10, ycs=None, save_path=None): vals = df.loc[symbol, metric] volvals = df.loc[symbol, 'Volume'] df_vals = pd.concat([vals, volvals], axis=1, keys=[metric, 'Volume']) df_vals['Symbol'] = symbol df_vals = df_vals.reset_index().set_index(['Symbol', 'Date']) df_vwpc = vwpc(df_vals, window_sizes=[ws], standard=False) vwpcvals = df_vwpc.loc['JPM', f'{metric}_vwpc_{ws}'] vals = vals / vals[vals.first_valid_index()] weighted = vals * volvals weighted = (weighted - weighted.min()) / (weighted.max() - weighted.min()) x1 = pd.DataFrame({metric: vals, 'norm vwp': weighted}) x2 = pd.DataFrame({'vwpc': vwpcvals}) plotter = Plotter() colors = [[(0.6, 0.13, 0.79), (0.79, 0.5, 0.13)], [(0.35, 0.35, 0.35)]] hcolors = [(0, 0, 1), (0, 0, 0)] yax_labels = [f'indexed {metric}, norm vwp', 'vwpc'] plotter.stacked_plot(x1, x2, yax_labels=yax_labels, title=f'{symbol} {metric} VWPC', colors=colors, hcolors=hcolors, ycs=ycs, save_path=save_path)
def train(self): caffe.set_device(0) caffe.set_mode_gpu() solver = caffe.SGDSolver(self.netPath + "solver.prototxt") if len(self.snapshotFilename) != 0: solver.restore(self.netPath + self.snapshotPath + self.snapshotFilename) baseIter = solver.iter plotter = Plotter() plotter.initLossAndAccu(baseIter, self.iterationCount, self.netPath) plotter.initResult(interval=50) for i in range(self.iterationCount - baseIter): solver.step(1) # plot loss and accu loss = solver.net.blobs["loss"].data accu = solver.test_nets[0].blobs["accu"].data plotter.plotLossAndAccu(loss, accu) # plot result and label data = solver.net.blobs["data"].data data = np.squeeze(data[0, 0, :, :, :]) result = solver.net.blobs["conv_i64c2o64_output_1"].data result = np.squeeze(result[0, 1, :, :, :]) # print(result) label = solver.net.blobs["label"].data label = np.squeeze(label[0, 0, :, :, :]) plotter.plotResult(data, label, result)
def display_sma(df, symbol, metric, ws=10, ycs=None, save_path=None): vals = df.loc[symbol, metric] df_vals = pd.DataFrame(pd.concat([vals], keys=[symbol], names=['Symbol'])) df_sma = sma(df_vals, ws) smas = df_sma.loc[symbol, metric] df_pct_sma = pct_sma(df_vals, window_sizes=[ws], standard=True) psmas = df_pct_sma.loc[symbol, f'{metric}_pct_sma_{ws}'] vals = vals / vals[vals.first_valid_index()] smas = smas / smas[smas.first_valid_index()] x1 = pd.DataFrame({metric: vals, 'sma': smas}) x2 = pd.DataFrame({'standard pct sma': psmas}) plotter = Plotter() yax_labels = [f'indexed {metric}, sma', 'standard pct sma'] colors = [[(0.6, 0.13, 0.79), (0.79, 0.5, 0.13)], [(0.35, 0.35, 0.35)]] hcolors = [(0, 0, 1), (0, 0, 0)] plotter.stacked_plot(x1, x2, yax_labels=yax_labels, title=f'{symbol} {metric} SMA', ycs=ycs, colors=colors, hcolors=hcolors, save_path=save_path)
def cmp_benchmark(self, symbol, sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31), sv=1e5, bench_quantity=1e3, commission=9.95, impact=0.001, should_plot=False, labels=None, title=None, save_path=None): df_trades = self.testPolicy(symbol=symbol, sd=sd, ed=ed, sv=sv) sp = msim.compute_portvals(df_trades, start_val=sv, commission=commission, impact=impact) bp = self.benchmark_policy(symbol, sd=sd, ed=ed, sv=sv, quantity=bench_quantity, commission=commission, impact=impact) if labels is None: labels = ['benchmark', 'manual'] # combine policies into single dataframe df_cmp = pd.concat([bp, sp], axis=1) df_cmp.columns = labels # optionally plot comparison if should_plot: plotter = Plotter() yax_labels = [f'indexed portfolio value', 'shares'] colors = [[(0, 1, 0), (1, 0, 0)], [(0.35, 0.35, 0.35)]] df_pos = df_trades.cumsum() df_cmp['benchmark'] = df_cmp['benchmark']/bp.iloc[0] df_cmp['manual'] = df_cmp['manual']/sp.iloc[0] ycs = [[3, ['>', 0, 1]], [3, ['<', 0, 1]]] hcolors = [(0, 0, 1), (0, 0, 0)] plotter.stacked_plot(df_cmp, df_pos, yax_labels=yax_labels, title=title, ycs=ycs, colors=colors, hcolors=hcolors, yc_data=df_trades, save_path=save_path) return df_cmp
def __init__(self, params): self.batchSize = params["batch_size"] self.volSize = params["vol_size"] self.iterationCount = params["iter_count"] self.queueSize = params["queue_size"] self.shiftRatio = params["shift_ratio"] self.rotateRatio = params["rotate_ratio"] self.histogramShiftRatio = params["histogram_shift_ratio"] self.dataPath = params["data_path"] self.netPath = params["net_path"] self.phase = params["phase"] self.phaseSubPath = self.phase + "/" self.dataQueue = multiprocessing.Queue(self.queueSize) self.plotter = Plotter() self.plotter.initDataAndLabel2D(interval=20) if self.phase == "deploy": # scan pass else: # load all nodules and groundTruths dataProcess = multiprocessing.Process(target=self.dataProcessor, args=(self.dataQueue, )) dataProcess.daemon = True dataProcess.start()
def plotStationET(): station = request.form.getlist('station[]') print(station) date = request.form.get('date') print(date) p = Plotter() figdata_png = p.plot_hourly_eto_by_station_date(int(station[0]), date) return render_template('img.html', result=figdata_png)
def __init__(self, objective_function, configuration, result_file_name, skip_frames=0): super().__init__(objective_function, configuration[0], configuration[1], result_file_name) self.max_beta = configuration[2] self.absorption_coefficient = configuration[3] self.result_file_name = result_file_name self.factor = objective_function.factor self.skip_frames = skip_frames self.plotter = Plotter(objective_function, 'Firefly')
def _plot(eval_results, eval_targets): plotter = Plotter(eval_results, eval_targets) plotter.plot_arousal() plotter.show() plotter.plot_valence() plotter.show()
def plot(self, predict): """ :param predict: トレーニングしたモデルで予測した結果。one_hot表現ではなく、確率が入っている。 :return: """ p = Plotter() p.plot_and_show(self.d.inputs_org, predict, self.NUM_OF_EACH_CLASS_DATA, self.NUM_OF_CLASSES)
def plot_three_meshes(a_the_meshes: list): # a_the_meshes = [study1['rho_gamma10.0_mesh1']['mesh'], # study1['rho_gamma10.0_mesh2']['mesh'], # study1['rho_gamma10.0_mesh3']['mesh']] usr = study1['rho_gamma10.0_mesh1']['mesh'].usr msh = a_the_meshes[0] plotter = Plotter(usr, msh) plotter.plot_mesh() usr = study1['rho_gamma10.0_mesh2']['mesh'].usr msh = a_the_meshes[1] plotter = Plotter(usr, msh) plotter.plot_mesh() usr = study1['rho_gamma10.0_mesh3']['mesh'].usr msh = a_the_meshes[2] plotter = Plotter(usr, msh) plotter.plot_mesh()
def plot_configuration(config_name, policy_names): #set the regrets setting = Setting() regrets = setting.set_regrets() num_regrets = len(regrets) #load experiments loader = DataLoader() experiments = loader.load_config_experiments(config_name, policy_names) num_exp = len(list(experiments.values())[0]) #retrieve configuration config = list(experiments.values())[0][0].config #retrive time horizon N = config.N #retrive policies policies = [] for exp_list in experiments.values(): policies = policies + [exp_list[0].policy] num_policies = len(policies) #compute the regrets regret = np.zeros((num_exp, num_policies, num_regrets, N)) for pol_idx in range(num_policies): curr_policy = policies[pol_idx] for exp_idx in range(num_exp): curr_exp = experiments[curr_policy.name][exp_idx] pulls = curr_exp.pulls for reg_idx in range(num_regrets): curr_regr = regrets[reg_idx] regret[exp_idx, pol_idx, reg_idx, :] = curr_regr.compute_regret( pulls, curr_exp.config) mean_regret = np.mean(regret, axis=0) #varianza del regret std_regret = np.std(regret, axis=0) error = 2 * np.true_divide(std_regret, num_exp**0.5) #plot the regrets titles = [] labels = [] filename = config_name + '_' for policy in policies: filename = filename + policy.name + '-' labels = labels + [policy.name] filename = filename[:-1] + '_' for reg_type in regrets: titles = titles + [reg_type.description] filename = filename + reg_type.name + '-' plt = Plotter() plt.plot_regret(mean_regret, error, None, titles, labels, filename[:-1])
def calcReg(): params = request.form.getlist('params[]') p = Plotter() # print(params) # print(p.get_regression_result(params)) if (len(params) > 0): return jsonify(p.get_regression_result(params)) else: return jsonify(p.get_regression_result())
def visualizePredictions(self, training_x, training_y, test_x, test_y): #Input 1 or 2 D. Output 1 D. assert (training_x.shape[1] == 1 or training_x.shape[1] == 2), \ "Invalid Dimensions for Plotting Results - Input: %d" %(training_x.shape[1]) plotter = Plotter() plotter.plotPrediction(self, training_x, training_y, self.norm_test_x, self.norm_test_y) plotter.plotExpertsPrediction(self, test_x, test_y) plotter.plotExpertsCenters(self, training_x, training_y) plotter.plotGaussians(self, training_x, training_y)
def plot(self, filter, property, axis = (0,1)): """ Plots the graphic and exhibits it. :param filter: The filter to use within files' data. :param property: Property to be plotted. :param axis: Value interval for the y-axis. """ plotter = Plotter(self) plotter.plot(filter, property, axis) plotter.clean()
def __init__(self, objective_function, configuration, result_file_name, skip_frames=0): super().__init__(objective_function, configuration[0], configuration[1], result_file_name) self.max_trials = configuration[2] self.skip_frames = skip_frames self.plotter = Plotter(objective_function, 'Bees')
def OnGetQuotes(self): #self.bridge.SubscribeMarketQuotes(view.state.ListOfActiveInstruments,view.state.selectedExchange) for instrument in view.state.ListOfActiveInstruments: plotter = Plotter(PlotData, PlotDataDBOperator(PlotData), view.state.ListOfActiveInstruments) threading.Thread( target=plotter.Animate, args=(view.state.ListOfActiveInstruments.index(instrument), instrument)).start()
def run(self): if self.simulation_state.show_viewer: self.viewer = Viewer(self.simulation_state, self.aircraft_state, self.app) if self.simulation_state.show_plotter: self.plotter = Plotter(self.log, self.app) self.sim_loop() self.export_logs() if not self.simulation_state.show_plotter and self.simulation_state.aar: self.plotter = Plotter(self.log, self.app) self.plotter.update_plots() self.app.processEvents() print("Opening After Action Report") if self.simulation_state.show_viewer or self.simulation_state.show_plotter or self.simulation_state.aar: input("Press enter to quit.") if self.simulation_state.show_viewer: self.viewer.window.close() if self.simulation_state.show_plotter or self.simulation_state.aar: self.plotter.window.close() self.app.quit()
def __init__(self): QtGui.QMainWindow.__init__(self) self.plotHolder = Plotter() self.layout = QtGui.QVBoxLayout() self.data = 0 self.dataStr = 0 self.filePath = None self.filePath2 = 0 self.setWindowTitle("FlightMadness") self.setWindowIcon(QtGui.QIcon('phyton.ico')) self.setupUi(self)
def printAll(self): (G, X, Y) = self.gridCoordinates() (Xs, Ys, Zs, XYs, XYZs) = self.middlePointsInTheGrid() PL = Plotter() Z = [100 for i in range(len(Alls[0]))] Alls[0].extend(X) Alls[1].extend(Y) Alls[2].extend(Z) Alls[0].extend(Xs) Alls[1].extend(Ys) Alls[2].extend(Zs) PL.printCompleteMap(Alls)
def plotDiff(X, ys, xlim=None, lpSize=168): p = Plotter(plt, linewidth=0.2) xPlot = np.arange(0, len(Xbh1_), 1) for expect, predict, label in ys: d = np.log2((expect - predict) ** 2 + 1) / 2.0 p.plot(xPlot, d, color=p.nextColor(), label=label) if lpSize is not None: dm = np.convolve(d, np.full(lpSize, 1./lpSize), mode='same') p.plot(xPlot, dm, color=p.nextColor(), label=label + ' mean') if xlim is not None: p.limit(d, xlim=xlim) p.savefig('../figures/diff.svg')
def plan_handle(channel, data): plan = drc.footstep_plan_t.decode(data) # -- PLOT FOOTSTEP PLAN -- print("-------------------------------------------") footsteps = [] # Unpack footstps into list for f in plan.footsteps: footsteps.append([f.pos.translation.x, f.pos.translation.y]) footsteps = np.array(footsteps) p = Plotter(2, GOAL_POS, footsteps, plan.num_steps/2, REACHABLE, Y_OFFSET) p.plot() print("-------------------------------------------") p.show()
def __init__(self, plotting_freq): self.plotter = Plotter(plotting_freq) # Define plot names plots = self._define_plots() # Add plots to the window for p in plots: self.plotter.add_plot(p) # Define state vectors for simpler input self._define_input_vectors()