def __init__(self): self.bool_test = False self.bleftBtnReleased = False self.bleftDoubleClicked = False self.output_counter = 0 # ******************main program starts****************** # Set Alpha Vantage key and create timeseriese and time indicator objects self.key = 'XXXX' # get your key from https://www.alphavantage.co/support/#api-key # ts = TimeSeries(key, output_format='json') self.ts = TimeSeries(self.key, output_format='pandas') self.ti = TechIndicators(self.key, output_format='pandas') # Now create tkinter root object and the frame object on which we will place the other widgets self.root = Tk() self.root.state('zoomed') #this maximizes the app window self.root.title('Stock Analytics') self.content = ttk.Frame(self.root, padding=(5, 5, 12, 0)) self.content.grid(column=0, row=0, sticky=(N, S, E, W)) # add main menu object self.menu = Menu() self.root.config(menu=self.menu) # add file menu self.file_menu = Menu(self.menu, tearoff=0) self.file_menu.add_command(label="Open Portfolio", command=self.OpenPortfolio) self.file_menu.add_command(label="Save Portfolio", command=self.SavePortfolio) self.file_menu.add_separator() self.file_menu.add_command(label="Exit", command=self.root.destroy) self.menu.add_cascade(label='File', menu=self.file_menu) # Now create exchange label and combo box to show exchange along with associated text variable to hold selection self.exchange_label = ttk.Label(self.content, text='Select Exchange: ') self.exchange_text = StringVar() self.exchange_combo = ttk.Combobox(self.content, textvariable=self.exchange_text, values=('BSE', 'NSE'), state='readonly') # Now create stock symbol label and text box to allow user to enter stock symbol self.symbol_label = ttk.Label(self.content, text='Enter stock symbol: ') self.symbol_text = StringVar() self.symbol_entry = ttk.Entry(self.content, textvariable=self.symbol_text, width=5) # Now create purchase price entry self.price_label = ttk.Label(self.content, text='Enter your purchase price: ') self.price_text = StringVar(value='0.00') self.price_entry = ttk.Entry(self.content, textvariable=self.price_text, width=10) # Now create purchase date entry self.purchasedate_label = ttk.Label(self.content, text='Enter date of purchase: ') self.purchasedate_text = StringVar(value=date.today()) self.purchasedate_entry = ttk.Entry( self.content, text='yyyy-mm-dd', textvariable=self.purchasedate_text, width=10) # Now create buttons to fetch respective information related to user specified stock self.btn_get_stock_qte = ttk.Button(self.content, text="Get Quote", command=self.btn_get_stock_quote) self.btn_get_intra_day = ttk.Button(self.content, text="Get Intra Day", command=self.get_intra_day) self.btn_get_daily_stock = ttk.Button(self.content, text="Get Daily Stock", command=self.get_daily_stock) #Add tree view self.output_tree = ttk.Treeview(self.content, selectmode='browse') self.output_tree.bind('<Double 1>', self.OnTreeDoubleClick) self.output_tree.bind('<Button 1>', self.OnTreeSingleClick) self.output_tree.bind('<ButtonRelease 1>', self.OnLeftBtnReleased) self.output_tree.bind('<Button-3>', self.OnRightClick) #scroll bar for Tree self.vert_scroll = ttk.Scrollbar(self.content, orient=VERTICAL, command=self.output_tree.yview) self.output_tree.configure(yscrollcommand=self.vert_scroll.set) self.horiz_scroll = ttk.Scrollbar(self.content, orient=HORIZONTAL, command=self.output_tree.xview) self.output_tree.configure(xscrollcommand=self.horiz_scroll.set) # plot variable used on single & double click of TreeView row self.f = Figure(figsize=(15, 6), dpi=100, facecolor='w', edgecolor='k', tight_layout=True) self.output_canvas = FigureCanvasTkAgg(self.f, master=self.content) self.toolbar_frame = Frame(master=self.root) self.toolbar = NavigationToolbar2Tk(self.output_canvas, self.toolbar_frame) # Now put all this on grid self.exchange_label.grid(row=0, column=0, sticky=E) self.exchange_combo.grid(row=0, column=1, sticky=W) self.symbol_label.grid(row=0, column=2, sticky=E) self.symbol_entry.grid(row=0, column=3, sticky=W) self.price_label.grid(row=0, column=4, sticky=E) self.price_entry.grid(row=0, column=5, sticky=W) self.purchasedate_label.grid(row=0, column=6, sticky=E) self.purchasedate_entry.grid(row=0, column=7, sticky=W) self.btn_get_stock_qte.grid(row=0, column=8, padx=5, pady=5) self.btn_get_intra_day.grid(row=0, column=9, padx=5, pady=5) self.btn_get_daily_stock.grid(row=0, column=10, padx=5, pady=5) self.output_tree.grid(row=1, column=0, rowspan=1, columnspan=11, sticky=(N, E, W, S)) self.vert_scroll.grid(row=1, column=11, sticky=(N, E, S)) self.horiz_scroll.grid(row=2, column=0, columnspan=11, sticky=(N, E, W, S)) self.output_canvas.get_tk_widget().grid(row=3, column=0, columnspan=11, sticky=(N, E, W)) self.toolbar_frame.grid(row=4, column=0, columnspan=11, sticky=(N, E, W)) self.toolbar.grid(row=0, column=0, sticky=(N, W)) # Now set the stretch options so that the widget are seen properly when window is resized self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) self.content.columnconfigure(0, weight=1) self.content.columnconfigure(0, weight=3) self.content.columnconfigure(1, weight=3) self.content.columnconfigure(2, weight=3) self.content.columnconfigure(3, weight=3) self.content.columnconfigure(4, weight=3) self.content.columnconfigure(5, weight=3) self.content.columnconfigure(6, weight=3) self.content.columnconfigure(7, weight=3) self.content.columnconfigure(8, weight=1) self.content.columnconfigure(9, weight=1) self.content.columnconfigure(10, weight=1) # this will also take care of vertical resize, where we want the text box to be expanded # content.rowconfigure(1, weight=1) #tree # content.rowconfigure(2, weight=1) #horiz scrl # content.rowconfigure(3, weight=1) #canvas # content.rowconfigure(4, weight=1) #frame for toolbar mainloop()
def covid_numbers_country(self, event): """ Helps getting countries' statistics for covid-19""" self.clear() list_to_display = [] requested_country = covid_case.get_status_by_country_name( self.country.get()) data_requested = { key: requested_country[key] for key in requested_country.keys() and {'confirmed', 'active', 'deaths', 'recovered'} } # Add every case to the new list list_to_display.append("Comfirmed cases: " + str(data_requested['confirmed']) + '\n' + '\n') list_to_display.append("Active cases: " + str(data_requested['active']) + '\n' + '\n') list_to_display.append("Total recovered: " + str(data_requested['recovered']) + '\n' + '\n') list_to_display.append("Total deaths: " + str(data_requested['deaths']) + '\n' + '\n') # Display countries' statistics into text widget for text in list_to_display: self.text2.tag_configure("center", justify='center') self.text2.insert(END, text) self.text2.tag_add("center", "1.0", "end") cases = ['Confirmed', 'Active', 'Recovered', 'Deaths'] numbers = [ data_requested['confirmed'], data_requested['active'], data_requested['recovered'], data_requested['deaths'] ] try: self.get_the_drawing = self.fig_to_canvas.get_tk_widget( ).grid_forget() except AttributeError: pass # Creating figure figure = Figure(figsize=(5, 4), dpi=80) # Plot the graph inside the figure plot = figure.add_subplot(1, 1, 1) plot.bar(cases, numbers) plot.set_title(self.country.get(), fontsize=12) plot.set_xlabel('Cases', fontsize=10) plot.set_ylabel('Numbers', fontsize=10) # plot.set_tick_params(labelsize=12) # Creating canvas self.fig_to_canvas = FigureCanvasTkAgg(figure, self.canvas2) self.fig_to_canvas.get_tk_widget().grid(sticky='w') self.fig_to_canvas.draw()
def plot(self, peptide, modinfo, charge, nce, instrument): ions = {} bions, pepmass = calc_b_ions(peptide, modinfo) print("parent m/z (%d+) = %.6f" % (charge, pepmass / charge + self.mass_proton)) if 'b{}' in self.config.ion_types: ions['b{}'] = bions if 'y{}' in self.config.ion_types: ions['y{}'] = calc_y_from_b(bions, pepmass) if 'c{}' in self.config.ion_types: ions['c{}'] = calc_c_from_b(bions) if 'z{}' in self.config.ion_types: ions['z{}'] = calc_z_from_b(bions, pepmass) if 'b{}-ModLoss' in self.config.ion_types: ions['b{}-ModLoss'] = calc_ion_modloss(bions, peptide, modinfo, N_term=True) if 'y{}-ModLoss' in self.config.ion_types: ions['y{}-ModLoss'] = calc_ion_modloss(ions['y{}'], peptide, modinfo, N_term=False) max_plot_mz = min( self.max_plot_mz, max([max(tmp_ions) for tmp_ions in ions.values()]) + 200) if self.show_plot: fig = Figure(figsize=(12, 8)) ax = get_ax(fig) else: fig = None ax = None self.spec_charge = charge self.pepmass = pepmass buckets = self.ion2vec.FeaturizeOnePeptide_buckets( peptide, modinfo, self.spec_charge, nce, instrument) if buckets is None: return predictions = self.model.Predict(buckets)[len(peptide)][0][0, :, :] matched_inten2 = self.Plot_Predict(ax, ions, predictions) if self.show_plot: ax.text(200, 1.3, '{} ({}+), {}'.format(peptide, self.spec_charge, modinfo), fontsize=14) ax.set_xlim(xmin=0, xmax=max_plot_mz) ax.set_ylim(ymin=0, ymax=1.4) ax.hlines([0], [0], [max_plot_mz]) ax.set_xlabel('m/z') ax.set_ylabel('Relative Abundance') ylabels = ax.get_yticks().tolist() # ylabels = ["{:.0f}%".format(abs(float(label)*100)) if float(label) >= 0 else '' for label in ylabels] ylabels = [ "{:.0f}%".format(abs(float(label) * 100)) for label in ylabels ] #ylabels = ['' for label in ylabels] ax.set_yticklabels(ylabels) return fig
def process_abba_band(recipe, utdate, refdate, band, obsids, frametypes, config, do_interactive_figure=False, threshold_a0v=0.1, objname="", multiply_model_a0v=False, html_output=False): from libs.products import ProductDB, PipelineStorage if recipe == "A0V_AB": FIX_TELLURIC = False elif recipe == "STELLAR_AB": FIX_TELLURIC = True elif recipe == "EXTENDED_AB": FIX_TELLURIC = True elif recipe == "EXTENDED_ONOFF": FIX_TELLURIC = True else: raise ValueError("Unsupported Recipe : %s" % recipe) if 1: igr_path = IGRINSPath(config, utdate) igr_storage = PipelineStorage(igr_path) obj_filenames = igr_path.get_filenames(band, obsids) master_obsid = obsids[0] tgt_basename = os.path.splitext(os.path.basename(obj_filenames[0]))[0] db = {} basenames = {} db_types = ["flat_off", "flat_on", "thar", "sky"] for db_type in db_types: db_name = igr_path.get_section_filename_base( "PRIMARY_CALIB_PATH", "%s.db" % db_type, ) db[db_type] = ProductDB(db_name) # db on output path db_types = ["a0v"] for db_type in db_types: db_name = igr_path.get_section_filename_base( "OUTDATA_PATH", "%s.db" % db_type, ) db[db_type] = ProductDB(db_name) # to get basenames db_types = ["flat_off", "flat_on", "thar", "sky"] if FIX_TELLURIC: db_types.append("a0v") for db_type in db_types: basenames[db_type] = db[db_type].query(band, master_obsid) if 1: # make aperture from libs.storage_descriptions import SKY_WVLSOL_JSON_DESC sky_basename = db["sky"].query(band, master_obsid) wvlsol_products = igr_storage.load([SKY_WVLSOL_JSON_DESC], sky_basename)[SKY_WVLSOL_JSON_DESC] orders_w_solutions = wvlsol_products["orders"] wvl_solutions = map(np.array, wvlsol_products["wvl_sol"]) # prepare i1i2_list from libs.storage_descriptions import ORDER_FLAT_JSON_DESC prod = igr_storage.load([ORDER_FLAT_JSON_DESC], basenames["flat_on"])[ORDER_FLAT_JSON_DESC] new_orders = prod["orders"] i1i2_list_ = prod["i1i2_list"] order_indices = [] for o in orders_w_solutions: o_new_ind = np.searchsorted(new_orders, o) order_indices.append(o_new_ind) i1i2_list = get_fixed_i1i2_list(order_indices, i1i2_list_) from libs.storage_descriptions import (SPEC_FITS_DESC, SN_FITS_DESC) if 1: # load target spectrum tgt_spec_ = igr_storage.load([SPEC_FITS_DESC], tgt_basename)[SPEC_FITS_DESC] tgt_spec = list(tgt_spec_.data) tgt_sn_ = igr_storage.load([SN_FITS_DESC], tgt_basename)[SN_FITS_DESC] tgt_sn = list(tgt_sn_.data) fig_list = [] # telluric if 1: #FIX_TELLURIC: A0V_basename = db["a0v"].query(band, master_obsid) from libs.storage_descriptions import SPEC_FITS_FLATTENED_DESC telluric_cor_ = igr_storage.load( [SPEC_FITS_FLATTENED_DESC], A0V_basename)[SPEC_FITS_FLATTENED_DESC] #A0V_path = ProductPath(igr_path, A0V_basename) #fn = A0V_path.get_secondary_path("spec_flattened.fits") telluric_cor = list(telluric_cor_.data) a0v_spec_ = igr_storage.load([SPEC_FITS_DESC], A0V_basename)[SPEC_FITS_DESC] a0v_spec = list(a0v_spec_.data) if 1: if do_interactive_figure: from matplotlib.pyplot import figure as Figure else: from matplotlib.figure import Figure fig1 = Figure(figsize=(12, 6)) fig_list.append(fig1) ax1a = fig1.add_subplot(211) ax1b = fig1.add_subplot(212, sharex=ax1a) for wvl, s, sn in zip(wvl_solutions, tgt_spec, tgt_sn): #s[s<0] = np.nan #sn[sn<0] = np.nan ax1a.plot(wvl, s) ax1b.plot(wvl, sn) ax1a.set_ylabel("Counts [DN]") ax1b.set_ylabel("S/N per Res. Element") ax1b.set_xlabel("Wavelength [um]") ax1a.set_title(objname) if FIX_TELLURIC: fig2 = Figure(figsize=(12, 6)) fig_list.append(fig2) ax2a = fig2.add_subplot(211) ax2b = fig2.add_subplot(212, sharex=ax2a) #from libs.stddev_filter import window_stdev tgt_spec_cor = [] #for s, t in zip(s_list, telluric_cor): for s, t, t2 in zip(tgt_spec, a0v_spec, telluric_cor): st = s / t #print np.percentile(t[np.isfinite(t)], 95), threshold_a0v t0 = np.percentile(t[np.isfinite(t)], 95) * threshold_a0v st[t < t0] = np.nan st[t2 < threshold_a0v] = np.nan tgt_spec_cor.append(st) if multiply_model_a0v: # multiply by A0V model from libs.a0v_spec import A0VSpec a0v_model = A0VSpec() a0v_interp1d = a0v_model.get_flux_interp1d(1.3, 2.5, flatten=True, smooth_pixel=32) for wvl, s in zip(wvl_solutions, tgt_spec_cor): aa = a0v_interp1d(wvl) s *= aa for wvl, s, t in zip(wvl_solutions, tgt_spec_cor, telluric_cor): ax2a.plot(wvl, t, "0.8", zorder=0.5) ax2b.plot(wvl, s, zorder=0.5) s_max_list = [] s_min_list = [] for s in tgt_spec_cor[3:-3]: s_max_list.append(np.nanmax(s)) s_min_list.append(np.nanmin(s)) s_max = np.max(s_max_list) s_min = np.min(s_min_list) ds_pad = 0.05 * (s_max - s_min) ax2a.set_ylabel("A0V flattened") ax2a.set_ylim(-0.05, 1.1) ax2b.set_ylabel("Target / A0V") ax2b.set_xlabel("Wavelength [um]") ax2b.set_ylim(s_min - ds_pad, s_max + ds_pad) ax2a.set_title(objname) # save figures if fig_list: for fig in fig_list: fig.tight_layout() figout = igr_path.get_section_filename_base("QA_PATH", "spec_" + tgt_basename, "spec_" + tgt_basename) #figout = obj_path.get_secondary_path("spec", "spec_dir") from libs.qa_helper import figlist_to_pngs figlist_to_pngs(figout, fig_list) # save html if html_output: dirname = config.get_value('HTML_PATH', utdate) objroot = "%04d" % (master_obsid, ) html_save(utdate, dirname, objroot, band, orders_w_solutions, wvl_solutions, tgt_spec, tgt_sn, i1i2_list) if FIX_TELLURIC: objroot = "%04dA0V" % (master_obsid, ) html_save(utdate, dirname, objroot, band, orders_w_solutions, wvl_solutions, telluric_cor, tgt_spec_cor, i1i2_list, spec_js_name="jj_a0v.js") if do_interactive_figure: import matplotlib.pyplot as plt plt.show()
from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, # not FigureCanvasTk NavigationToolbar2Tk # not NavigationToolbar2TkAgg ) import tkinter as tk # --- random data --- import random y = [random.randint(-100, 100) for x in range(200)] # --- GUI --- root = tk.Tk() #fig = plt.Figure() fig = Figure() canvas = FigureCanvasTkAgg(fig, root) canvas.get_tk_widget().pack() navbar = NavigationToolbar2Tk(canvas, root) #navbar.update() # not needed #ax = fig.add_subplot(111) ax = fig.subplots() ax.plot(y) root.mainloop()
class Canvas(object): figure = Figure()
def sweeper_layout(self): frame_param = tk.Frame(self.tab_sweeeper, bg='grey', width=200, height=1080) frame_param.pack(side='left', expand='no', fill='y') frame_figure = tk.Frame(self.tab_sweeeper, bg='beige', width=1000, height=1080, padx=4) frame_figure.pack(side='right', expand='yes', fill='both') #开始与结束的频率 tk.Label(frame_param, text='sweep from', width=12, anchor='nw', relief='ridge', pady=1).grid(row=1, column=1, sticky='n') tk.Label(frame_param, text='sweep to', width=12, anchor='nw', relief='ridge', pady=1).grid(row=2, column=1, sticky='n') sweep_from = tk.StringVar() sweep_to = tk.StringVar() self.sf = tk.Entry(frame_param, textvariable=sweep_from, width=10) self.st = tk.Entry(frame_param, textvariable=sweep_to, width=10) self.sf.insert(0, 33700) self.st.insert(0, 33900) self.sf.grid(row=1, column=2) self.st.grid(row=2, column=2) #扫描点数 tk.Label(frame_param, text='sample count', width=12, anchor='nw', relief='ridge', pady=1).grid(row=4, column=1, sticky='n') sample_num = tk.StringVar() sample_count = tk.Entry(frame_param, textvariable=sample_num, width=10) sample_count.insert(0, 40) sample_count.grid(row=4, column=2) #进度 tk.Label(frame_param, text='Progress', width=12, anchor='nw', relief='ridge', pady=1).grid(row=8, column=1, sticky='n') sweep_progress_str = tk.StringVar() sweep_progerss = tk.Entry(frame_param, width=10) sweep_progerss.grid(row=8, column=2) #Q值 tk.Label(frame_param, text='Q', width=12, anchor='nw', relief='ridge', pady=1).grid(row=9, column=1, sticky='n') q_str = tk.StringVar() q = tk.Entry(frame_param, width=10, textvariable=q_str) q.grid(row=9, column=2) #共振频率 tk.Label(frame_param, text='hamo_freq', width=12, anchor='nw', relief='ridge', pady=1).grid(row=10, column=1, sticky='n') hamo_freq_str = tk.DoubleVar() hamo_freq_entry = tk.Entry(frame_param, width=10, textvariable=hamo_freq_str) hamo_freq_entry.grid(row=10, column=2) #信号幅值 tk.Label(frame_param, text='max_sigin', width=12, anchor='nw', relief='ridge', pady=1).grid(row=11, column=1, sticky='n') max_sigin_str = tk.DoubleVar() max_sigin_entry = tk.Entry(frame_param, width=10, textvariable=max_sigin_str) max_sigin_entry.grid(row=11, column=2) #开始 tk.Button( frame_param, text='start', width=12, command=lambda: self.start_sweep( self.sf.get(), self.st.get(), sample_count.get(), canvas, aix1, aix2, q, sweep_progerss, max_sigin_str, hamo_freq_str)).grid( row=12, column=1, sticky='w') ##绑定鼠标单击更新q,hamo_freq,max_sigin frame_param.bind( sequence='<Button-1>', func=lambda x: self.refresh_para_of_fre_q_sigin( eval(q_str.get()), hamo_freq_str.get(), max_sigin_str.get())) ##在frame_fig中创建画布和轴 fig = Figure(figsize=(5, 5), dpi=100) canvas = FigureCanvasTkAgg(figure=fig, master=frame_figure) aix1 = fig.add_subplot(211) aix2 = fig.add_subplot(212) canvas.get_tk_widget().pack(side='top', fill='both', expand=1) canvas.draw() toobar = NavigationToolbar2Tk(canvas, frame_figure) toobar.update() #测试 list = [1, 2, 3, 4, 5, 6] function.plot_fig_sweep(canvas, aix1, aix2, list, list, list, list)
def run(filename, outfilename, plot_dir=None, tell_file='data/TelluricModel.dat', blaze_corrected=False): # prepare figures and axes if plot_dir is None: #interactive mode from matplotlib.pyplot import figure as Figure else: from matplotlib.figure import Figure fig1 = Figure(figsize=(12, 6)) ax1 = fig1.add_subplot(111) orders, order_numbers = read_data(filename, debug=False) tell_model = get_tell_model(tell_file) kwargs = {} if blaze_corrected: kwargs["N"] = None else: print 'Roughly removing blaze function for {}'.format(filename) filtered_orders, original_pixels = remove_blaze(orders, tell_model, **kwargs) corrected_orders = [] print 'Optimizing wavelength for order ', for o_n, order in zip(order_numbers, filtered_orders): l_orig = plot_spec(ax1, order[0], order[1], 'k-', alpha=0.4) l_model = plot_spec(ax1, order[0], tell_model(order[0]), 'r-', alpha=0.6) # Use the wavelength fit function to fit the wavelength. print ' {}'.format(o_n), sys.stdout.flush() new_order = optimize_wavelength(order, tell_model, fitorder=2) l_modified = plot_spec(ax1, new_order[0], new_order[1], 'g-', alpha=0.4) corrected_orders.append(new_order) # do not trt to plot if number valid points is less than 2 if len(order[0]) < 2: continue ax1.legend([l_model, l_orig, l_modified], ["Telluric Model", "Original Spec.", "Modified Spec."]) if plot_dir is not None: ax1.set_title('Individual order fit : {}'.format(o_n)) ax1.set_xlim(order[0][0], order[0][-1]) ax1.set_ylim(-0.05, 1.15) figout = os.path.join(plot_dir, 'individual_order') postfix = "_%03d" % (o_n, ) from igrins.libs.qa_helper import fig_to_png fig_to_png(figout, fig1, postfix=postfix) # fig1.savefig('{}{}-individual_order{}.png'.format(plot_dir, filename.split('/')[-1], i+1)) ax1.cla() print original_orders = [o.copy() for o in orders] # Now, fit the entire chip to a surface fig3d = Figure() import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") ax3d = fig3d.add_subplot(111, projection='3d') final_orders = fit_chip(original_orders, corrected_orders, original_pixels, order_numbers, tell_model, ax3d=ax3d) if plot_dir is not None: figout = os.path.join(plot_dir, 'fullchip_fit') from igrins.libs.qa_helper import fig_to_png fig_to_png(figout, fig3d) fig3 = Figure(figsize=(12, 6)) ax3 = fig3.add_subplot(111) # Filter again just for plotting final_filtered, _ = remove_blaze(final_orders, tell_model, **kwargs) for o_n, order in zip(order_numbers, final_filtered): l_final = plot_spec(ax3, order[0], order[1], 'k-', alpha=0.4) l_model = plot_spec(ax3, order[0], tell_model(order[0]), 'r-', alpha=0.6) if len(order[0]) < 2: continue ax3.legend([l_model, l_final], ["Telluric Model", "Final Spec."]) if plot_dir is not None: ax3.set_title('Final wavelength solution : {}'.format(o_n)) ax3.set_xlim(order[0][0], order[0][-1]) ax3.set_ylim(-0.05, 1.15) figout = os.path.join(plot_dir, 'final_order') postfix = "_%03d" % (o_n, ) from igrins.libs.qa_helper import fig_to_png fig_to_png(figout, fig3, postfix=postfix) # fig1.savefig('{}{}-individual_order{}.png'.format(plot_dir, filename.split('/')[-1], i+1)) ax3.cla() if plot_dir is None: ax3.set_title('Final wavelength solution') import matplotlib.pyplot as plt with warnings.catch_warnings(): warnings.simplefilter("ignore") plt.show() # Output wave_arr = np.array([o[0] for o in final_orders]) hdulist = fits.PrimaryHDU(wave_arr) hdulist.writeto(outfilename, clobber=True)
def reconfigure_axes(self): if not hasattr(self, "fig"): self.fig = Figure() if not hasattr(self, "canvas"): self.canvas = FigureCanvas(self.fig) if not hasattr(self, "ax"): self.ax = self.fig.add_subplot(111) self.ax.clear() else: self.ax.clear() self.files = [] self.peaks = [] for sheet_file in self.sheet_files[0]: dx, dy = self.get_rx_spectrum( sheet_file, interpolation=self.interpolate_cb.currentText()) self.files.append(sheet_file.split('/')[-1].split('.')[0][-4:]) self.peaks.append(dx[dy.argmax()]) plot = self.plot_cb.currentText() if plot == "Normalised": dy = dy / max(dy) elif plot == "Desibles": dy = 20 * np.log(dy / max(dy)) if self.legend_chb.isChecked(): if self.peaks_chb.isChecked(): self.ax.plot( dx, dy, label= f"{sheet_file.split('/')[-1]},{dx[dy.argmax()]:.3f}") else: self.ax.plot(dx, dy, label=f"{sheet_file.split('/')[-1]}") else: self.ax.plot(dx, dy) # self.ax.scatter(dx[ymaxp], dy[ymaxp],label = 'peak L:' + )) if self.plot_cb.currentText() == "Raw": self.ax.set_title("FBG Spectrums") self.ax.set_ylabel("Amplitude (AU)") self.ax.set_xlabel("Wavelength (nm)") self.ax.set_xlim(1511, 1594) if self.legend_chb.isChecked(): self.ax.legend() if self.plot_cb.currentText() == "Normalised": self.ax.set_title("Normalised FBG Spectrums") self.ax.set_ylabel("Normalised Amplitude (AU)") self.ax.set_xlabel("Wavelength (nm)") self.ax.set_xlim(1511, 1594) if self.legend_chb.isChecked(): self.ax.legend() if self.plot_cb.currentText() == "Peaks": self.ax.clear() self.ax.set_title("Peaks in FBG Spectrums") self.ax.set_ylabel("Peak Wavelength (nm)") self.ax.set_xlabel("Files") self.ax.plot(np.arange(len(self.peaks)), self.peaks) self.ax.plot(self.files, self.peaks) if self.plot_cb.currentText() == "Desibels": self.ax.set_title("FBG Spectrums in Desibels") self.ax.set_ylabel("Amplitude (dB)") self.ax.set_xlabel("Wavelength (nm)") self.ax.set_xlim(1511, 1594) if self.legend_chb.isChecked(): self.ax.legend() self.ax.grid("True") # self.fig.subplots_adjust(top=0.921, # bottom=0.123, # left=0.169, # right=0.972, # hspace=0.2, # wspace=0.2 # ) self.fig.tight_layout() if not hasattr(self, "image"): self.image = FigureCanvas(self.fig) self.screen.addWidget(self.image) if not hasattr(self, "toolbar"): self.toolbar = NavigationToolbar(self.image, self.display, coordinates=True) self.screen.addWidget(self.toolbar) self.fig.canvas.draw() self.statusbar.showMessage("Reconfigured Plot")
def __init__(self, master=None, argkey=None, argscript="", argoutputtree=None, argIsTest=False, argDataFolder=None): Toplevel.__init__(self, master=master) #self.wm_state(newstate='zoomed') self.wm_state(newstate='normal') #self.wm_resizable(width=False, height=False) self.key = argkey self.script = argscript self.output_tree = argoutputtree self.bool_test = argIsTest self.datafolderpath = argDataFolder #graph filter params self.pastdate = str(date.today()) self.graphctr = 1 if (len(self.script) <= 0): self.wm_title("Get Quote") else: self.wm_title("Get Quote: " + self.script) self.search_symbol_combo_text.set(argscript) #self.configure(padx=5, pady=10) self.wm_protocol("WM_DELETE_WINDOW", self.OnClose) self.iscancel = False #check box buttons self.bdaily = BooleanVar() self.bintra = BooleanVar() self.bsma = BooleanVar() self.bema = BooleanVar() self.bvwap = BooleanVar() self.bmacd = BooleanVar() self.brsi = BooleanVar() self.badx = BooleanVar() self.baroon = BooleanVar() self.brsi = BooleanVar() self.bdaily.set(False) self.bintra.set(False) self.bsma.set(False) self.bema.set(False) self.bvwap.set(False) self.bmacd.set(False) self.brsi.set(False) self.badx.set(False) self.baroon.set(False) self.brsi.set(False) self.frame1 = ttk.Frame(self, borderwidth=5, relief="sunken") #, width=200, height=100) self.frame2 = ttk.Frame(self, borderwidth=5, relief="sunken") #, width=200, height=100) self.search_symbol_label = ttk.Label(self, text='*Search Symbol: ') self.search_symbol_combo_text = StringVar() #self.search_symbol_combo = ttk.Combobox(self, textvariable=self.search_symbol_combo_text,state='normal', postcommand=self.commandSearchSymbol) self.search_symbol_combo = ttk.Combobox( self, width=60, textvariable=self.search_symbol_combo_text, state='normal') self.search_symbol_combo.bind('<Return>', self.commandEnterKey) self.open_label = ttk.Label(self.frame2, text='Open: ') self.open_val_label = ttk.Label(self.frame2, text='ABCD') self.high_label = ttk.Label(self.frame2, text='High: ') self.high_val_label = ttk.Label(self.frame2, text='ABCD') self.low_label = ttk.Label(self.frame2, text='Low: ') self.low_val_label = ttk.Label(self.frame2, text='ABCD') self.price_label = ttk.Label(self.frame2, text='Price: ') self.price_val_label = ttk.Label(self.frame2, text='ABCD') self.volume_label = ttk.Label(self.frame2, text='Volume: ') self.volume_val_label = ttk.Label(self.frame2, text='ABCD') self.latesttradingday_label = ttk.Label(self.frame2, text='Latest Trading Day: ') self.latesttradingday_val_label = ttk.Label(self.frame2, text='ABCD') self.prevclose_label = ttk.Label(self.frame2, text='Previous Close: ') self.prevclose_val_label = ttk.Label(self.frame2, text='ABCD') self.change_label = ttk.Label(self.frame2, text='Change: ') self.change_val_label = ttk.Label(self.frame2, text='ABCD') self.changepct_label = ttk.Label(self.frame2, text='Change %: ') self.changepct_val_label = ttk.Label(self.frame2, text='ABCD') self.f = Figure(figsize=(12.6, 8.55), dpi=100, facecolor='w', edgecolor='k', tight_layout=True, linewidth=0.5) self.output_canvas = FigureCanvasTkAgg(self.f, master=self) self.toolbar_frame = Frame(master=self) self.toolbar = NavigationToolbar2Tk(self.output_canvas, self.toolbar_frame) self.btn_search_script = ttk.Button(self, text="Search Script", command=self.btnSearchScript) self.btn_get_quote = ttk.Button(self, text="Get Quote", command=self.btnGetQuote) self.btn_get_daily_close = ttk.Button(self, text="Show selected graphs", command=self.btnGetDailyClose) self.btn_cancel = ttk.Button(self, text="Close", command=self.btnCancel) self.btn_add_script = ttk.Button(self, text="Add script", command=self.btnAddScript) self.checkdaily = ttk.Checkbutton(self.frame1, text="Daily close", variable=self.bdaily, onvalue=True) self.checkintra = ttk.Checkbutton(self.frame1, text="Intra day", variable=self.bintra, onvalue=True) self.checksma = ttk.Checkbutton(self.frame1, text="SMA", variable=self.bsma, onvalue=True) self.checkema = ttk.Checkbutton(self.frame1, text="EMA", variable=self.bema, onvalue=True) self.checkvwap = ttk.Checkbutton(self.frame1, text="VWAP", variable=self.bvwap, onvalue=True) self.checkmacd = ttk.Checkbutton(self.frame1, text="MACD", variable=self.bmacd, onvalue=True) self.checkrsi = ttk.Checkbutton(self.frame1, text="RSI", variable=self.brsi, onvalue=True) self.checkadx = ttk.Checkbutton(self.frame1, text="ADX", variable=self.badx, onvalue=True) self.checkaroon = ttk.Checkbutton(self.frame1, text="AROON", variable=self.baroon, onvalue=True) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.search_symbol_label.grid_configure(row=0, column=0, sticky=(N, E), padx=5, pady=5) self.search_symbol_combo.grid_configure(row=0, column=1, sticky=(N, S, E, W), columnspan=3, padx=5, pady=5) self.btn_search_script.grid_configure(row=0, column=4, padx=5, pady=5) self.btn_get_quote.grid_configure(row=0, column=5, pady=5) self.btn_add_script.grid_configure(row=0, column=6, pady=5) self.frame1.grid_configure(row=0, column=7, columnspan=8, rowspan=4, sticky=(N, S, E, W), padx=5, pady=5) self.checkdaily.grid_configure(row=0, column=0, sticky=(W)) self.checkintra.grid_configure(row=0, column=1, sticky=(W)) self.checksma.grid_configure(row=0, column=2, sticky=(W)) self.checkema.grid_configure(row=1, column=0, sticky=(W)) self.checkvwap.grid_configure(row=1, column=1, sticky=(W)) self.checkmacd.grid_configure(row=1, column=2, sticky=(W)) self.checkrsi.grid_configure(row=2, column=0, sticky=(W)) self.checkadx.grid_configure(row=2, column=1, sticky=(W)) self.checkaroon.grid_configure(row=2, column=2, sticky=(W)) self.btn_get_daily_close.grid_configure(row=0, column=15, padx=5, pady=5) self.btn_cancel.grid_configure(row=2, column=15, padx=5, pady=5) self.frame2.grid_configure(row=1, column=0, columnspan=7, rowspan=3, sticky=(N, S, E, W), padx=5, pady=5) self.open_label.grid_configure(row=1, column=0, sticky='E') self.open_val_label.grid_configure( row=1, column=1, padx=35, sticky='W') #, columnspan=2, sticky='NW') self.high_label.grid_configure(row=1, column=3, sticky='E') #, columnspan=2) self.high_val_label.grid_configure(row=1, column=4, padx=35, sticky='W') #, sticky='NW') self.low_label.grid_configure( row=1, column=6, sticky='E') #, columnspan=2, sticky='NE') self.low_val_label.grid_configure(row=1, column=7, padx=35, sticky='W') #,sticky='NW') self.price_label.grid_configure(row=2, column=0, sticky='E') #, sticky='NE') self.price_val_label.grid_configure( row=2, column=1, padx=35, sticky='W') #, columnspan=2, sticky='NW') self.volume_label.grid_configure( row=2, column=3, sticky='E') #, columnspan=2, sticky='NE') self.volume_val_label.grid_configure(row=2, column=4, padx=35, sticky='W') #, sticky='NW') self.latesttradingday_label.grid_configure( row=2, column=6, sticky='E') #,columnspan=2, sticky='NE') self.latesttradingday_val_label.grid_configure( row=2, column=7, padx=35, sticky='W') #, sticky='NW') self.prevclose_label.grid_configure(row=3, column=0, sticky='E') #, sticky='NE') self.prevclose_val_label.grid_configure( row=3, column=1, padx=35, sticky='W') #, columnspan=2, sticky='NW') self.change_label.grid_configure( row=3, column=3, sticky='E') #, columnspan=2, sticky='NE') self.change_val_label.grid_configure(row=3, column=4, padx=35, sticky='W') #, sticky='NW') self.changepct_label.grid_configure( row=3, column=6, sticky='E') #, columnspan=2, sticky='NE') self.changepct_val_label.grid_configure(row=3, column=7, padx=35, sticky='W') #, sticky='NW') self.output_canvas.get_tk_widget().grid(row=5, column=0, columnspan=17, sticky=(N, E, W, S)) self.toolbar_frame.grid(row=6, column=0, columnspan=17, rowspan=1, sticky=(N, E, W, S)) self.toolbar.grid(row=0, column=2, sticky=(N, W))
def initMatplotlib(self): self.fig = Figure(figsize=(9, 7)) self.canvas = FigureCanvas(self.fig) self.mapLayout.addWidget(self.canvas)
def test_matplotlib_view(): from matplotlib.pyplot import Figure assert isinstance(_try_get_matplotlib_canvas(Figure()), QWidget)
def __init__(self, master=None, argistestmode=False, argkey='XXXX', argscript='', argmenucalled=False, arggraphid=-1, argoutputtree=None, **kw): super().__init__(master=master, **kw) self.wm_state(newstate='zoomed') self.wm_title("Graphs") self.key = argkey self.script = argscript self.bool_test = argistestmode self.bool_menucalled = argmenucalled self.graphid = arggraphid self.output_tree = argoutputtree self.pastdate = str(date.today()) self.wm_protocol("WM_DELETE_WINDOW", self.OnClose) self.frame1 = ttk.Frame(self, borderwidth=5, relief="sunken") self.frame2 = ttk.Frame(self, borderwidth=5, relief="sunken") #search script related widgets self.search_symbol_label = ttk.Label(self.frame1, text='*Search Symbol: ') self.search_symbol_combo_text = StringVar() self.search_symbol_combo = ttk.Combobox( self.frame1, width=60, textvariable=self.search_symbol_combo_text, state='normal') self.search_symbol_combo.bind('<Return>', self.commandEnterKey) self.btn_search_script = ttk.Button(self.frame1, text="Search Script", command=self.btnSearchScript) self.btn_add_script = ttk.Button(self.frame1, text="Add to portfolio", command=self.btnAddScript) self.btn_cancel = ttk.Button(self.frame1, text="Close", command=self.OnClose) self.graph_select_label = ttk.Label(self.frame1, text='*Select Graph: ') self.graph_select_combo_text = StringVar() self.graph_select_combo = ttk.Combobox( self.frame1, width=60, textvariable=self.graph_select_combo_text, values=[ 'Daily Price', 'Intraday', 'Simple Moving Avg', 'Volume weighted avg price', 'Relative Strength Index', 'Avg directional movement index', 'stochastic oscillator', 'moving average convergence / divergence', 'Aroon', 'Bollinger bands' ], state='readonly') self.graph_select_combo_text.set('Daily Price') self.graph_select_combo.current(0) self.graph_select_combo.bind('<<ComboboxSelected>>', self.OnGraphSelectionChanged) self.btn_show_graph = ttk.Button(self.frame1, text="Show selected graphs", command=self.btnShowGraph) self.outputsize_label = ttk.Label(self.frame2, text='Output size: ') self.outpusize_combo_text = StringVar() self.outputsize_combo = ttk.Combobox( self.frame2, width=10, textvariable=self.outpusize_combo_text, values=['compact', 'full'], state='normal') self.outpusize_combo_text.set('compact') self.outputsize_combo.current(0) self.interval_label = ttk.Label(self.frame2, text='Interval: ') self.interval_combo_text = StringVar() self.interval_combo = ttk.Combobox( self.frame2, width=10, textvariable=self.interval_combo_text, values=[ '1min', '5min', '15min', '30min', '60min', 'daily', 'weekly', 'monthly' ], state='normal') self.interval_combo_text.set('15min') self.interval_combo.current(2) self.time_period_label = ttk.Label( self.frame2, text='Time period(positive int:10/20): ') self.time_period_text = StringVar(10) self.time_period_entry = ttk.Entry(self.frame2, textvariable=self.time_period_text, width=3) self.series_type_label = ttk.Label(self.frame2, text='Series Type: ') self.series_type_combo_text = StringVar() self.series_type_combo = ttk.Combobox( self.frame2, width=10, textvariable=self.series_type_combo_text, values=['open', 'high', 'low', 'close'], state='normal') self.series_type_combo_text.set('close') self.series_type_combo.current(3) self.fastkperiod_label = ttk.Label( self.frame2, text='Time period fastk moving avg(positive int): ') self.fastkperiod_text = StringVar('5') self.fastkperiod_entry = ttk.Entry(self.frame2, textvariable=self.fastkperiod_text, width=3) self.slowkperiod_label = ttk.Label( self.frame2, text='Time period slowk moving avg(positive int): ') self.slowkperiod_text = StringVar('3') self.slowkperiod_entry = ttk.Entry(self.frame2, textvariable=self.slowkperiod_text, width=3) self.slowdperiod_label = ttk.Label( self.frame2, text='Time period slowd moving avg(positive int): ') self.slowdperiod_text = StringVar('3') self.slowdperiod_entry = ttk.Entry(self.frame2, textvariable=self.slowdperiod_text, width=3) self.slowkmatype_label = ttk.Label(self.frame2, text='Slowk mov avg: ') self.slowkmatype_combo_text = StringVar() self.slowkmatype_combo = ttk.Combobox( self.frame2, width=10, textvariable=self.slowkmatype_combo_text, values=[ 'Simple Moving Average (SMA)', 'Exponential Moving Average (EMA)', 'Weighted Moving Average (WMA)', 'Double Exponential Moving Average (DEMA)', 'Triple Exponential Moving Average (TEMA)', 'Triangular Moving Average (TRIMA)', 'T3 Moving Average', 'Kaufman Adaptive Moving Average (KAMA)', 'MESA Adaptive Moving Average (MAMA)' ], state='normal') self.slowkmatype_combo_text.set('Simple Moving Average (SMA)') self.slowkmatype_combo.current(0) self.slowdmatype_label = ttk.Label(self.frame2, text='Slowd mov avg: ') self.slowdmatype_combo_text = StringVar() self.slowdmatype_combo = ttk.Combobox( self.frame2, width=10, textvariable=self.slowdmatype_combo_text, values=[ 'Simple Moving Average (SMA)', 'Exponential Moving Average (EMA)', 'Weighted Moving Average (WMA)', 'Double Exponential Moving Average (DEMA)', 'Triple Exponential Moving Average (TEMA)', 'Triangular Moving Average (TRIMA)', 'T3 Moving Average', 'Kaufman Adaptive Moving Average (KAMA)', 'MESA Adaptive Moving Average (MAMA)' ], state='normal') self.slowdmatype_combo_text.set('Simple Moving Average (SMA)') self.slowdmatype_combo.current(0) self.fastperiod_label = ttk.Label(self.frame2, text='Fast period(positive int): ') self.fastperiod_text = StringVar('12') self.fastperiod_entry = ttk.Entry(self.frame2, textvariable=self.fastperiod_text, width=3) self.slowperiod_label = ttk.Label(self.frame2, text='Slow period(positive int): ') self.slowperiod_text = StringVar('26') self.slowperiod_entry = ttk.Entry(self.frame2, textvariable=self.slowperiod_text, width=3) self.signalperiod_label = ttk.Label( self.frame2, text='Signal period(positive int): ') self.signalperiod_text = StringVar('9') self.signalperiod_entry = ttk.Entry( self.frame2, textvariable=self.signalperiod_text, width=3) self.nbdevup_label = ttk.Label( self.frame2, text= ' Standard deviation multiplier of the upper band(positive int): ') self.nbdevup_text = StringVar('2') self.nbdevup_entry = ttk.Entry(self.frame2, textvariable=self.nbdevup_text, width=3) self.nbdevdn_label = ttk.Label( self.frame2, text= ' Standard deviation multiplier of the lower band(positive int): ') self.nbdevdn_text = StringVar('2') self.nbdevdn_entry = ttk.Entry(self.frame2, textvariable=self.nbdevdn_text, width=3) self.matype_label = ttk.Label(self.frame2, text='Moving avg type: ') self.matype_combo_text = StringVar() self.matype_combo = ttk.Combobox( self.frame2, width=10, textvariable=self.matype_combo_text, values=[ 'Simple Moving Average (SMA)', 'Exponential Moving Average (EMA)', 'Weighted Moving Average (WMA)', 'Double Exponential Moving Average (DEMA)', 'Triple Exponential Moving Average (TEMA)', 'Triangular Moving Average (TRIMA)', 'T3 Moving Average', 'Kaufman Adaptive Moving Average (KAMA)', 'MESA Adaptive Moving Average (MAMA)' ], state='normal') self.slowdmatype_combo_text.set('Simple Moving Average (SMA)') self.slowdmatype_combo.current(0) self.f = Figure(figsize=(12.6, 8.55), dpi=100, facecolor='w', edgecolor='k', tight_layout=True, linewidth=0.5) self.output_canvas = FigureCanvasTkAgg(self.f, master=self) self.toolbar_frame = Frame(master=self) self.toolbar = NavigationToolbar2Tk(self.output_canvas, self.toolbar_frame) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.frame1.grid_configure(row=0, column=0, columnspan=8, rowspan=2, sticky=(N, S, E, W), padx=5, pady=5) self.search_symbol_label.grid_configure(row=0, column=0, sticky=(E)) self.search_symbol_combo.grid_configure(row=0, column=1, sticky=(W)) self.btn_search_script.grid_configure(row=0, column=2, padx=5, pady=5) self.btn_add_script.grid_configure(row=0, column=3, padx=5, pady=5) self.graph_select_label.grid_configure(row=0, column=4, sticky=(E)) self.graph_select_combo.grid_configure(row=0, column=5, sticky=(W)) self.btn_show_graph.grid_configure(row=0, column=6, padx=5, pady=5) self.btn_cancel.grid_configure(row=0, column=7, padx=5, pady=5) self.frame2.grid_configure(row=1, column=0, columnspan=8, rowspan=4, sticky=(N, S, E, W), padx=5, pady=5) self.output_canvas.get_tk_widget().grid(row=6, column=0, columnspan=17, sticky=(N, E, W, S)) self.toolbar_frame.grid(row=7, column=0, columnspan=17, rowspan=1, sticky=(N, E, W, S)) self.toolbar.grid(row=0, column=2, sticky=(N, W)) if (self.bool_menucalled == False): self.wm_title("Graphs - " + self.script) self.search_symbol_combo_text.set(self.script) self.search_symbol_combo['values'] = (self.script) self.search_symbol_combo.current(0) self.search_symbol_combo.configure(state='disabled') self.btn_search_script.configure(state='disabled') self.graph_select_combo.current(self.graphid) self.btn_add_script.configure(state='disabled')
def scan_layout(self): frame_param = tk.Frame(self.tab_scan, bg='grey', width=200, height=1080) frame_param.pack(side='left', expand='no', fill='y') frame_figure = tk.Frame(self.tab_scan, bg='ivory', width=1700, height=1080) frame_figure.pack(side='top', fill='both', expand='yes') #tk.Label(frame_param, text='sweep from', width=18, anchor='w').grid(row=1, column=1) tk.Label(frame_param, text='x_points', anchor='nw', width=10, relief='ridge').grid(row=1, column=1, sticky=tk.NW) tk.Label(frame_param, text='x_lenth/um', anchor='nw', width=10, relief='ridge').grid(row=2, column=1, sticky='n') tk.Label(frame_param, text='y_points', anchor='nw', width=10, relief='ridge').grid(row=3, column=1, sticky='n') tk.Label(frame_param, text='y_lenth/um', anchor='nw', width=10, relief='ridge').grid(row=4, column=1, sticky='n') tk.Label(frame_param, text='x_start/um', anchor='nw', width=10, relief='ridge').grid(row=5, column=1, sticky='n') tk.Label(frame_param, text='y_start/um', anchor='nw', width=10, relief='ridge').grid(row=6, column=1, sticky='n') tk.Label(frame_param, text='seconds/point', anchor='nw', width=10, relief='ridge').grid(row=50, column=1, sticky='n') tk.Label(frame_param, text='total time', anchor='nw', width=10, relief='ridge').grid(row=60, column=1, sticky='n') tk.Label(frame_param, text='direction', anchor='nw', width=10, relief='ridge').grid(row=70, column=1, sticky='n') x_points_str = tk.IntVar() x_lenth_str = tk.DoubleVar() y_points_str = tk.IntVar() y_lenth_str = tk.DoubleVar() x_start_var = tk.DoubleVar() y_start_var = tk.DoubleVar() time_stay_str = tk.DoubleVar() total_time_str = tk.StringVar() x_points_str.set(20) y_points_str.set(20) x_lenth_str.set(5) y_lenth_str.set(5) x_start_var.set(0.1) y_start_var.set(0.1) time_stay_str.set(0.3) ##每行回针时间为3秒 ##总点数x每个点时间+每个点采样时间x点数+每行回针时间x行数 total_time = ( x_points_str.get() * y_points_str.get() * time_stay_str.get() + 0.015 * x_points_str.get() * y_points_str.get() + 3 * x_points_str.get()) total_time_str.set('{}min{}s'.format(total_time // 60, total_time % 60)) direction_str = tk.StringVar() # 创建画布和轴 fig = Figure(figsize=(5, 5), dpi=100) canvas = FigureCanvasTkAgg(figure=fig, master=frame_figure) aix1 = fig.add_subplot(121) aix2 = fig.add_subplot(122) canvas.get_tk_widget().pack(side='top', fill='both', expand=1) canvas.draw() toobar = NavigationToolbar2Tk(canvas, frame_figure) toobar.update() #绑定鼠标左键更新total_time frame_param.bind( sequence='<Button-1>', func=lambda x: total_time_str.set('{}min{}s'.format( (x_points_str.get() * y_points_str.get() * time_stay_str.get() + x_points_str.get( ) + 0.015 * x_points_str.get() * y_points_str.get()) // 60, (x_points_str.get() * y_points_str.get() * time_stay_str.get() + x_points_str.get( ) + 0.015 * x_points_str.get() * y_points_str.get()) % 60))) x_points_entry = tk.Entry(frame_param, textvariable=x_points_str) x_points_entry.grid(row=1, column=2) x_lenth_entry = tk.Entry(frame_param, textvariable=x_lenth_str) x_lenth_entry.grid(row=2, column=2) y_points_entry = tk.Entry(frame_param, textvariable=y_points_str) y_points_entry.grid(row=3, column=2) y_lenth_entry = tk.Entry(frame_param, textvariable=y_lenth_str) y_lenth_entry.grid(row=4, column=2) x_start_entry = tk.Entry(frame_param, textvariable=x_start_var) x_start_entry.grid(row=5, column=2) y_start_entry = tk.Entry(frame_param, textvariable=y_start_var) y_start_entry.grid(row=6, column=2) time_stay_entry = tk.Entry(frame_param, textvariable=time_stay_str) time_stay_entry.grid(row=50, column=2) total_time_entry = tk.Entry(frame_param, textvariable=total_time_str) total_time_entry.grid(row=60, column=2) direction = tk.Spinbox(frame_param, values=('along the x-axis', 'along the y-axis'), wrap=True, textvariable=direction_str, width=15) direction.grid(row=70, column=2, sticky='w') #创建一个变量来控制扫描的开始与暂停,1表示开始,0表示暂停 begin_or_stop = tk.IntVar() begin_or_stop.set(0) begin_scan_button = tk.Button( frame_param, text='begin', width=10, command=lambda: function.scan_control( canvas, fig, aix1, aix2, x_points_str.get(), x_lenth_str.get(), y_points_str.get(), y_lenth_str.get(), time_stay_str.get(), direction_str.get(), begin_or_stop, begin_scan_button, self. daq, x_start_var.get(), y_start_var.get())) begin_scan_button.grid(row=80, column=1, sticky='w') #将位移台的位置归零 set_zero_strvar = tk.StringVar() set_zero_spinbox = tk.Spinbox(frame_param, values=('x', 'y', 'x_y'), wrap=True, textvariable=set_zero_strvar, width=15) set_zero_spinbox.grid(row=90, column=2, sticky='w') set_zero = tk.Button( frame_param, text='set zero', width=10, command=lambda: function.set_zero(set_zero_strvar.get())) set_zero.grid(row=90, column=1, sticky='w') ##测试 lst = np.load('data\z_position_reverse May_ 6_16_18+5.0+5.0+.npy', allow_pickle=True) x_demo = np.linspace(0, 5, 50) function.plot_fig_scan(canvas, fig, aix1, aix2, lst, x_demo, lst[:, 10], 6, 6)
def setup_graph(self): self.figure = Figure() self.graph_plot = self.figure.add_subplot(1, 1, 1) self.graph_canvas = FigureCanvasTkAgg(self.figure, self) self.graph_canvas.get_tk_widget().grid(row=1, column=0, sticky='nesw', padx=10)
def __init__(self, parent=None): """ Initialization and set up """ # Base class QMainWindow.__init__(self, parent) # Mantid configuration config = ConfigService.Instance() self._instrument = config["default.instrument"] # Central widget self.centralwidget = QWidget(self) # UI Window (from Qt Designer) self.ui = load_ui(__file__, 'MainWindow.ui', baseinstance=self) mpl_layout = QVBoxLayout() self.ui.graphicsView.setLayout(mpl_layout) self.fig = Figure() self.canvas = FigureCanvas(self.fig) self.ui.mainplot = self.fig.add_subplot(111, projection='mantid') mpl_layout.addWidget(self.canvas) # Do initialize plotting vecx, vecy, xlim, ylim = self.computeMock() self.mainline = self.ui.mainplot.plot(vecx, vecy, 'r-') leftx = [xlim[0], xlim[0]] lefty = [ylim[0], ylim[1]] self.leftslideline = self.ui.mainplot.plot(leftx, lefty, 'b--') rightx = [xlim[1], xlim[1]] righty = [ylim[0], ylim[1]] self.rightslideline = self.ui.mainplot.plot(rightx, righty, 'g--') upperx = [xlim[0], xlim[1]] uppery = [ylim[1], ylim[1]] self.upperslideline = self.ui.mainplot.plot(upperx, uppery, 'b--') lowerx = [xlim[0], xlim[1]] lowery = [ylim[0], ylim[0]] self.lowerslideline = self.ui.mainplot.plot(lowerx, lowery, 'g--') self.canvas.mpl_connect('button_press_event', self.on_mouseDownEvent) # Set up horizontal slide (integer) and string value self._leftSlideValue = 0 self._rightSlideValue = 99 self.ui.horizontalSlider.setRange(0, 100) self.ui.horizontalSlider.setValue(self._leftSlideValue) self.ui.horizontalSlider.setTracking(True) self.ui.horizontalSlider.setTickPosition(QSlider.NoTicks) self.ui.horizontalSlider.valueChanged.connect(self.move_leftSlider) self.ui.horizontalSlider_2.setRange(0, 100) self.ui.horizontalSlider_2.setValue(self._rightSlideValue) self.ui.horizontalSlider_2.setTracking(True) self.ui.horizontalSlider_2.setTickPosition(QSlider.NoTicks) self.ui.horizontalSlider_2.valueChanged.connect(self.move_rightSlider) # self.connect(self.ui.lineEdit_3, QtCore.SIGNAL("textChanged(QString)"), # self.set_startTime) self.ui.lineEdit_3.setValidator(QDoubleValidator(self.ui.lineEdit_3)) self.ui.pushButton_setT0.clicked.connect(self.set_startTime) # self.connect(self.ui.lineEdit_4, QtCore.SIGNAL("textChanged(QString)"), # self.set_stopTime) self.ui.lineEdit_4.setValidator(QDoubleValidator(self.ui.lineEdit_4)) self.ui.pushButton_setTf.clicked.connect(self.set_stopTime) # File loader self.scanEventWorkspaces() self.ui.pushButton_refreshWS.clicked.connect(self.scanEventWorkspaces) self.ui.pushButton_browse.clicked.connect(self.browse_File) self.ui.pushButton_load.clicked.connect(self.load_File) self.ui.pushButton_3.clicked.connect(self.use_existWS) # Set up time self.ui.lineEdit_3.setValidator(QDoubleValidator(self.ui.lineEdit_3)) self.ui.lineEdit_4.setValidator(QDoubleValidator(self.ui.lineEdit_4)) # Filter by time self.ui.pushButton_filterTime.clicked.connect(self.filterByTime) # Filter by log value self.ui.lineEdit_5.setValidator(QDoubleValidator(self.ui.lineEdit_5)) self.ui.lineEdit_6.setValidator(QDoubleValidator(self.ui.lineEdit_6)) self.ui.lineEdit_7.setValidator(QDoubleValidator(self.ui.lineEdit_7)) self.ui.lineEdit_8.setValidator(QDoubleValidator(self.ui.lineEdit_8)) self.ui.lineEdit_9.setValidator(QDoubleValidator(self.ui.lineEdit_9)) self.ui.lineEdit_5.textChanged.connect(self.set_minLogValue) self.ui.lineEdit_6.textChanged.connect(self.set_maxLogValue) dirchangeops = ["Both", "Increase", "Decrease"] self.ui.comboBox_4.addItems(dirchangeops) logboundops = ["Centre", "Left"] self.ui.comboBox_5.addItems(logboundops) self.ui.pushButton_4.clicked.connect(self.plotLogValue) self.ui.pushButton_filterLog.clicked.connect(self.filterByLogValue) # Set up help button self.ui.helpBtn.clicked.connect(self.helpClicked) # Set up vertical slide self._upperSlideValue = 99 self._lowerSlideValue = 0 self.ui.verticalSlider.setRange(0, 100) self.ui.verticalSlider.setValue(self._upperSlideValue) self.ui.verticalSlider.setTracking(True) self.ui.verticalSlider.valueChanged.connect(self.move_upperSlider) self.ui.verticalSlider_2.setRange(0, 100) self.ui.verticalSlider_2.setValue(self._lowerSlideValue) self.ui.verticalSlider_2.setTracking(True) self.ui.verticalSlider_2.valueChanged.connect(self.move_lowerSlider) # Set up for filtering (advanced setup) self._tofcorrection = False self.ui.checkBox_fastLog.setChecked(False) self.ui.checkBox_filterByPulse.setChecked(False) self.ui.checkBox_from1.setChecked(False) self.ui.checkBox_groupWS.setChecked(True) self.ui.comboBox_tofCorr.currentIndexChanged.connect(self.showHideEi) self.ui.pushButton_refreshCorrWSList.clicked.connect( self._searchTableWorkspaces) self.ui.lineEdit_Ei.setValidator(QDoubleValidator(self.ui.lineEdit_Ei)) self.ui.label_Ei.hide() self.ui.lineEdit_Ei.hide() self.ui.label_Ei_2.hide() self.ui.comboBox_corrWS.hide() self.ui.pushButton_refreshCorrWSList.hide() # Set up for workspaces self._dataWS = None self._sampleLogNames = [] self._sampleLog = None # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() self.ui.label_avg.hide() self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() self.ui.label_logname.hide() self.ui.label_lognamevalue.hide() self.ui.label_logsize.hide() self.ui.label_logsizevalue.hide() # Default self._defaultdir = os.getcwd() # register startup mantid.UsageService.registerFeatureUsage( mantid.kernel.FeatureType.Interface, "EventFilter", False)
class MyFigure(object): figure = Figure()
def plot(self, peptide, modinfo, spec, nce, instrument): self.raw_scan = '.'.join(spec.split('.')[:-4]) if not self.raw_scan in self.pf2idx: print('no spec {} in pf2 file'.format(spec)) return print('{}-{} <-> {}'.format(peptide, modinfo, spec)) ions = {} bions, pepmass = calc_b_ions(peptide, modinfo) if 'b{}' in self.config.ion_types: ions['b{}'] = bions if 'y{}' in self.config.ion_types: ions['y{}'] = calc_y_from_b(bions, pepmass) if 'c{}' in self.config.ion_types: ions['c{}'] = calc_c_from_b(bions) if 'z{}' in self.config.ion_types: ions['z{}'] = calc_z_from_b(bions, pepmass) if 'b{}-ModLoss' in self.config.ion_types: ions['b{}-ModLoss'] = calc_ion_modloss(bions, peptide, modinfo, N_term=True) if 'y{}-ModLoss' in self.config.ion_types: ions['y{}-ModLoss'] = calc_ion_modloss(ions['y{}'], peptide, modinfo, N_term=False) max_plot_mz = min( self.max_plot_mz, max([max(tmp_ions) for tmp_ions in ions.values()]) + 200) if self.show_plot: fig = Figure(figsize=(12, 8)) ax = get_ax(fig) else: fig = None ax = None self.spec_charge = int(spec.split('.')[-3]) self.pepmass = pepmass matched_inten1 = self.Plot_Real(ax, ions, spec) self.max_real_inten = max(matched_inten1) buckets = self.ion2vec.FeaturizeOnePeptide_buckets( peptide, modinfo, self.spec_charge, nce, instrument) if buckets is None: return predictions = self.model.Predict(buckets)[len(peptide)][0][0, :, :] matched_inten2 = self.Plot_Predict(ax, ions, predictions) if len(matched_inten1) < len(matched_inten2): matched_inten2 = matched_inten2[:len(matched_inten1)] print('[Warning] ion number is not equal') elif len(matched_inten1) > len(matched_inten2): matched_inten1 = matched_inten1[:len(matched_inten2)] print('[Warning] ion number is not equal') PCC = pearsonr(np.array(matched_inten1), -np.array(matched_inten2)) if self.show_plot: ax.text(200, 1.3, '{} ({}+), {}, R = {:.2f}'.format(peptide, self.spec_charge, modinfo, PCC[0]), fontsize=14) ax.set_xlim(xmin=0, xmax=max_plot_mz) ax.set_ylim(ymin=-1.2, ymax=1.4) ax.hlines([0], [0], [max_plot_mz]) ax.set_xlabel('m/z') ax.set_ylabel('Relative Abundance') ylabels = ax.get_yticks().tolist() # ylabels = ["{:.0f}%".format(abs(float(label)*100)) if float(label) >= 0 else '' for label in ylabels] ylabels = [ "{:.0f}%".format(abs(float(label) * 100)) for label in ylabels ] #ylabels = ['' for label in ylabels] ax.set_yticklabels(ylabels) print('R = {:.2f}'.format(PCC[0])) return (fig, PCC[0])
def GenerateBlankFigure(PlotOptions): figsize = PlotOptions["figsize"] return Figure(figsize=(figsize, figsize), dpi=PlotOptions["dpi"])
Thread(target=show_pitch_contour).start() # add pitch button pitch_btn = Button(root) pitch_btn.configure(text='Pitch contour', font=('segoe ui', 10), bg='#0052cc', fg='#ffffff') pitch_btn.bind('<Button-1>', pitch_btn_clicked) pitch_btn.place(x=10, y=510, width=100) # add loader icon frames = [PhotoImage(file='./image/loader.gif', format='gif -index %i' % i) for i in range(8)] loader = Label(root) is_loader = False # create new figure figure = Figure() is_redraw = False # for before median filter graph_1 = figure.add_subplot(311) graph_1.set_ylabel('Frequency (Hz)') graph_1.set_xlabel('Time') graph_1.set_ylim(0, 400) scatter_1 = None figure.tight_layout() # for after median filter graph_2 = figure.add_subplot(312) graph_2.set_ylabel('Frequency (Hz)') graph_2.set_xlabel('Time') graph_2.set_ylim(0, 400)