def setup_plot(): global rate_slider, delta_slider, fig, ax, l, radio fig, ax = plt.subplots() ax.grid('on') plt.subplots_adjust(left=0.25, bottom=0.25) moneyFmt = FuncFormatter(money) ax.yaxis.set_major_formatter(moneyFmt) s = calc_compounding( rate, periods, principal, contribution, delta,inflation) t = np.arange(2014, (2014+periods)) l, = plt.plot(t,s, lw=2, color='red') plt.ylabel("Investment Loss (FV)") plt.axis([2014, (2014+periods), 0, principal]) plt.axis('tight') axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axamp = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) rate_slider = Slider(axfreq, 'Avg.Returns', 4, 8, valinit=rate) delta_slider = Slider(axamp, 'Delta', 0.1, 1, valinit=delta) resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') rate_slider.on_changed(update) delta_slider.on_changed(update) button.on_clicked(reset) rax = plt.axes([0.015, 0.15, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('0','3000', '6000', '9000'), active=0) radio.on_clicked(contribution_update) plt.show() return rate_slider,delta_slider,fig,ax,l,radio
def slide_ddg(args): global new_df, radio, color_by, picked global scat, ax, sliders, sc_df, fig, cm, cbar sc_df = Rf.score_file2df(args['sc'], args['names']) args['logger'].log('score file has %i entries' % len(sc_df)) if args['pc'] is not None: pc_df = get_rmsds_from_table(args['pc']) args['logger'].log('pc file had %i entries' % len(pc_df)) a = sc_df.merge(pc_df, on='description') args['logger'].log('combined there are %i entries' % len(a)) sc_df = a.copy() if args['percent'] != 100: threshold = np.percentile(sc_df[args['y']], args['percent']) sc_df = sc_df[ sc_df[args['y']] < threshold ] color_by = args['y'] picked = False new_df = sc_df.copy() fig, ax = plt.subplots() plt.subplots_adjust(left=0.25, bottom=0.25) cm = plt.cm.get_cmap('RdYlBu') scat = ax.scatter(sc_df[args['x']].values, sc_df[args['y']].values, s=40, cmap=cm, c=sc_df[color_by], picker=True) cbar = plt.colorbar(scat) sliders = {} for i, term in enumerate(args['terms']): slider_ax = plt.axes([0.25, 0.01+i*0.035, 0.65, 0.03]) sliders[term] = Slider(slider_ax, term, np.min(sc_df[term].values), np.max(sc_df[term].values), 0) sliders[term].on_changed(update) ax.set_xlim(np.min(new_df[args['x']].values)-1, np.max(new_df[args['x']].values)+1) ax.set_ylim(np.min(new_df[args['y']].values)-1, np.max(new_df[args['y']].values)+1) ax.set_xlabel(args['x']) ax.set_ylabel(args['y']) resetax = plt.axes([0.025, 0.7, 0.15, 0.15]) #[0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color='lightgoldenrodyellow', hovercolor='0.975') button.on_clicked(reset) printax = plt.axes([0.025, 0.3, 0.15, 0.15]) printbutton = Button(printax, 'Print', color='green', hovercolor='red') printbutton.on_clicked(print_table) logax = plt.axes([0.025, 0.1, 0.15, 0.15]) logbutton = Button(logax, 'log table', color='blue', hovercolor='red') logbutton.on_clicked(log_table) rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg='white') radio = RadioButtons(rax, args['terms'], active=0) radio.on_clicked(colorfunc) # cbar = plt.colorbar(scat) pl = PointLabel(new_df, ax, fig, args['x'], args['y'], ['description', 'a_sasa', 'a_res_solv', 'a_pack', 'a_span_topo', 'a_ddg', 'fa_elec'], args['logger']) fig.canvas.mpl_connect('pick_event', pl.onpick) plt.show()
class WidgetsBasic(WidgetsSimple): def __init__(self, canvas=None, active_prop=None): super(WidgetsBasic, self).__init__(canvas, active_prop) self.colors_ifs = {} @property def prop_ifs(self): return self.active_prop def update_show_components(self, label): super(WidgetsBasic, self).update_show_components(label) if label == "hide ifs": if self.holder_actives[label]: self.prop_ifs.holder.set_linestyle(" ") self.prop_ifs.holder.set_visible(False) self.prop_ifs.set_visible_annotations(False) self.prop_ifs.topo_const.set_visible(False) else: self.prop_ifs.holder.set_linestyle(" ") self.prop_ifs.holder.set_visible(True) self.prop_ifs.set_visible_annotations(True) self.prop_ifs.topo_const.set_visible(True) # here is updated the active prop_ifs def recreate_widgets(self, idx_active, props, active_prop): super(WidgetsBasic, self).recreate_widgets_(active_prop) self._recreate_active_ifs_radiobutton(idx_active, props) def _recreate_active_ifs_radiobutton(self, idx_active, props): self.props = props axcolor = "lightgoldenrodyellow" if hasattr(self, "rax_activeifs"): self.rax_activeifs.cla() self.rax_activeifs = plt.axes( [0.2 + self.button_length__ + 0.01, 0.05, self.button_length__, self.button_height__], axisbg=axcolor ) activecolor = self.active_prop.get_color() self.w_rad_active_ifs = RadioButtons( self.rax_activeifs, sorted(self.colors_ifs.keys()), active=idx_active, activecolor=activecolor ) self.w_rad_active_ifs.on_clicked(self.colorfunc) return self.w_rad_active_ifs def colorfunc(self, label): idx = int(label) self.active_prop = self.props[idx] self.w_rad_active_ifs.activecolor = self.prop_ifs.get_color() self._recreate_radius_slider() self._recreate_show_lines_check_button() self._recreate_alpha_slider() self._recreate_textsize_slider() if self.canvas is None: self.canvas.draw()
def run_main(A,B,C,dA,dB,dC): plt.close() plt.figure() int_writer() var_writer_uncert(A,B,C) run_SPCAT() data = cat_reader() t = [] s = [] for x in data: s.append(0.0) s.append(str(10**float(x[1]))) s.append(0.0) t.append(float(x[0])-0.0001) t.append(x[0]) t.append(float(x[0])+0.0001) ax = plt.subplot(111) plt.subplots_adjust(left=0.25, bottom=0.25) a0 = 5 f0 = 3 global l l, = plt.plot(t,s, lw=2, color='red') #plt.axis([0, 1, -10, 10]) axcolor = 'lightgoldenrodyellow' axA = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) axB = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axC = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor) global A_slider global B_slider global C_slider A_slider = Slider(axA, 'A', A-dA, A+dA, valinit=A) B_slider = Slider(axB, 'B', B-dB, B+dB, valinit=B) C_slider = Slider(axC, 'C', C-dC, C+dC, valinit=C) A_slider.on_changed(update) B_slider.on_changed(update) C_slider.on_changed(update) global button global radio resetax = plt.axes([0.1, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') button.on_clicked(reset) rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) radio.on_clicked(colorfunc) plt.show()
def _GUI_display(self,redshift_est,ztest,corr_val,wave,flux_sc): '''Display the spectrum and reference lines.''' self.fig = plt.figure(figsize=(10, 8)) gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1]) ax2 = plt.subplot(gs[0]) ax = plt.subplot(gs[1]) plt.subplots_adjust(right=0.8) ax.plot(ztest,corr_val,'b') ax.axvline(redshift_est,color='k',ls='--') ax.fill_between(self.ztest,np.zeros(self.ztest.size),self.corr_prior,facecolor='grey',alpha=0.6) ax.set_xlabel('Redshift') ax.set_ylabel('Correlation') self.pspec, = ax2.plot(wave,flux_sc) ax2.axvline(3725.0*(1+redshift_est),ls='--',alpha=0.7,c='blue') ax2.axvline(3968.5*(1+redshift_est),ls='--',alpha=0.7,c='red') ax2.axvline(3933.7*(1+redshift_est),ls='--',alpha=0.7,c='red') ax2.axvline(4102.9*(1+redshift_est),ls='--',alpha=0.7,c='orange') ax2.axvline(4304.0*(1+redshift_est),ls='--',alpha=0.7,c='orange') ax2.axvline(4862.0*(1+redshift_est),ls='--',alpha=0.7,c='orange') ax2.axvline(4959.0*(1+redshift_est),ls='--',alpha=0.7,c='blue') ax2.axvline(5007.0*(1+redshift_est),ls='--',alpha=0.7,c='blue') ax2.axvline(5175.0*(1+redshift_est),ls='--',alpha=0.7,c='orange') if self.first_pass: self.line_est = Estimateline(self.pspec,ax2,self.uline_n) rax = plt.axes([0.85, 0.5, 0.1, 0.2]) if self.qualityval == 0: radio = RadioButtons(rax, ('Unclear', 'Clear')) else: radio = RadioButtons(rax, ('Unclear', 'Clear'),active=1) def qualfunc(label): if label == 'Clear': self.qualityval = 1 else: self.qualityval = 0 radio.on_clicked(qualfunc) closeax = plt.axes([0.83, 0.3, 0.15, 0.1]) button = Button(closeax, 'Accept & Close', hovercolor='0.975') def closeplot(event): plt.close() button.on_clicked(closeplot) ax2.set_xlim(self.lower_w,self.upper_w) ax2.set_xlabel('Wavelength (A)') ax2.set_ylabel('Counts') if not self.first_pass: self.spectra2 = DragSpectra(self.pspec,flux_sc,ax2,self.fig) self.fig.canvas.mpl_connect('motion_notify_event',self.spectra2.on_motion) self.fig.canvas.mpl_connect('button_press_event',self.spectra2.on_press) self.fig.canvas.mpl_connect('button_release_event',self.spectra2.on_release) plt.show()
def slider_radio(): def update(val): amp = samp.val freq = sfreq.val l.set_ydata(amp*np.sin(2*np.pi*freq*t)) fig.canvas.draw_idle() def reset(event): sfreq.reset() samp.reset() def colorfunc(label): l.set_color(label) fig.canvas.draw_idle() fig = figure() ax = fig.subplots() fig.subplots_adjust(left=0.25, bottom=0.25) t = np.arange(0.0, 1.0, 0.001) a0 = 5 f0 = 3 s = a0*np.sin(2*np.pi*f0*t) l, = ax.plot(t, s, lw=2, color='red') ax.axis([0, 1, -10, 10]) # %% plot axes axcolor = 'lightgoldenrodyellow' axfreq = fig.add_axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor) axamp = fig.add_axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor) # %% freq slide sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0) samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0) sfreq.on_changed(update) samp.on_changed(update) # %% reset button resetax = fig.add_axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') button.on_clicked(reset) # %% color buttons rax = fig.add_axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor) radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) radio.on_clicked(colorfunc) # %% scoping axw = [axfreq, axamp, sfreq, samp, button, radio] # place to hold all the axesWidgets to keep in scope return axw # MUST return ax or GUI will be non-responsive!
def plot_mapqs(folder): """Plots the Distribution of MAPQ Scores for the Inversion Regions in the respective species folder : input folder to look for the files """ mapqs_counts = defaultdict(list) mapqs_labels = defaultdict(list) strain_matcher = re.compile('(.*) \(.*\)') ## regex to get strain name from radio button click ## Parse the information from the mapq count files and store the information in a dictionary of lists for mapq_file in glob.glob(folder+"*.count.txt"): strain = mapq_file.split("/")[-1].split(".")[0] TEMP_HANDLE = open(mapq_file,'r') for line in TEMP_HANDLE: line = line.strip('\n') mapqs_counts[strain].append(int(line.split(' ')[0])) mapqs_labels[strain].append(line.split(' ')[1]) fig, ax = plt.subplots() indexes = np.arange(len(mapqs_counts[S])) rects = plt.bar(indexes,mapqs_counts[S],0.5) ax.set_xticks(indexes+1*0.2) ax.set_xticklabels(mapqs_labels[S],rotation=30) rax1 = plt.axes([0.92, 0.1, 0.08, 0.8]) radio1 = RadioButtons(rax1, ('MC (Sand)','CL (Sand)','CM (Sand)','CN (Sand)','TI (Sand)','DC (Sand)','MS (Sand)','CV (Sand)','PN (Rock)','AC (Rock)','LF (Rock)','MP (Rock)','MZ (Rock)'), active=0) def update1(strain): match = re.match(strain_matcher,strain) strain = match.group(1) #indexes = np.arange(len(mapqs_counts[S])) for rect,h in zip(rects,mapqs_counts[strain]): rect.set_height(h) ax.set_xticks(indexes+1*0.2) ax.set_xticklabels(mapqs_labels[strain],rotation=30) ax.relim() ax.autoscale() fig.canvas.draw_idle() #global S #print S #S = strain radio1.on_clicked(update1) plt.show()
class AnalyzeFrame(object): """ A slider representing a floating point range """ def __init__(self, fname, n=10, intraday=False): """ """ self.fig = plt.figure(facecolor='white') self.fig.canvas.set_window_title(u'期货数据分析') self.nbar = n self.cursors = [] self.data, = load_datas(n, intraday, fname) self.axes = [] self.rax = plt.axes([0, 0.5, 0.08, 0.15]) self.radio = RadioButtons(self.rax, ('scatter', 'summary', 'summary2', 'entry', 'exit', 'simple'), active=0) self.axes, self.cursors = scatter_analyze(self.fig, self.data) self.radio.on_clicked(self.update) def update(self, op): for ax in self.axes: self.fig.delaxes(ax) for c in self.cursors: del c if op == "scatter": print "scatter_analyze" self.axes, self.cursors = scatter_analyze(self.fig, self.data) elif op == "summary": print "summary_analyze" self.axes, self.cursors = summary_analyze(self.fig, self.data, self.nbar, 1) elif op == "summary2": print "summary2_analyze" self.axes, self.cursors = summary_analyze(self.fig, self.data, self.nbar, 2) elif op == "entry": print "entry_analyze" self.axes, self.cursors = entry_analyze(self.fig, self.data, self.nbar) elif op == "exit": print "exit_analyze" self.axes, self.cursors = exit_analyze(self.fig, self.data, self.nbar) elif op == "simple": self.axes, self.cursors = simple_entry_analyze(self.fig, self.data, self.nbar) #elif op == "hm": #axes, cursors = follow_entry_analyze(fig, data) #print "hm" self.fig.canvas.draw()
def Slider(): import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons fig, ax = plt.subplots() plt.subplots_adjust(left=0.25, bottom=0.25) t = np.arange(0.0, 1.0, 0.001) a0 = 5 f0 = 3 s = a0*np.sin(2*np.pi*f0*t) l, = plt.plot(t,s, lw=2, color='red') plt.axis([0, 1, -10, 10]) axcolor = 'lightgoldenrodyellow' axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axamp = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0) samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0) def update(val): amp = samp.val freq = sfreq.val l.set_ydata(amp*np.sin(2*np.pi*freq*t)) fig.canvas.draw_idle() sfreq.on_changed(update) samp.on_changed(update) resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') def reset(event): sfreq.reset() samp.reset() button.on_clicked(reset) rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) def colorfunc(label): l.set_color(label) fig.canvas.draw_idle() radio.on_clicked(colorfunc) plt.show()
def plot(Z): ax = plt.subplot(111) plt.subplots_adjust(bottom=0.25) ax.contour(flatperm2.pd(Z, 1, 1).T) ax1 = plt.axes([0.125, 0.15, 0.775, 0.03]) ax2 = plt.axes([0.125, 0.05, 0.775, 0.03]) s1 = Slider(ax1, r'$\omega_1$', 0.1, 30.0, valinit=1) s2 = Slider(ax2, r'$\omega_2$', 0.1, 10.0, valinit=1) plt.show() def update(val): w1 = s1.val w2 = s2.val print((w1, w2)) ax.clear() ax.contour(flatperm2.pd(Z, w1, w2).T) # l.set_ydata(amp*sin(2*pi*freq*t)) plt.draw() s1.on_changed(update) s2.on_changed(update) return resetax = axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') def reset(event): sfreq.reset() samp.reset() button.on_clicked(reset) rax = axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) def colorfunc(label): l.set_color(label) draw() radio.on_clicked(colorfunc) show()
def make_buttons(self): axcolor = 'lightgoldenrodyellow' rax = plt.axes([0.05, 0.05, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('x1', 'x5', 'x10')) radio.on_clicked(self.set_multiplier) axprev = plt.axes([0.7, 0.05, 0.1, 0.075]) axnext = plt.axes([0.81, 0.05, 0.1, 0.075]) axup = plt.axes([0.59, 0.05, 0.1, 0.075]) axdown = plt.axes([0.48, 0.05, 0.1, 0.075]) axdone = plt.axes([0.30, 0.05, 0.1, 0.075]) bnext = Button(axnext, 'Right') bnext.on_clicked(self.next) bprev = Button(axprev, 'Left') bprev.on_clicked(self.prev) bup = Button(axup, 'Up') bup.on_clicked(self.up) bdown = Button(axdown, 'Down') bdown.on_clicked(self.down) bdone = Button(axdone, 'Done') bdone.on_clicked(self.done)
def setup_canvas(self): """Create the figure and the axes for the plot and buttons.""" # Initialise the figure. self.currentFigure = plt.figure() self.axes = self.currentFigure.add_subplot(1, 1, 1) # Create the image. self.start_plotting(self.originalDataset) # Create the class radio button. classAxesLoc = plt.axes([0.05, 0.05, 0.07, 0.1 * round(len(self.classToColorMapping) / 3)], axisbg='0.85') classAxesLoc.set_title('Class Options') classRadio = RadioButtons(classAxesLoc, active=0, activecolor='black', labels=[i for i in sorted(self.classToColorMapping)]) classRadio.on_clicked(self.on_class_change) # Create the reset button. resetAxesLoc = plt.axes([0.05, 0.44, 0.07, 0.075], axisbg='white') resetButton = Button(resetAxesLoc, 'Reset') resetButton.on_clicked(self.on_reset) # Create the recompute boundaries button. recomputeAxesLoc = plt.axes([0.05, 0.54, 0.07, 0.075], axisbg='white') recomputeButton = Button(recomputeAxesLoc, 'Recompute') recomputeButton.on_clicked(self.on_recompute) # Create the k choice button. kAxesLoc = plt.axes([0.05, 0.65, 0.07, 0.15], axisbg='0.85') kAxesLoc.set_title('K Options') kRadio = RadioButtons(kAxesLoc, active=0, activecolor='black', labels=[1, 3, 5, 7]) kRadio.on_clicked(self.on_k_change) # Create the add/delete radio button. addDeleteAxesLoc = plt.axes([0.05, 0.85, 0.07, 0.1], axisbg='0.85') addDeleteAxesLoc.set_title('Add/Delete Points') addDeleteRadio = RadioButtons(addDeleteAxesLoc, active=1, activecolor='black', labels=['Add', 'Delete']) addDeleteRadio.on_clicked(self.on_delete_change) # Attach the mouse click event. cid = self.currentFigure.canvas.mpl_connect('button_press_event', self.on_click) # Display the figure maximised. These commands to maximise the figure are for the Qt4Agg backend. If a different backend is being used, then # the maximisation command will likely need to be changed. figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.show() # Disconnect the mouse click event. self.currentFigure.canvas.mpl_disconnect(cid)
# Radio buttons in each axes radioSex = RadioButtons(axSex, ('Male', 'Female')) radioAge = RadioButtons(axAge, ('35-65', '65+')) radioRace = RadioButtons(axRace, ('White', 'Black', 'Other')) radioEthn = RadioButtons(axEthn, ('Hispanic', 'Non-Hisp')) radioIncome = RadioButtons(axIncome, ('< 40K', '40-80K ', '80-150k')) radioStress = RadioButtons(axStress, ('no stress', 'stress')) radioTrauma = RadioButtons(axTrauma, ('0', '1', '2')) def sexfunc(label): global isFemale sexdict = {'Male': 0, 'Female': 1} isFemale = sexdict[label] # calculate_distribution() radioSex.on_clicked(sexfunc) def agefunc(label): global isYoung agedict = {'35-65': 1, '65+': 0} isYoung = agedict[label] # print 'isYoung = %r'%isYoung # calculate_distribution() radioAge.on_clicked(agefunc) def racefunc(label): global race racedict = {'White':'white', 'Black':'black', 'Other':'other'} race = racedict[label]
bsubmit = Button(axsubmit, 'Submit and show next', color='green', hovercolor='green') bsubmit.on_clicked(callback.submit) bmark = Button(axmark, 'Mark for return', color='orange', hovercolor='orange') bmark.on_clicked(callback.mark) axcolor = 'lightgoldenrodyellow' rb1_axes = plt.axes([0.70, 0.62, 0.10, 0.15], axisbg=axcolor) radio1 = RadioButtons(rb1_axes, ('A', 'B', 'C')) def rb_1(label): print 'radio button 1' radio1.on_clicked(rb_1) rax = plt.axes([0.70, 0.3, 0.2, 0.25]) labels=['Type 1','Type 2', 'Type 4', 'Other'] check = CheckButtons(rax, (labels[0], labels[1], labels[2], labels[3]), (False, False, False, False)) def func(label): if label == labels[0]: check_text=labels[0] elif label == labels[1]: check_text=labels[1] elif label == labels[2]: check_text=labels[2] elif label == labels[3]: check_text=labels[3] print 'checked: ', check_text check.on_clicked(func)
class SetUp: def __init__(self): fig, axs = self.setFigure() self.fig = fig self.axs = axs self.connect() py.show() def setFigure(self): fig = py.figure(figsize=(5,5)) axs = self.addAxes(fig) self.bntext = py.Button(axs['text'], 'Text') self.bnchange= py.Button(axs['change'], 'Change') self.bnband = RadioButtons(axs['band'], ('low','high','double')) self.bnBandLabel = py.Button(axs['band_label'], 'low') return fig, axs def connect(self): self.cidtext = self.bntext.on_clicked(self.texting) self.cidchange = self.bnchange.on_clicked(self.changed) self.cidpress = self.fig.canvas.mpl_connect('key_press_event', self.on_key) self.cidband = self.bnband.on_clicked(self.getBand) def getBand(self, event): print 'Ducks want food!' self.bnBandLabel.label.set_text(event) self.fig.canvas.draw() def addStuff(self, numA, numB): return numA + numB def on_key(self, event): if (event.key == 'H'): print 'YOLOSWAG' def texting(self, event): if self.bntext.label.get_text() == 'Text': self.bntext.label.set_text('LOL') else: self.bntext.label.set_text('Text') def addAxes(self, fig): axs = {} # buttons rectchange = [0.20, 0.50, 0.20, 0.05] axs['change'] = fig.add_axes(rectchange) recttext = [0.20, 0.30, 0.20, 0.05] axs['text'] = fig.add_axes(recttext) rectband = [0.50, 0.40, 0.30, 0.25] axs['band'] = fig.add_axes(rectband) # label rect_lband = [0.50, 0.70, 0.30, 0.05] axs['band_label'] = fig.add_axes(rect_lband) return axs def changed(self,event): if self.bnchange.label.get_text() == 'Change': self.bnchange.label.set_text('Hello') self.bntext.label.set_text('LOL') else: self.bnchange.label.set_text('Change')
def run_main(A, B, C, dA, dB, dC, DJ, DJK, DK, ua, ub, uc, T, last_times_picked_list, number_of_skips, spectrum_filename=None): #matplotlib.use('TkAggx') global DJ_g, DJK_g, DK_g, ua_g, ub_g, uc_g, T_g DJ_g = DJ DJK_g = DJK DK_g = DK ua_g = ua ub_g = ub uc_g = uc T_g = T global picked_list picked_list = last_times_picked_list plt.close() global figure_h figure_h = plt.figure(figsize=(16.5, 4)) figure_h.canvas.manager.window.Move((00, 00)) int_writer(ua, ub, uc, temp=T_g) var_writer_uncert(A, B, C, DJ, DJK, DK) run_SPCAT() data = cat_reader() global t global s t = [] s = [] t_b = [] s_b = [] for x in data: s.append(0.0) s.append(str(10**float(x[1]))) s.append(0.0) t.append(float(x[0]) - 0.0001) t.append(x[0]) t.append(float(x[0]) + 0.0001) for y in picked_list: if x[2] == y[1] and x[3] == y[2]: s_b.append(0.0) s_b.append(str(10**float(x[1]))) s_b.append(0.0) t_b.append(float(x[0]) - 0.0001) t_b.append(x[0]) t_b.append(float(x[0]) + 0.0001) ax = figure_h.add_subplot(212) plt.subplots_adjust(left=0.25, bottom=0.25) a0 = 5 f0 = 3 global l l, = plt.plot(t, s, lw=2, color='red') global picked_plt picked_plt, = plt.plot(t_b, s_b, lw=2, color='black') #plt.axis([0, 1, -10, 10]) #figure_h.canvas.mpl_connect('button_press_event', handle_mouse_press) ax2 = figure_h.add_subplot(211, sharex=ax) try: fh = open(spectrum_filename) spectrum_list_F = [] spectrum_list_I = [] counter = 0 for line in fh: counter += 1 if counter % (number_of_skips + 1) == 0: spectrum_list_F.append(line.split()[0]) spectrum_list_I.append(line.split()[1]) else: pass ax2.plot(spectrum_list_F, spectrum_list_I, lw=2, color='black') except TypeError or IOError: pass figure_h.canvas.mpl_connect('key_press_event', on_key) axcolor = 'lightgoldenrodyellow' axA = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) axB = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axC = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor) global A_slider global B_slider global C_slider A_slider = Slider(axA, 'A', A - dA, A + dA, valinit=A) B_slider = Slider(axB, 'B', B - dB, B + dB, valinit=B) C_slider = Slider(axC, 'C', C - dC, C + dC, valinit=C) A_slider.on_changed(update) B_slider.on_changed(update) C_slider.on_changed(update) global button global radio resetax = plt.axes([0.1, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') button.on_clicked(reset) rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) radio.on_clicked(colorfunc) global text_box global text_box2 text_box = plt.text(-0.15, 2, "Most Recent Selection: \n") text_box2 = plt.text(-0.15, -2, "Other Nearby Peaks \n") plt.show()
l, = ax.plot(t, s0, lw=2, color='red') plt.subplots_adjust(left=0.3) axcolor = 'lightgoldenrodyellow' rax = plt.axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor) radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz')) def hzfunc(label): hzdict = {'2 Hz': s0, '4 Hz': s1, '8 Hz': s2} ydata = hzdict[label] l.set_ydata(ydata) plt.draw() radio.on_clicked(hzfunc) rax = plt.axes([0.05, 0.4, 0.15, 0.15], facecolor=axcolor) radio2 = RadioButtons(rax, ('red', 'blue', 'green')) def colorfunc(label): l.set_color(label) plt.draw() radio2.on_clicked(colorfunc) rax = plt.axes([0.05, 0.1, 0.15, 0.15], facecolor=axcolor) radio3 = RadioButtons(rax, ('-', '--', '-.', 'steps', ':'))
class HilbertGUI(HilbertPlot): def __init__(self, *args, **kwargs): """ Similar to HilbertPlot class, but automatically adds GUI elements. """ super(HilbertGUI, self).__init__(*args, **kwargs) def _configure_axes(self): """ Given the number of chromosomes and the number of data files configured, create a bunch of subplots. Abuses matplotlib.gridspec.GridSpec """ # The area that will be subdivided into subplots per chrom. # TODO: expose this to the figure-saving method, which should get its # bbox [in part] from these coords. CHROM = dict( left=0.05, right=0.8, top=0.9, bottom=0.2, wspace=0.01, hspace=0.1) # Area used for alpha sliders SLIDER_PAD = 0.01 SLIDER = dict( left=0.15, right=0.70, bottom=0.1, top=CHROM['bottom'] - SLIDER_PAD, hspace=0.5, ) # Area used for colorbars # TODO: similar to CHROM, expose this to figure-saving method CBAR_PAD = 0.01 CBAR = dict( left=CHROM['right'] + CBAR_PAD, right=0.95, wspace=1.5, top=CHROM['top'], bottom=CHROM['bottom'], ) # Area used for checkboxes. CHECKS = dict( top=SLIDER['top'], bottom=SLIDER['bottom'], left=CBAR['left'], right=CBAR['right'], wspace=CBAR['wspace'], hspace=SLIDER['hspace']) RADIO_PAD = 0.01 RADIO = ( CHROM['left'], # left SLIDER['bottom'], # bottom SLIDER['left'] - CHROM['left'] - RADIO_PAD, # width SLIDER['top'] - SLIDER['bottom'], # height ) self.radio_ax = plt.Axes(self.fig, RADIO) self.fig.add_axes(self.radio_ax) # Set up the grids upon which new axes will eventually be organized and # created nrows = int(np.ceil(np.sqrt(self.nchroms))) ncols = nrows assert nrows * ncols >= len(self.chroms) chrom_grid = gs.GridSpec(nrows, ncols) chrom_grid.update(**CHROM) slider_grid = gs.GridSpec(self.nfiles, 1) slider_grid.update(**SLIDER) colorbar_grid = gs.GridSpec(1, self.nfiles) colorbar_grid.update(**CBAR) checks_grid = gs.GridSpec(self.nfiles, self.nfiles) checks_grid.update(**CHECKS) # Now create the actual axes, and store them in self.*_axs dictionaries # for later access -- keyed by chrom (for chrom_axs) or filenames (all # others) self.chrom_axs = {} for chrom, spec in zip(self.chroms, chrom_grid): ax = plt.subplot(spec) ax.set_yticks([]) ax.set_xticks([]) ax.set_title(chrom, size=10) self.chrom_axs[chrom] = ax self.slider_axs = {} for fn, spec in zip(self.fns, slider_grid): self.slider_axs[fn] = plt.subplot(spec) self.colorbar_axs = {} for fn, spec in zip(self.fns, colorbar_grid): self.colorbar_axs[fn] = plt.subplot(spec) self.checks_axs = {} for i in range(self.nfiles): # this way only axes on the diagonal across the checkbox grid will # be created ax = plt.subplot(checks_grid[i, i]) ax.set_yticks([]) ax.set_xticks([]) ax.patch.set_color('k') ax.SHOW = True ax.last_slider_val = 0.5 self.checks_axs[self.fns[i]] = ax # Initialize widgets ------------------------------------------------------ def _init_alpha_sliders(self): """ Add sliders to self.slider_axs. Assumes self._configure_axes has been called so that self.slider_axs has been populated. """ self.sliders = {} for fn in self.fns: # Disable for now.... #label = '%s: %s' % (string.letters[i], os.path.basename(fn)) label = "" slider = Slider( self.slider_axs[fn], label, valmin=0, valmax=1, valinit=0.5, facecolor='0.3') slider.label.set_size(10) self.sliders[fn] = slider # TODO: it would be a nice touch if slider color == max cmap color def _init_radio(self): """ Add radio buttons to the radio ax for color scale. self._make_radio_axes() needs to have been called. """ self.radio = RadioButtons( self.radio_ax, labels=['log', 'linear'], active=1) def _make_connections(self): # Alpha sliders for fn in self.fns: self.sliders[fn].on_changed( self._slider_callback_factory(fn)) # Radio callback changes color scale self.radio.on_clicked(self._radio_callback) self.fig.canvas.mpl_connect('button_press_event', self._check_callback) self.fig.canvas.mpl_connect('motion_notify_event', self._coord_tracker) self.fig.canvas.mpl_connect('pick_event', self._coord_callback) # Plot data --------------------------------------------------------------- def plot(self, figsize=(8, 8)): """ Does most of the work to set up the figure, axes, and widgets. """ super(HilbertGUI, self).plot(figsize=figsize) def _post_plot_tasks(self): super(HilbertGUI, self)._post_plot_tasks() # Initialize the various widgets self._init_alpha_sliders() self._init_radio() # Connect callbacks to events self._make_connections() # Helper methods for getting various info when given an axes -------------- def _radio_callback(self, label): # Hello? Am I the 9th caller!? if label == 'log': self.set_log() elif label == 'linear': self.set_linear() else: raise ValueError("unspecified label for radio button") def _check_callback(self, event): """ Toggles the alpha between 0.0 and 0.5 and also changes the color of the checkbox axes. """ ax = event.inaxes fn = self._fn_from_check_ax(ax) if ax in self.checks_axs.values(): ax.SHOW = not ax.SHOW color = {True: 'k', False: 'w'} if ax.SHOW: self.sliders[fn].set_val(ax.last_slider_val) else: ax.last_slider_val = self.sliders[fn].val self.sliders[fn].set_val(0) ax.patch.set_color(color[ax.SHOW]) # explicitly update all the matrices with the new value for chrom in self.chroms: self.mappables[chrom][fn].set_alpha(self.sliders[fn].val) plt.draw() def _fn_from_check_ax(self, ax): for fn, check_ax in self.checks_axs.iteritems(): if check_ax == ax: return fn def _slider_callback_factory(self, fn): """ Given a filename, return a function that will modify all that filename's mappables based on the slider's value. """ def _slider_callback(x): self.set_alpha(fn, x) return _slider_callback def set_alpha(self, fn, alpha): """ Set alpha for file `fn` :param fn: Which filename to set the alpha for :param alpha: Transparency of the matrix colors (0-1) """ super(HilbertGUI, self).set_alpha(fn, alpha) self.sliders[fn].val = alpha
class TSOM2_Viewer: def __init__(self, y, winner1, winner2, fig_size=None, label1=None, label2=None, button_label=None): # ---------- 参照テンソルとデータ ---------- # self.Mode1_Num = y.shape[0] self.Mode2_Num = y.shape[1] if y.ndim == 2: # 1次元の場合 self.Dim = 1 self.Y = y[:, :, np.newaxis] else: # 2次元の場合 self.Dim = y.shape[2] self.Y = y # ---------- 勝者 ---------- # self.Winner1 = winner1 self.Winner2 = winner2 # ----------コンポーネントプレーン用---------- # self.Map1_click_unit = 0 # Map0のクリック位置 self.Map2_click_unit = 0 # Map1のクリック位置 self.Map3_click_unit = 0 # add machida Map3のクリック位置 self.map1x_num = int(np.sqrt(self.Mode1_Num)) # マップの1辺を算出(正方形が前提) self.map2x_num = int(np.sqrt(self.Mode2_Num)) # マップの1辺を算出(正方形が前提) # マップ上の座標 map1x = np.arange(self.map1x_num) map1y = -np.arange(self.map1x_num) map1x_pos, map1y_pos = np.meshgrid(map1x, map1y) self.Map1_position = np.c_[map1x_pos.ravel(), map1y_pos.ravel()] # マップ上の座標 map2x = np.arange(self.map2x_num) map2y = -np.arange(self.map2x_num) map2x_pos, map2y_pos = np.meshgrid(map2x, map2y) self.Map2_position = np.c_[map2x_pos.ravel(), map2y_pos.ravel()] # マップ上の座標 #label self.label1 = label1 self.label2 = label2 self.button_label = button_label if button_label is None: #radioボタンにラベルが与えられなかったときの処理(観測データ次元分の番号を振る) self.button_label = np.arange(self.Dim) values = np.arange(self.Dim) #radioボタンにラベルをはる際に辞書を作成 dict_keys = [] for i in np.arange(self.Dim): dict_keys.append(str(self.button_label[i])) self.hzdict = dict(zip( dict_keys, values)) # e.g.Deskwork_or_studyingが与えられたら0を返す else: values = np.arange(self.Dim) # radioボタンにラベルをはる際に辞書を作成 dict_keys = [] for i in np.arange(self.Dim): dict_keys.append(str(self.button_label[i])) self.hzdict = dict(zip( dict_keys, values)) # e.g.Deskwork_or_studyingが与えられたら0を返す # コンポーネントプレーン self.__calc_component(1) self.__calc_component(2) self.click_map = 0 # ----------描画用---------- # self.Mapsize = np.sqrt(y.shape[0]) if fig_size is None: self.Fig = plt.figure(figsize=(15, 6)) else: self.Fig = plt.figure(figsize=fig_size) plt.subplots_adjust(right=0.7) self.Map1 = self.Fig.add_subplot(1, 2, 1) self.Map1.set_title('Situation View') self.Map2 = self.Fig.add_subplot(1, 2, 2) self.Map2.set_title('Position View') rax = plt.axes([0.7, 0.25, 0.1, 0.5], facecolor='lightgoldenrodyellow', aspect='equal') if not button_label is None: self.radio = RadioButtons(rax, button_label) else: self.radio = RadioButtons(rax, np.arange(self.Dim)) self.count_click = None # 枠線と目盛りの消去 self.Map1.spines["right"].set_color("none") self.Map1.spines["left"].set_color("none") self.Map1.spines["top"].set_color("none") self.Map1.spines["bottom"].set_color("none") self.Map2.spines["right"].set_color("none") self.Map2.spines["left"].set_color("none") self.Map2.spines["top"].set_color("none") self.Map2.spines["bottom"].set_color("none") self.Map1.tick_params(labelbottom='off', color='white') self.Map1.tick_params(labelleft='off') self.Map2.tick_params(labelbottom='off', color='white') self.Map2.tick_params(labelleft='off') # textboxのプロパティ self.bbox_labels = dict(fc="gray", ec="black", lw=2, alpha=0.5) self.bbox_mouse = dict(fc="yellow", ec="black", lw=2, alpha=0.9) # 勝者が被った場合にラベルが重ならないようにするためのノイズ self.noise_map1 = (np.random.rand(self.Winner1.shape[0], 2) - 0.5) self.noise_map2 = (np.random.rand(self.Winner2.shape[0], 2) - 0.5) def hzfunc(self, label): #radioボタンを押した時の処理 if self.count_click == self.hzdict[label]: return else: self.count_click = self.hzdict[label] self.Map3_click_unit = self.hzdict[label] self.__calc_component(1) self.__calc_component(2) self.__draw_map1() self.__draw_map2() self.__draw_click_point() # ------------------------------ # # --- イベント時の処理 ----------- # # ------------------------------ # # クリック時の処理 def __onclick_fig(self, event): if event.xdata is not None: # クリック位置取得 click_pos = np.random.rand(1, 2) click_pos[0, 0] = event.xdata click_pos[0, 1] = event.ydata if event.inaxes == self.Map1.axes: # 左のマップをクリックした時 self.Map1_click_unit = self.__calc_arg_min_unit( self.Map1_position, click_pos) # コンポーネント値計算 self.__calc_component(2) self.click_map = 1 elif event.inaxes == self.Map2.axes: # 右のマップをクリックした時 self.Map2_click_unit = self.__calc_arg_min_unit( self.Map2_position, click_pos) # コンポーネント値計算 self.__calc_component(1) self.click_map = 2 else: return # コンポーネントプレーン表示 self.__draw_map1() self.__draw_map2() self.__draw_click_point() # マウスオーバー時(in)の処理 def __mouse_over_fig(self, event): if event.xdata is not None: # マウスカーソル位置取得 click_pos = np.random.rand(1, 2) click_pos[0, 0] = event.xdata click_pos[0, 1] = event.ydata if event.inaxes == self.Map1.axes: # 左マップのマウスオーバー処理 mouse_over_unit = self.__calc_arg_min_unit( self.Map1_position, click_pos) self.__draw_mouse_over_label_map1(mouse_over_unit) elif event.inaxes == self.Map2.axes: # 右のマップのマウスオーバー処理 mouse_over_unit = self.__calc_arg_min_unit( self.Map2_position, click_pos) self.__draw_mouse_over_label_map2(mouse_over_unit) self.__draw_click_point() self.Fig.show() # マウスオーバー時(out)の処理 def __mouse_leave_fig(self, event): self.__draw_map1() self.__draw_map2() self.radio.on_clicked(self.hzfunc) self.__draw_click_point() # ------------------------------ # # --- 描画 ---------------------- # # ------------------------------ # def draw_map(self): # コンポーネントの初期表示(左下が0番目のユニットが来るように行列を上下反転している) self.__draw_map1() self.__draw_map2() self.radio.on_clicked(self.hzfunc) self.__draw_click_point() # クリックイベント self.Fig.canvas.mpl_connect('button_press_event', self.__onclick_fig) # マウスオーバーイベント self.Fig.canvas.mpl_connect('motion_notify_event', self.__mouse_over_fig) self.Fig.canvas.mpl_connect('axes_leave_event', self.__mouse_leave_fig) plt.show() # ------------------------------ # # --- ラベルの描画 --------------- # # ------------------------------ # # 左のマップ def __draw_label_map1(self): epsilon = 0.02 * (self.Map1_position.max() - self.Map1_position.min()) if not self.label1 is None: #ラベルを与えばそのラベルを出力,そうでないなら出力しない for i in range(self.Winner1.shape[0]): self.Map1.text(self.Map1_position[self.Winner1[i], 0] + epsilon * self.noise_map1[i, 0], self.Map1_position[self.Winner1[i], 1] + epsilon * self.noise_map1[i, 1], self.label1[i], ha='center', va='bottom', color='black') self.Map1.scatter(self.Map1_position[self.Winner1[:], 0] + epsilon * self.noise_map1[:, 0], self.Map1_position[self.Winner1[:], 1] + epsilon * self.noise_map1[:, 1], c="white", linewidths=1, edgecolors="black") self.Fig.show() # 右のマップ def __draw_label_map2(self): epsilon = 0.02 * (self.Map2_position.max() - self.Map2_position.min()) if not self.label2 is None: # ラベルを与えばそのラベルを出力,そうでないなら出力しない for i in range(self.Winner2.shape[0]): self.Map2.text(self.Map2_position[self.Winner2[i], 0] + epsilon * self.noise_map2[i, 0], self.Map2_position[self.Winner2[i], 1] + epsilon * self.noise_map2[i, 1], self.label2[i], ha='center', va='bottom', color='black') self.Map2.scatter(self.Map2_position[self.Winner2[:], 0] + epsilon * self.noise_map2[:, 0], self.Map2_position[self.Winner2[:], 1] + epsilon * self.noise_map2[:, 1], c="white", linewidths=1, edgecolors="black") self.Fig.show() # ------------------------------ # # --- ラベルの描画(マウスオーバ時) - # # ------------------------------ # # 左のマップ def __draw_mouse_over_label_map1(self, mouse_over_unit): wine_labels = " " # for i in range(self.Winner0.shape[0]): # if mouse_over_unit == self.Winner0[i]: # if len(wine_labels) <= 1: # wine_labels = self.labels0[i] # temp = i # else: # wine_labels = wine_labels + "\n" + self.labels0[i] # if len(wine_labels) > 1: # if self.radio_click_flg == 0: # self.__draw_map0() # elif self.radio_click_flg == 1: # self.__draw_radio1_data() # self.__draw_map0() # elif self.radio_click_flg == 2: # self.__draw_radio2_data() # self.__draw_map0() # if self.Winner0[temp] % self.map0x_num < self.map0x_num / 2.0: # self.Map0.text(self.Map0_position[mouse_over_unit, 0], self.Map0_position[mouse_over_unit, 1], # wine_labels, color='black', ha='left', va='center', bbox=self.bbox_mouse) # else: # self.Map0.text(self.Map0_position[mouse_over_unit, 0], self.Map0_position[mouse_over_unit, 1], # wine_labels, color='black', ha='right', va='center', bbox=self.bbox_mouse) # 右のマップ def __draw_mouse_over_label_map2(self, mouse_over_unit): chemical_labels = " " # for i in range(self.Winner2.shape[0]): # if mouse_over_unit == self.Winner2[i]: # if len(chemical_labels) <= 1: # chemical_labels = self.labels2[i] # temp = i # else: # chemical_labels = chemical_labels + "\n" + self.labels2[i] # if len(chemical_labels) > 1: # self.__draw_map2() # if self.Winner2[temp] % self.map2x_num < self.map2x_num / 2.0: # self.Map2.text(self.Map2_position[mouse_over_unit, 0], self.Map2_position[mouse_over_unit, 1], # chemical_labels, color='black', ha='left', va='center', bbox=self.bbox_mouse) # else: # self.Map2.text(self.Map2_position[mouse_over_unit, 0], self.Map2_position[mouse_over_unit, 1], # chemical_labels, color='black', ha='right', va='center', bbox=self.bbox_mouse) # ------------------------------ # # --- クリック位置の描画 ---------- # # ------------------------------ # def __draw_click_point(self): self.Map1.plot(self.Map1_position[self.Map1_click_unit, 0], self.Map1_position[self.Map1_click_unit, 1], ".", color="black", ms=30, fillstyle="none") self.Map2.plot(self.Map2_position[self.Map2_click_unit, 0], self.Map2_position[self.Map2_click_unit, 1], ".", color="black", ms=30, fillstyle="none") self.Fig.show() # ------------------------------ # # --- コンポーネントプレーン表示 --- # # ------------------------------ # def __draw_map1(self): self.Map1.cla() self.Map1.set_title('Cases View') self.__draw_label_map1() self.Map1.imshow(self.Map1_val[::], interpolation='spline36', extent=[ 0, self.Map1_val.shape[0] - 1, -self.Map1_val.shape[1] + 1, 0 ], cmap="rainbow") self.Map1.set_xlim(-1, self.Mapsize) self.Map1.set_ylim(-self.Mapsize, 1) self.Fig.show() def __draw_map2(self): self.Map2.cla() self.Map2.set_title('Parameter View') # self.Map2.set_xlabel("Aroma Map") self.Map2.xaxis.set_label_coords(0.5, -0.1) self.__draw_label_map2() self.Map2.imshow(self.Map2_val[::], interpolation='spline36', extent=[ 0, self.Map2_val.shape[0] - 1, -self.Map2_val.shape[1] + 1, 0 ], cmap="rainbow") self.Map2.set_xlim(-1, self.Mapsize) self.Map2.set_ylim(-self.Mapsize, 1) self.Fig.show() # ------------------------------ # # --- コンポーネント値の算出 ------ # # ------------------------------ # def __calc_component(self, map_num): if map_num == 1: temp1 = self.Y[:, self.Map2_click_unit, self.Map3_click_unit] # print(temp1.shape) self.Map1_val = temp1.reshape( (self.map1x_num, self.map1x_num) ) #np.sqrt(np.sum(temp1 * temp1, axis=1)).reshape([self.map1x_num, self.map1x_num]) else: temp2 = self.Y[self.Map1_click_unit, :, self.Map3_click_unit] # print(temp2.shape) self.Map2_val = temp2.reshape( (self.map2x_num, self.map2x_num) ) #np.sqrt(np.sum(temp2 * temp2, axis=1)).reshape([self.map2x_num, self.map2x_num]) # ------------------------------ # # --- 最近傍ユニット算出 ---------- # # ------------------------------ # @staticmethod def __calc_arg_min_unit(zeta, click_point): distance = dist.cdist(zeta, click_point) unit = np.argmin(distance, axis=0) return unit[0]
class LineExtractor(object): """ Parameters ---------- pixels path Attributes ---------- sel_fig sel_axes ann_fig ann_axes select_image cropper cropped_img line_manual line_shadow points_manual points_shadow select_iamge dump_button dump_func path """ def __init__(self, pixels, path): self.sel_fig, self.sel_axes = self.create_selector_figure() self.ann_fig, self.ann_axes = self.create_annotate_figure() self.select_image = self.sel_axes['img'].imshow(pixels) self.cropper = ShutterCrop(self.sel_axes['img']) self.cropper.active = False self.cropper.set_visible(True) self.cropped_img = CroppedImage(self.ann_axes['img'], pixels) self.cropped_img.make_xyextent_textboxes(self.ann_axes['xlo'], self.ann_axes['xhi'], self.ann_axes['ylo'], self.ann_axes['yhi']) self.cropper.on_changed( lambda has_extent: self.cropped_img.crop(has_extent.get_extents()), args=[self.cropper]) line_kw = dict(linewidth=0.5, color='k', alpha=0.5) circle_kw = dict(radius=15, alpha=0.5) self.line_manual = DeformableLine(self.sel_axes['img'], grows=True, shrinks=True, line_kw=line_kw, circle_kw=circle_kw) self.line_manual.active = False self.line_manual.set_visible(True) self.line_shadow = ShadowLine(self.ann_axes['img'], self.line_manual, self.cropper, marker='o', markersize=15, **line_kw) self.cropper.on_changed(self.line_shadow.update) line_kw = dict(lw=0) circle_kw = dict(radius=10, color='k') self.points_manual = DeformableLine( self.sel_axes['img'], grows=True, shrinks=True, line_kw=line_kw, circle_kw=circle_kw, ) self.points_manual.active = False self.points_manual.set_visible(True) # shadow data plotted in axes coordiates self.points_shadow = ShadowLine(self.ann_axes['img'], self.points_manual, self.cropper, marker='o', markersize=10, **line_kw) self.cropper.on_changed(self.points_shadow.update) # the xlim/ylim may have changed due to adding the lines # set xlim/ylim to the pre-lines-added state extent = self.select_image.get_extent() self.select_image.axes.set_xlim(extent[:2]) self.select_image.axes.set_ylim(extent[2:]) extent = self.cropped_img.image.get_extent() self.cropped_img.ax.set_xlim(extent[:2]) self.cropped_img.ax.set_ylim(extent[2:]) self.create_selector_toggle() self.dump_button = Button(self.ann_axes['dump'], 'Dump to file') self.dump_func = self.dump_npz self.dump_button.on_clicked(self.dump) self.path = path def create_selector_toggle(self): self.selector_widgets = OrderedDict() self.selector_widgets['Do nothing'] = NothingWidget() self.selector_widgets['Crop'] = self.cropper self.selector_widgets['Segmented Line'] = self.line_manual self.selector_widgets['Manual Points'] = self.points_manual self.toggle_state('Do nothing') self.select_radio = RadioButtons(self.sel_axes['select'], labels=self.selector_widgets.keys(), active=0) self.select_radio.on_clicked(self.toggle_state) def toggle_state(self, new_state): """Change the active selector widget""" assert new_state in self.selector_widgets for k in self.selector_widgets: if k == new_state: continue self.selector_widgets[k].active = False self.selector_widgets[new_state].active = True def create_selector_figure(self, gut=0.04, sepx=0.01, wide=0.2, tall=0.3, **ax_kwargs): fig = plt.figure() axes = {} x0 = gut + wide + sepx x1 = 1 - (gut + sepx) y0 = gut y1 = 1 - gut l, b = x0, y0 w, h = x1 - x0, y1 - y0 img = fig.add_axes([l, b, w, h], **ax_kwargs) img.yaxis.set_visible(False) img.xaxis.set_visible(False) axes['img'] = img l, b = gut, 0.5 * (y0 + y1 - tall) w, h = wide, tall select = fig.add_axes([l, b, w, h], **ax_kwargs) select.yaxis.set_visible(False) select.xaxis.set_visible(False) axes['select'] = select return fig, axes def create_annotate_figure(self, gut=0.04, sepx=0.05, sepy=0.04, wide=0.09, tall=0.06, **ax_kwargs): fig = plt.figure() axes = {} x0 = gut + wide + sepx x1 = 1 - (gut + sepx) y0 = gut + tall + sepy y1 = 1 - gut l, b = x0, y0 w, h = x1 - x0, y1 - y0 axes['img'] = fig.add_axes([l, b, w, h], **ax_kwargs) sizes = {} sizes['yhi'] = (gut, 1 - gut - tall, wide, tall) sizes['ylo'] = (gut, gut + tall + sepy, wide, tall) sizes['xlo'] = (x0, gut, wide, tall) sizes['xhi'] = (x1 - wide, gut, wide, tall) sizes['dump'] = (x0 + wide + sepx, gut, x1 - x0 - 2 * (sepx + wide), tall) for name, lbwh in sizes.items(): ax = fig.add_axes(lbwh, **ax_kwargs) ax.yaxis.set_visible(False) ax.xaxis.set_visible(False) axes[name] = ax return fig, axes def get_data(self): data = {} data['x'] = None data['y'] = None raise NotImplemented return data def dump_npz(self): data = self.get_data() print('dumping to', self.path) np.savez(self.path, **data) print('dumped') def dump_txt(self): data = self.get_data() print('dumping to %s.*.txt' % self.path) for key, val in data: np.savetxt('%s.%s.txt' % (self.path, key), val) print('dumped') def dump(self, event): self.dump_func()
nx.draw(G, with_labels=False, node_color='darkviolet', node_size=[size * 10 for size in degree_dict.values()], edge_color='red', alpha=0.5, linewidths=2, font_size=5, pos=nx.fruchterman_reingold_layout(G)) string = label + "\n" + "Connections shown: " + str(G.number_of_edges()) fig2.suptitle(string, fontsize=14, fontweight='bold', fontdict=font) fig2.set_facecolor("#00000F") plt.draw() radio.on_clicked(network) def network2(label): ''' Draws the network of the selected University @param label: string - The name of the radio button for the University selected ''' global school_dict fig3 = plt.figure(3, figsize=(10, 10)) fig3.clear() G = school_dict[label] degree_dict = nx.get_node_attributes(G, 'degree') nx.draw(G, with_labels=False,
class FreesurferReviewInterface(BaseReviewInterface): """Custom interface for rating the quality of Freesurfer parcellation.""" def __init__(self, fig, axes_seg, rating_list=cfg.default_rating_list, next_button_callback=None, quit_button_callback=None, alpha_seg=cfg.default_alpha_seg): """Constructor""" super().__init__(fig, axes_seg, next_button_callback, quit_button_callback) self.rating_list = rating_list self.overlaid_artists = axes_seg self.latest_alpha_seg = alpha_seg self.prev_axis = None self.prev_ax_pos = None self.zoomed_in = False self.add_radio_buttons() self.add_alpha_slider() self.next_button_callback = next_button_callback self.quit_button_callback = quit_button_callback # this list of artists to be populated later # makes to handy to clean them all self.data_handles = list() self.unzoomable_axes = [ self.radio_bt_rating.ax, self.text_box.ax, self.bt_next.ax, self.bt_quit.ax ] def add_radio_buttons(self): ax_radio = plt.axes(cfg.position_radio_buttons, facecolor=cfg.color_rating_axis, aspect='equal') self.radio_bt_rating = RadioButtons(ax_radio, self.rating_list, active=None, activecolor='orange') self.radio_bt_rating.on_clicked(self.save_rating) for txt_lbl in self.radio_bt_rating.labels: txt_lbl.set(color=cfg.text_option_color, fontweight='normal') for circ in self.radio_bt_rating.circles: circ.set(radius=0.06) def add_alpha_slider(self): """Controls the transparency level of overlay""" # alpha slider ax_slider = plt.axes(cfg.position_slider_seg_alpha, facecolor=cfg.color_slider_axis) self.slider = Slider(ax_slider, label='transparency', valmin=0.0, valmax=1.0, valinit=0.7, valfmt='%1.2f') self.slider.label.set_position((0.99, 1.5)) self.slider.on_changed(self.set_alpha_value) def save_rating(self, label): """Update the rating""" # print(' rating {}'.format(label)) self.user_rating = label def get_ratings(self): """Returns the final set of checked ratings""" return self.user_rating def allowed_to_advance(self): """ Method to ensure work is done for current iteration, before allowing the user to advance to next subject. Returns False if atleast one of the following conditions are not met: Atleast Checkbox is checked """ return self.radio_bt_rating.value_selected is not None def reset_figure(self): "Resets the figure to prepare it for display of next subject." self.clear_data() self.clear_radio_buttons() self.clear_notes_annot() def clear_data(self): """clearing all data/image handles""" if self.data_handles: for artist in self.data_handles: artist.remove() # resetting it self.data_handles = list() # this is populated for each unit during display self.overlaid_artists.clear() def clear_radio_buttons(self): """Clears the radio button""" # enabling default rating encourages lazy advancing without review # self.radio_bt_rating.set_active(cfg.index_freesurfer_default_rating) for index, label in enumerate(self.radio_bt_rating.labels): if label.get_text() == self.radio_bt_rating.value_selected: self.radio_bt_rating.circles[index].set_facecolor( cfg.color_rating_axis) break self.radio_bt_rating.value_selected = None def clear_notes_annot(self): """clearing notes and annotations""" self.text_box.set_val(cfg.textbox_initial_text) # text is matplotlib artist self.annot_text.remove() def on_mouse(self, event): """Callback for mouse events.""" if self.prev_axis is not None: # include all the non-data axes here (so they wont be zoomed-in) if event.inaxes not in self.unzoomable_axes: self.prev_axis.set_position(self.prev_ax_pos) self.prev_axis.set_zorder(0) self.prev_axis.patch.set_alpha(0.5) self.zoomed_in = False # right click toggles overlay if event.button in [3]: self.toggle_overlay() # double click to zoom in to any axis elif event.dblclick and event.inaxes is not None and \ event.inaxes not in self.unzoomable_axes: # zoom axes full-screen self.prev_ax_pos = event.inaxes.get_position() event.inaxes.set_position(cfg.zoomed_position) event.inaxes.set_zorder(1) # bring forth event.inaxes.set_facecolor('black') # black event.inaxes.patch.set_alpha(1.0) # opaque self.zoomed_in = True self.prev_axis = event.inaxes else: pass plt.draw() def on_keyboard(self, key_in): """Callback to handle keyboard shortcuts to rate and advance.""" # ignore keyboard key_in when mouse within Notes textbox if key_in.inaxes == self.text_box.ax or key_in.key is None: return key_pressed = key_in.key.lower() # print(key_pressed) if key_pressed in ['right', ' ', 'space']: self.next_button_callback() if key_pressed in ['ctrl+q', 'q+ctrl']: self.quit_button_callback() else: if key_pressed in cfg.default_rating_list_shortform: self.user_rating = cfg.map_short_rating[key_pressed] index_to_set = cfg.default_rating_list.index(self.user_rating) self.radio_bt_rating.set_active(index_to_set) elif key_pressed in ['t']: self.toggle_overlay() else: pass def toggle_overlay(self): """Toggles the overlay by setting alpha to 0 and back.""" if self.latest_alpha_seg != 0.0: self.prev_alpha_seg = self.latest_alpha_seg self.latest_alpha_seg = 0.0 else: self.latest_alpha_seg = self.prev_alpha_seg self.update() def set_alpha_value(self, latest_value): """" Use the slider to set alpha.""" self.latest_alpha_seg = latest_value self.update() def update(self): """updating seg alpha for all axes""" for art in self.overlaid_artists: art.set_alpha(self.latest_alpha_seg) # update figure plt.draw()
class HyperparameterExplorer(object): def __init__(self, store, ws_name, run_group_type, run_group_name, hp_config_cloud_path, hp_config_local_dir, plot_x_metric_name, plot_y_metric_name, hist_x_metric_name): # on-demand import (since reference causes fonts to rebuild cache...) global plt, Rectangle, Button, RadioButtons import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from matplotlib.widgets import Button from matplotlib.widgets import RadioButtons # Initialize the graphics. self.fig = plt.figure(figsize=(20, 12)) self.fig.canvas.set_window_title('Hyperparameter Explorer') self.left_pane_axes = self.fig.add_axes([0.0, 0.0, 1.0, 1.0]) self.left_pane_axes.get_xaxis().set_visible(False) self.left_pane_axes.get_yaxis().set_visible(False) self.left_pane_axes.spines["left"].set_visible(False) self.left_pane_axes.spines["right"].set_visible(False) self.left_pane_axes.spines["top"].set_visible(False) self.left_pane_axes.spines["bottom"].set_visible(False) self.plot_style = STD_DEV self.radio_buttons_axes = self.fig.add_axes([0.83, 0.07, 0.14, 0.1]) self.radio_buttons = RadioButtons( self.radio_buttons_axes, (PLOT_STYLE_LABELS[0], PLOT_STYLE_LABELS[1], PLOT_STYLE_LABELS[2])) self.radio_buttons_axes.set_zorder(20) self.radio_buttons.on_clicked(self.radio_buttons_on_clicked) # Get the data. local_config_file_path, all_run_records = self.download_runs( store, ws_name, run_group_name, run_group_type, hp_config_cloud_path, hp_config_local_dir) # Handle the hyperparameters. self.hparams = [] self.set_current_hparam(None) self.define_hyperparameters( local_config_file_path) # Get the superset of hparam definitions. self.load_runs( all_run_records, plot_x_metric_name, plot_y_metric_name, hist_x_metric_name) # Populate the run objects with some data. self.get_plot_bounds_from_runs() self.populate_hparams() # Assemble runsets. self.configstring_runset_dict = {} self.group_runs_into_runsets() for run in self.runs: run.update_inclusion( ) # This takes into consideration any non-included settings. # Left pane. self.assemble_left_pane() self.create_hparam_border() # Center pane. # Create a fixed set of histogram objects to be reused for all settings. # The first (top) histogram is the aggregate for all settings (in the focus). self.hists = [] for i in range(self.max_settings_per_hparam + 1): self.hists.append( Histogram(self, self.fig, i, self.max_settings_per_hparam + 1, hist_x_metric_name)) axes_to_share = self.hists[self.max_settings_per_hparam].add_axes(None) for i in range(self.max_settings_per_hparam): self.hists[self.max_settings_per_hparam - i - 1].add_axes(axes_to_share) self.update_histograms() # Right pane. self.perf = PerformanceChart(self, self.fig, self.plot_num_points, self.plot_min_x, self.plot_x_inc, ws_name, run_group_type, run_group_name, plot_x_metric_name, plot_y_metric_name) def download_runs(self, store, ws_name, run_group_name, run_group_type, hp_config_cloud_path, hp_config_local_dir): # Download the all_runs file local_cache_path = "{}/{}/{}/".format(hp_config_local_dir, ws_name, run_group_type) local_config_file_path = "{}{}".format(local_cache_path, "hp-config.yaml") if run_group_name == "experiment": console.print( "downloading runs for EXPERIMENT={}...".format(run_group_type)) # files are at EXPERIMENT LEVEL # read SWEEPS file if not store.does_experiment_file_exist(ws_name, run_group_type, hp_config_cloud_path): errors.store_error( "missing experiment hp_config file (ws={}, exper={}, fn={})" .format(ws_name, run_group_type, hp_config_cloud_path)) store.download_file_from_experiment(ws_name, run_group_type, hp_config_cloud_path, local_config_file_path) # read ALLRUNS info aggregated in EXPERIMENT allrun_records = store.get_all_runs(run_group_name, ws_name, run_group_type) else: console.print( "downloading runs for JOB={}...".format(run_group_type)) # files are at JOB LEVEL # read SWEEPS file if not store.does_job_file_exist(run_group_type, hp_config_cloud_path): errors.store_error( "missing job hp_config file (job={}, fn={})".format( run_group_type, hp_config_cloud_path)) store.download_file_from_job(run_group_type, hp_config_cloud_path, local_config_file_path) # read ALLRUNS info aggregated in JOB allrun_records = store.get_all_runs(run_group_name, ws_name, run_group_type) console.diag("after downloading all runs") return local_config_file_path, allrun_records def radio_buttons_on_clicked(self, label): if label == PLOT_STYLE_LABELS[self.plot_style]: return if label == PLOT_STYLE_LABELS[0]: self.plot_style = 0 elif label == PLOT_STYLE_LABELS[1]: self.plot_style = 1 elif label == PLOT_STYLE_LABELS[2]: self.plot_style = 2 self.perf.prev_curve = None self.perf.plot_from_runs() self.fig.canvas.draw() def draw(self): self.hist.draw() def create_hparam_border(self): if len(self.name_hparam_dict) > 0: if len(self.displayed_hparams) > 0: rect = self.displayed_hparams[0].button_axes.get_position() xm = 0.004 ym = 0.006 x = rect.x0 - xm y = 2.0 w = (rect.x1 - rect.x0) + 2 * xm h = (rect.y1 - rect.y0) + 2 * ym rectangle = Rectangle((x, y), w, h, linewidth=4, edgecolor='g', facecolor='none') self.hparam_border = self.left_pane_axes.add_patch(rectangle) def add_hparam(self, hparam): self.hparams.append(hparam) def set_current_hparam(self, hparam): self.current_hparam = hparam if hparam != None: rect = hparam.button_axes.get_position() xm = 0.004 ym = 0.006 x = rect.x0 - xm y = rect.y0 - ym self.hparam_border.set_xy([x, y]) def run(self, timeout=None): if len(self.runs) == 0: console.print("error - no valid runs found") return if timeout: # build a thread to close our plot window after specified time from threading import Thread def set_timer(timeout): console.print("set_timer called: timeout=", timeout) time.sleep(timeout) console.diag("timer triggered!") plt.close("all") thread = Thread(target=set_timer, args=[timeout]) thread.daemon = True # mark as background thread thread.start() plt.show() def define_hyperparameters(self, hp_config_file_path): self.name_hparam_dict = {} import yaml hp_config_yaml = yaml.load(stream=open(hp_config_file_path, 'r'), Loader=yaml.Loader) hp_dict = hp_config_yaml["hparams"] for name, values in hp_dict.items(): if not isinstance(values, list): continue # Only lists of values are handled at the moment. hparam = Hyperparameter(self, self.fig, name) for value in values: hparam.add_setting(value, True) self.name_hparam_dict[name] = hparam self.add_hparam(hparam) def load_runs(self, all_run_records, plot_x_metric_name, plot_y_metric_name, hist_x_metric_name): self.runs = [] for record in all_run_records: run = Run(record, plot_x_metric_name, plot_y_metric_name, hist_x_metric_name) if len(run.metric_reports) == 0: # Exclude parent runs. continue self.runs.append(run) if MAX_NUM_RUNS > 0: if len(self.runs) == MAX_NUM_RUNS: break console.print("{} runs downloaded".format(len(self.runs))) def get_plot_bounds_from_runs(self): self.plot_min_x = np.PINF self.plot_max_x = np.NINF self.plot_min_y = np.PINF self.plot_max_y = np.NINF self.hist_min_x = np.PINF self.hist_max_x = np.NINF max_reports = 0 for run in self.runs: if len(run.metric_reports) > max_reports: max_reports = len(run.metric_reports) for report in run.metric_reports: x = report.x if x > self.plot_max_x: self.plot_max_x = x if x < self.plot_min_x: self.plot_min_x = x y = report.y if y > self.plot_max_y: self.plot_max_y = y if y < self.plot_min_y: self.plot_min_y = y if run.summary_val > self.hist_max_x: self.hist_max_x = run.summary_val if run.summary_val < self.hist_min_x: self.hist_min_x = run.summary_val self.plot_num_points = max_reports self.plot_x_inc = (self.plot_max_x - self.plot_min_x) / (self.plot_num_points - 1) def populate_hparams(self): # Connect up the runs and hparams. for run in self.runs: for hparam_name in run.hparam_name_value_pairs.keys( ): # Only hparams that were read by the code, if hparam_name in self.name_hparam_dict.keys( ): # and were listed in config_overrides.txt. hparam = self.name_hparam_dict[hparam_name] setting_value = run.hparam_name_value_pairs[hparam_name] setting = hparam.add_setting(setting_value, False) run.settings.append(setting) # Decide which hparams to display in the left pane. for hparam_name, hparam in self.name_hparam_dict.items(): if len(hparam.value_setting_dict) > 1: hparam.display = True setting_values = [] for setting in hparam.value_setting_dict.values(): setting_values.append(setting.value) # Sort the settings, to determine their display order in the middle pane. setting_values.sort() for val in setting_values: hparam.settings.append(hparam.value_setting_dict[val]) def group_runs_into_runsets(self): # Create the runsets. for run in self.runs: for hparam_name in run.hparam_name_value_pairs.keys( ): # Only hparams that were read by the code, if hparam_name in self.name_hparam_dict.keys( ): # and were listed in config_overrides.txt, hparam = self.name_hparam_dict[hparam_name] if hparam.display: # and are currently selected for display. run.configuration_string += '{}, '.format( run.hparam_name_value_pairs[hparam_name]) if run.configuration_string not in self.configstring_runset_dict.keys( ): self.configstring_runset_dict[ run.configuration_string] = RunSet( run.configuration_string) runset = self.configstring_runset_dict[run.configuration_string] runset.runs.append(run) self.max_runs_per_runset = 0 for runset in self.configstring_runset_dict.values(): num_runs = len(runset.runs) if num_runs > self.max_runs_per_runset: self.max_runs_per_runset = num_runs # Finalize each runset. for runset in self.configstring_runset_dict.values(): runset.count = len(runset.runs) # Average total = 0. for run in runset.runs: total += run.summary_val runset.metric = total / runset.count def assemble_left_pane(self): self.max_settings_per_hparam = 0 id = 0 self.displayed_hparams = [] for hparam in self.hparams: if hparam.display: self.displayed_hparams.append(hparam) num_settings = len(hparam.settings) if num_settings > self.max_settings_per_hparam: self.max_settings_per_hparam = num_settings hparam.id = id id += 1 hparam.init_button() self.num_settings_to_display = self.max_settings_per_hparam def update_histograms(self): for hist in self.hists: hist.update() self.hists[0].axes.set_xlim(self.hist_min_x, self.hist_max_x) def update_runs(self): for run in self.runs: run.update_inclusion() self.update_histograms() self.perf.plot_from_runs() self.fig.canvas.draw()
def genHDBdwelling(): import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons title = "Total HDB Dwellings" titlelen = len(title) print("{:*^{titlelen}}".format(title, titlelen=titlelen + 6)) print() data = np.genfromtxt( 'data/resident-households-by-type-of-dwelling-hdb-ethnic-grp-of-head-of-household-tenancy.csv', skip_header=1, dtype=[('year', 'U10'), ('level_1', 'U50'), ('level_2', 'U50'), ('level_3', 'U50'), ('level_4', 'U50'), ('value', 'f8')], delimiter=",", missing_values=['na', '-'], filling_values=[0]) #print("Original data: " + str(data.shape)) null_rows = np.isnan(data['value']) nonnull_values = data[null_rows == False] #print("Filtered data: " + str(nonnull_values.shape)) #Get only Total value of each categories dataTotal = data[data['level_2'] == 'Total'] flatType = '4-Room Flats' dataSelect = dataTotal[dataTotal['level_4'] == flatType] #print(dataSelect) fig, ax = plt.subplots(figsize=(19, 15), subplot_kw=dict(aspect="equal")) plt.subplots_adjust(bottom=0.25) def plotPieChart(dataSelect): labels = list(set(dataSelect['level_1'])) labels = ['Chinese', 'Malays', 'Indians', 'Others'] levels = np.arange(0, len(labels)) levels_values = dataSelect[['level_1', 'value']] values = levels_values['value'] values_TotalHDBDwellings = values[levels_values['level_1'] == 'Total'] values_Chinese = values[levels_values['level_1'] == 'Chinese'] values_Malays = values[levels_values['level_1'] == 'Malays'] values_Indians = values[levels_values['level_1'] == 'Indians'] values_Others = values[levels_values['level_1'] == 'Others'] values_combined = [ values_Chinese, values_Malays, values_Indians, values_Others ] racesList = np.concatenate(values_combined).ravel().tolist() #print(racesList) ax.clear() def func(pct, allvals): absolute = int(pct / 100. * np.sum(allvals)) return "{:.1f}%\n({:d} g)".format(pct, absolute) wedges, texts, autotexts = ax.pie( racesList, autopct=lambda pct: func(pct, racesList), textprops=dict(color="w")) ax.legend(wedges, labels, title="HDB Dwelling By Ethnic Group", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1)) plt.setp(autotexts, size=8, weight="bold") ax.set_title("HDB Dwelling By Ethnic Group and Flat Type") plotPieChart(dataSelect) ###### ['1- and 2-Room Flats', '3-Room Flats', '4-Room Flats', '5-Room and Executive Flats'] axcolor = 'lightgoldenrodyellow' radioax = plt.axes([0.25, 0.08, 0.15, 0.12], facecolor=axcolor) radio = RadioButtons(radioax, ('1- and 2-Room Flats', '3-Room Flats', '4-Room Flats', '5-Room and Executive Flats'), active=2) def flatTypefunc(label): global flatType flatType = label dataSelect = dataTotal[dataTotal['level_4'] == flatType] plotPieChart(dataSelect) #fig.canvas.draw_idle() plt.draw() radio.on_clicked(flatTypefunc) plt.show()
#Setup for the graph (left, bottom, width, height0 histRect=[0.25, 0.15, 0.7, 0.65] rugRect=[0.25, 0.1, 0.7, 0.05] controlRect=[0.05, 0.15, 0.15, 0.25] fig=plt.figure(facecolor='white') axescolor="#f6f6f6" controlPanel=fig.add_axes(controlRect) controlFields=[] radio=RadioButtons(controlPanel, hist1.fieldnames, active=0) ax1=fig.add_axes(histRect, axisbg=axescolor) ax1.grid(True) ax1.axes.get_xaxis().set_visible(False) ax2=fig.add_axes(rugRect, axisbg=axescolor, sharex=ax1) zeros=[0]*hist1.length() ax2.axes.get_yaxis().set_visible(False) ax1.hist(hist1.data, facecolor='green', alpha=0.75, align='mid', range=(hist1.min, hist1.max), rwidth=1) ax2.plot(hist1.data, zeros, "|") def columnChange(column): hist1=Histogram(filename, column, format) ax1.clear() ax2.clear() ax1.hist(hist1.data, facecolor='green', alpha=0.75, align='mid', range=(hist1.min, hist1.max), rwidth=1) ax2.plot(hist1.data, zeros, "|") radio.on_clicked(columnChange) show()
class WindowedSincFilterDesigner: def __init__(self): self.samplerate = 48000 self.framesize = 512 self.cutoff = self.samplerate / 4.0 self.bandwidth = 1000 self.nfft = 0 self.filter_type = 'Lowpass' self.flt = yodel.filter.WindowedSinc(self.samplerate, self.framesize) self.update_filter() self.create_plot() self.create_controls() def create_plot(self): self._fig, self._ax = plt.subplots() self._ax.set_title('Windowed Sinc Filter Design') self._ax.grid() plt.subplots_adjust(bottom=0.3) self._l_bot, = self._ax.plot(self.fr_xscale, [0] * self.nfft, 'k') self._l_top, = self._ax.plot(self.fr_xscale, [-100] * self.nfft, 'k') self._l_fr, = self._ax.plot(self.fr_xscale, self.fr_amp, 'b') self.rescale_plot() def create_controls(self): self._rax = plt.axes([0.30, 0.03, 0.15, 0.20]) self._radio = RadioButtons(self._rax, ('Lowpass', 'Highpass', 'Bandpass', 'Bandreject')) self._radio.on_clicked(self.set_filter_type) self._sfax = plt.axes([0.6, 0.19, 0.2, 0.03]) self._dlyslider = Slider(self._sfax, 'Cut-off', 1.0, self.samplerate / 2.0, valinit=self.cutoff) self._dlyslider.on_changed(self.set_filter_cutoff) self._sfax = plt.axes([0.6, 0.10, 0.2, 0.03]) self._gainslider = Slider(self._sfax, 'Bandwidth', 10, 5000, valinit=self.bandwidth) self._gainslider.on_changed(self.set_filter_bandwidth) def update_filter(self): if self.filter_type == 'Lowpass': self.flt.low_pass(self.cutoff, self.bandwidth) elif self.filter_type == 'Highpass': self.flt.high_pass(self.cutoff, self.bandwidth) elif self.filter_type == 'Bandpass': self.flt.band_pass(self.cutoff, self.bandwidth) elif self.filter_type == 'Bandreject': self.flt.band_reject(self.cutoff, self.bandwidth) frre, frim = frequency_response(self.flt.conv.ir) self.nfft = int((len(frre)/2.0)+1.0) self.fr_amp = amplitude_response(frre[0:self.nfft], frim[0:self.nfft]) self.fr_xscale = [int((i * self.samplerate / 2.0) / self.nfft) for i in range(0, self.nfft)] def set_filter_cutoff(self, cutoff): self.cutoff = cutoff self.update_filter() self.update_plot() def set_filter_bandwidth(self, bandwidth): self.bandwidth = bandwidth self.update_filter() self.update_plot() def set_filter_type(self, filter_type): self.filter_type = filter_type self.update_filter() self.update_plot() def update_plot(self): self._l_fr.set_xdata(self.fr_xscale) self._l_fr.set_ydata(self.fr_amp) self.rescale_plot() def rescale_plot(self): self._ax.set_ylim(-110, 5) plt.draw()
def backward(event): if pic_swap.val - 1 < 0: pass else: x = pic_swap.val - 1 pic_swap.set_val(x) roi1 = ROI(start.pic_list[0]) def update_values(event): roi1.update(rb.val, re.val, cb.val, ce.val) pic_switch(None) rb.on_changed(update_values) re.on_changed(update_values) cb.on_changed(update_values) ce.on_changed(update_values) pic_swap.on_changed(pic_switch) gray.on_clicked(pic_switch) skipf.on_clicked(forward) skipb.on_clicked(backward) vmin.on_changed(pic_switch) vmax.on_changed(pic_switch) zoom.on_clicked(pic_switch) update_values(None) pic_switch(None) plt.show()
class Graphics (GraphMolecule, GraphBias, GraphTrans, GraphOrbitals, GraphIVCurve): """ Manages the graphical representation of the project Attributes fig Handle to the entire figure Bias The selected bias Gate The selected gate voltage OrbitalSel The selected orbital or series of orbitals axSC Handle to the radio buttons window for the self consistency cbSC Handle to the radio buttons for the self consistency axOptions1 Handle to the checkbox window with options 1 cbOptions1 Handle to the checkboxes with options 1 axOptions2 Handle to the checkbox window with options 2 cbOptions2 Handle to the checkboxes with options 2 axGleft, axGright Handle to the slider windows for selecting the lead interaction strength sGleft, sGright Handle to the sliders for selecting the lead interaction strength axSave Handle to the save button window bSave Handle to the save button Methods init() OnPick(event) Manages the pick events OnClick(event) Manages the on click events Save() Manages the input from the save button Options1(label) Manages the input from the options 1 window Options2(label) Manages the input from the options 2 window SetMolecule(Mol) Sets the molecule class from which the graphics gets its information UpdateMolecule() Updates everything that changes when the molecule has changed UpdateConsistency(label)Updates the selected consistency method UpdateG(val) Updates the interaction strength with the leads UpdateBias(bias) Updates the selected bias UpdateHamExt() Updates everything that changes when the extended hamiltonian is changed UpdateGate(gate) Updates the selected gate voltage UpdateAtomSel(iAtom) Updates the selected atom UpdateOrbitalSel(iOrb) Updates the selected orbital UpdateSelection() Updates everything that changes after one of the selections has changed """ def __init__(self): self.Consistency = 'Not self consistent' self.Bias = 0.1 self.Gate = None self.OrbitalSel = None self.fig, (self.axBias, self.axTrans, self.axIVCurve) = plt.subplots(3,1) self.fig.patch.set_facecolor('ghostwhite') plt.subplots_adjust(left=0.3) pos = self.axBias.get_position() self.axBias.set_position ([pos.x0, 0.55, pos.width, 0.40]) self.axTrans.set_position([pos.x0, 0.05, pos.width, 0.40]) self.axIVCurve.set_position([0.05, 0.05, 0.2, 0.3]) self.axCM = self.fig.add_axes([0.94, 0.55, 0.01, 0.35]) self.fig.canvas.mpl_connect('button_press_event', self.OnClick) self.fig.canvas.mpl_connect('pick_event', self.OnPick) self.fig.canvas.mpl_connect('key_press_event', self.OnPress) self.InitMolecule() self.InitBias() self.InitTrans() self.InitOrbitals() self.InitIVCurve() self.axSC = plt.axes([0.05, 0.85, 0.15, 0.10], axisbg='white') self.cbSC = RadioButtons(self.axSC, ('Not self consistent', 'Hubbard', 'PPP')) self.cbSC.on_clicked(self.UpdateConsistency) self.axOptions1 = plt.axes([0.05, 0.7, 0.15, 0.10], axisbg='white') self.cbOptions1 = CheckButtons(self.axOptions1, ('Overlap', 'Show Local Density','Show Local Currents'), (False, False, True)) self.cbOptions1.on_clicked(self.Options1) self.axOptions2 = plt.axes([0.05, 0.5, 0.15, 0.15], axisbg='white') self.cbOptions2 = CheckButtons(self.axOptions2, ('Show Transmission', 'Show Current', 'Show DOS', 'Show Orbitals', 'Show Phase'), (True, True, False, False, False)) self.cbOptions2.on_clicked(self.Options2) c = ['seagreen', 'b', 'darkorange', 'lightsteelblue', 'm'] [rec.set_facecolor(c[i]) for i, rec in enumerate(self.cbOptions2.rectangles)] self.axGleft = plt.axes([0.05, 0.43, 0.15, 0.02], axisbg='white') self.axGright = plt.axes([0.05, 0.40, 0.15, 0.02], axisbg='white') self.sGleft = Slider(self.axGleft, 'Gl', 0.0, 1.0, valinit = gLeft) self.sGright = Slider(self.axGright, 'Gr', 0.0, 1.0, valinit = gRight) self.sGleft.on_changed(self.UpdateG) self.sGright.on_changed(self.UpdateG) self.axSave = plt.axes([0.92, 0.95, 0.07, 0.04]) self.bSave = Button(self.axSave, 'Save') self.bSave.on_clicked(self.Save) def OnPick(self, event): if isinstance(event.artist, Rectangle): self.OnPickOrbital(event) else: self.OnPickMolecule(event) def OnClick (self, event): if event.inaxes==self.axMol: if event.button==1: self.OnClickMolecule (event) elif event.button==3: self.OnClickBias (event) elif event.inaxes==self.axOrb: if event.button==1: return if event.button==3: self.OnClickTrans (event) return def Save(self, event): self.Mol.Save() def Options1(self, label): if label == 'Overlap': self.Mol.SetOverlap(self.cbOptions1.lines[0][0].get_visible()) self.UpdateMolecule() elif label == 'Show Local Density': self.DrawLocalDensity(self.cbOptions1.lines[1][0].get_visible()) elif label == 'Show Local Currents': self.DrawLocalCurrents(self.cbOptions1.lines[2][0].get_visible()) return def Options2(self, label): if label == 'Show Transmission': self.DrawTransmission() elif label == 'Show Current': self.DrawCurrent() elif label == 'Show DOS': self.DrawDOS() elif label == 'Show Orbitals': self.DrawOrbitals() self.DrawSelOrbitals() elif label == 'Show Phase': self.DrawTransmission() self.DrawSelTransmission() return def SetMolecule(self, Molecule): self.Mol = Molecule self.UpdateMolecule() def UpdateMolecule (self): self.Mol.CreateHam() self.Mol.CreateOverlap() self.Mol.CreateV() self.ChangeMolecule () self.ChangeMoleculeOrbitals () self.DrawMolecule () return self.UpdateHamExt () def UpdateConsistency(self, label): self.Consistency = label print "Consistency set to:", self.Consistency return self.UpdateHamExt () def UpdateG (self, val): print "Interaction strengths set to:", self.sGleft.val, self.sGright.val self.Mol.SetG (self.sGleft.val, self.sGright.val) return self.UpdateHamExt () def UpdateBias(self, bias): self.Bias = bias print "Bias voltage set to: ", self.Bias, "V" return self.UpdateHamExt () def UpdateHamExt (self): self.Mol.CreateHamExt (self.Bias, self.Consistency) self.Mol.CalcGamma() self.Mol.Density(self.Bias) self.Mol.Transmission() self.Mol.Current(self.Bias) self.Mol.CalcDOS() self.DrawLocalDensity () self.DrawBias () self.DrawTransmission () self.DrawDOS () self.DrawCurrent () self.DrawOrbitals () return self.UpdateSelection() def UpdateGate (self, gate): self.Gate = gate print "Gates voltage set to: ", self.Gate, "V" self.OrbitalSel = None self.AtomSel = None return self.UpdateSelection() def UpdateAtomSel(self, iAtom): self.AtomSel = iAtom if self.AtomSel == None: print "No atom selected" self.axMol.set_title('No atom selected') self.OrbitalSel = None elif isinstance(iAtom, int): print "Selected atom", self.Mol.Atom[self.AtomSel][0], "at", self.AtomSel, " Local density = ", self.Mol.LD[self.AtomSel, self.AtomSel] self.axMol.set_title('Selected atom: %c at %d. Density = %f'%(self.Mol.Atom[self.AtomSel][0],self.AtomSel, self.Mol.LD[self.AtomSel, self.AtomSel])) Orbitals = [] for i in range(self.Mol.N): Orbitals.append(np.real(self.Mol.eigvec[i][self.AtomSel]*np.conjugate(self.Mol.eigvec[i][self.AtomSel]))) self.OrbitalSel = Orbitals return self.UpdateSelection() def UpdateOrbitalSel(self, iOrbital): self.OrbitalSel = iOrbital if isinstance(self.OrbitalSel, int): print "Orbital set to:", self.OrbitalSel, "with energy", self.Mol.e_arr[self.OrbitalSel], "eV" self.AtomSel = self.Mol.eigvec[iOrbital] self.Gate = self.Mol.e_arr[self.OrbitalSel] return self.UpdateSelection() def UpdateSelection (self): self.DrawLocalCurrents () self.DrawGate() self.DrawIVCurve() self.DrawSelAtom() self.DrawSelOrbitals() self.DrawSelTransmission() return def RunSequence (self): self.fig.set_size_inches(18.5, 13.5) #default 18.5, 10.5 N=100 for i in range(N): e = self.Mol.Gates[0]+(self.Mol.Gates[-1]-self.Mol.Gates[0])/N*i self.UpdateGate(e) self.fig.savefig('Output/PN/Armchair 7,21, seq ' + str(i) + ' Energy=' + str(math.ceil(e*100)/100) + 'eV.png', dpi=self.fig.dpi) print e
# Get best piecewise fit popt, pcov = optimize.curve_fit(piecewise_2, x_axis, y_axis) # calculate y-values using fit function y_axis_new = piecewise_2(model_x, *popt) # Reset best fit line data points fit.set_ydata(y_axis_new) # Plot lower boundary for outliers lb.set_ydata(y_axis_new - slider1.val * mean(y_axis_new)) # Plot upper boundary for outliers ub.set_ydata(y_axis_new + slider1.val * mean(y_axis_new)) # Display equation as the plot title fig.suptitle(popt) # redraw canvas while idle fig.canvas.draw() fig.canvas.flush_events() butRadio.on_clicked(update) slider1.on_changed(update) #show plot # [left, bottom, right, top] plt.tight_layout(rect=[0, 0.25, 1, 0.95]) plt.show() #%%
slider_I = MySlider( plt.axes([0.03, 0.65, 0.22, 0.03]), "I", MIN_I, MAX_I, valinit=0, valfmt="%1.2f", dragging=slider_drag ) slider_I.on_changed(callback_slider_I) slider_D = MySlider( plt.axes([0.03, 0.6, 0.22, 0.03]), "D", MIN_D, MAX_D, valinit=0, valfmt="%1.3f", dragging=slider_drag ) slider_D.on_changed(callback_slider_D) # RADIO BUTTON radio_mode = RadioButtons( plt.axes([0.13, 0.3, 0.12, 0.28]), ("HOLO X", "HOLO Y", "HOLO R", "R Motor", "L Motor", "T Motor", "DD V", "DD R") ) radio_mode.on_clicked(callback_radio_mode) ####################################################### # MAIN ####################################################### def main(): global device global reading # while this is true, thread_read is still alive global continue_reading # If this is true, then the thread_read thread will not exit # begin setup hamr serial connection reading = False device = hamr_serial.initialize(PORT, BAUDRATE, timeout_=0.3, write_timeout_=0.3) # begin joystick thread thread_joystick = threading.Thread(target=read_joystick)
def select_gpu(default_platform=None, defualt_device=None): if default_platform is None: default_platform =opencl_tools.openc_platform_index if defualt_device is None: defualt_device = opencl_tools.openc_device_index figure = plt.figure() figure_number = figure.number selected_options = {'platform' : default_platform, 'device' : defualt_device, 'platforms' : cl.get_platforms(), 'devices' : cl.get_platforms()[default_platform].get_devices(), 'return_values' : False } platform_names = [ "%d. %s" % (index,platform.get_info(cl.platform_info.NAME)) for index,platform in enumerate(selected_options['platforms'])] def get_device_names(): return [ "%d. %s" % (index,device.get_info(cl.device_info.NAME)) for index,device in enumerate(selected_options['devices'])] grid_size = (6,6) ax_platform_selection = plt.subplot2grid(grid_size,(0,0),rowspan=5,colspan=3) ax_device_selection = plt.subplot2grid(grid_size,(0,3),rowspan=5,colspan=3) ax_save_button = plt.subplot2grid(grid_size,(5,4),rowspan=1,colspan=1) ax_cancel_button = plt.subplot2grid(grid_size,(5,5),rowspan=1,colspan=1) ax_platform_selection.set_title("Platform:") ax_device_selection.set_title("Device:") platform_selection = RadioButtons(ax_platform_selection,platform_names,active=selected_options['platform']) device_selection =[ RadioButtons(ax_device_selection,get_device_names(),active=selected_options['device']) ] def on_platform_select(selected_name): id_of_platform = platform_names.index(selected_name) selected_options['platform'] = id_of_platform selected_options['device'] = 0 selected_options['devices'] = cl.get_platforms()[id_of_platform].get_devices() device_selection[0].disconnect_events() allobs = list(iter(device_selection[0].observers)) for obs in allobs: device_selection[0].disconnect(obs) ax_device_selection.cla(); device_selection[0] = RadioButtons(ax_device_selection,get_device_names(),active=selected_options['device']) ax_device_selection.set_title("Device:") figure.canvas.draw() platform_selection.on_clicked(on_platform_select) def on_device_select(selected_name): device_names = get_device_names() selected_options['device'] = device_names.index(selected_name) device_selection[0].on_clicked(on_device_select) save_button = Button(ax_save_button,"Save") def save_click(*args): selected_options['return_values'] = True plt.close(figure) save_button.on_clicked(save_click) cancel_button = Button(ax_cancel_button,"Cancel") def cancel_click(*args): selected_options['return_values'] = False plt.close(figure) cancel_button.on_clicked(cancel_click) plt.show(block=True) if selected_options['return_values']: return selected_options['platform'], selected_options['device'] else: return None, None
#define the box where the buttons live rax = pl.axes([bxl, 0.87, bxl + bw, 0.11], axisbg=axcolor) radio = RadioButtons(rax, ('no marker', '40', '80', '120'), active=0) def msfunc(label): global y, NFFT, Fsamp, Fcentre, foverlap, detrend, _window, _type, fmod, marker_size msdict = {'no marker': 0, '40': 40, '80': 80, '120': 120} marker_size = msdict[label] print("marker_size", marker_size) callback.redraw( ) # really should add markers here! (this is a call without getting new data) radio.on_clicked(msfunc) rax = pl.axes([bxl, 0.68, bxl + bw, 0.18], axisbg=axcolor) radio = RadioButtons(rax, ('win 128', '256', '512', '1024', '2048', '4096'), active=2) def hzfunc(label): global y, NFFT, Fsamp, Fcentre, foverlap, detrend, _window, _type, fmod hzdict = { 'win 128': 128, '256': 256, '512': 512, '1024': 1024, '2048': 2048, '4096': 4096
sl = Slider(ax_plM, 'Payload Settings', 0, 20, valinit=init_pl_mass, valstep=.1, valfmt='%1.1fkg') sl.label.set_ha('left') sl.label.set_y(1.7) # explain on stackexchange question sl.on_changed(pl_mass_update) ax_morph = plt.axes([.01, .01, .15, .15]) #plt.axes([.89,.01,.1,.05]) ax_morph.axis('off') radio_morph = RadioButtons(ax_morph, (morph_label, 'Non-morphing Drone'), active=1) radio_morph.on_clicked(morph_radio_callback) updateTextBox() prompt("Change payload mass & position, analyze flight stats, or morph") # LEGEND main_ax.legend((d.pltInfo['cg_objs'][0], d.pltInfo['drone_objs'][0], d.pltInfo['pl_objs'][1]), ('CG', 'Drone', 'Payload')) plt.show() # add a remaining maneuverability % in info box # make custom text so payload mass value is left of slider and slider is .01 from right # show payload distance limit for nonmorphed drone. If someone presses outside it, it says "drone unstable - press morph" # show drone info, like thrusts, in visual representation such as bar graph with spread shown
def set_x(val): ax.set_xscale(val) if val == 'log': ax.set_xlim(100, 10**6) else: ax.set_xlim(100, 1000) fig.canvas.draw_idle() def set_y(val): ax.set_yscale(val) fig.canvas.draw_idle() def set_norm(val): if val == "blue": normalize_to_attenuated[0] = False if val == "red": normalize_to_attenuated[0] = True update(val) fig.canvas.draw_idle() radio_x.on_clicked(set_x) radio_y.on_clicked(set_y) radio_norm.on_clicked(set_norm) ### MAIN ### plot.show()
using_doppler = True else: using_doppler = False update(prain.val) def reset(event): prain.reset() accuracy.reset() button.on_clicked(reset) rax = plt.axes([0.0, 0.7, 0.15, 0.15], facecolor=axcolor) radio = RadioButtons(rax, ('Purchase Doppler', 'No Doppler'), active=1) radio.on_clicked(doppler_function) rax2 = plt.axes([0.0, 0.5, 0.15, 0.15], facecolor=axcolor) radio2 = RadioButtons(rax2, ('Purchase Spores', 'No Spores'), active=1) radio2.on_clicked(spores_function) def utility_function(x, rho): return -math.e**(-float(x) / rho) def inverse_utility_function(u, rho): return -rho * math.log(-float(u)) def utility_neither(rain_probability,
def plot_neuron_111(self): fig, ax = plt.subplots() plt.subplots_adjust(left=0.25, bottom=0.35) plt.title('$%s[w_{21}%s(w_{11}x+w_{10})+w_{20}]$' % (self.acttype, self.acttype)) # 使用默认值绘制图像 s = self.activate111(self.w_reset, self.w_reset, self.w_reset, self.w_reset) l, = plt.plot(self.x1, s, lw=2, color='red') # x 轴范围和 y 轴范围 plt.axis([-self.x_range, self.x_range, 0, 1]) # 滑动条背景颜色 axcolor = 'white' w10_bar = plt.axes([0.25, 0.25, 0.65, 0.03], facecolor=axcolor) w11_bar = plt.axes([0.25, 0.2, 0.65, 0.03], facecolor=axcolor) w20_bar = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor) w21_bar = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor) # 绑定滑动条和 reset 数值 w10 = Slider(w10_bar, 'w10', -self.w_range, self.w_range, valinit=self.w_reset) w11 = Slider(w11_bar, 'w11', -self.w_range, self.w_range, valinit=self.w_reset) w20 = Slider(w20_bar, 'w20', -self.w_range, self.w_range, valinit=self.w_reset) w21 = Slider(w21_bar, 'w21', -self.w_range, self.w_range, valinit=self.w_reset) # 滑动时调用函数 def update(val): # 获取更新数据 l.set_ydata(self.activate111(w11.val, w10.val, w21.val, w20.val)) fig.canvas.draw_idle() # 滑动时调用更新函数 w10.on_changed(update) w11.on_changed(update) w20.on_changed(update) w21.on_changed(update) # reset 按钮 resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') # 绑定 reset 函数 def reset(event): w10.reset() w11.reset() w20.reset() w21.reset() button.on_clicked(reset) rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor) radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) # 更新颜色 def colorfunc(label): l.set_color(label) fig.canvas.draw_idle() radio.on_clicked(colorfunc) plt.show()
class ParametricEQSelector: def __init__(self): self._fs = 48000 self._nbands = 7 self._params = [] for i in range(0, self._nbands): self._params.append({'center': 0, 'resonance': 1.0/math.sqrt(2.0), 'dbgain': 0}) self._selected_band = 0 self._blocksize = 512 self._nfft = int(self._blocksize / 2) self._impulse_response = [0] * self._blocksize self._freq_response_real = [0] * self._blocksize self._freq_response_imag = [0] * self._blocksize self._response = [0] * self._blocksize self._plot_db = True self._eq = yodel.filter.ParametricEQ(self._fs, self._nbands) self._create_plot() self._create_plot_controls() self.select_band('Band ' + str(self._selected_band+1)) def _create_plot(self): self._fig, self._ax = plt.subplots() self._ax.set_title('Parametric Equalizer Design') self._ax.grid() plt.subplots_adjust(bottom=0.3) self._update_filter_response() self._x_axis = [i*(self._fs/2/self._nfft) for i in range(0, self._nfft)] self._y_axis = self._response[0:self._nfft] self._l_center, = self._ax.plot(self._x_axis, [0] * self._nfft, 'k') self._l_fr, = self._ax.plot(self._x_axis, self._y_axis, 'b') self._rescale_plot() def _create_plot_controls(self): self._dbrax = plt.axes([0.12, 0.05, 0.13, 0.10]) self._dbradio = RadioButtons(self._dbrax, ('Amplitude', 'Phase')) self._dbradio.on_clicked(self.set_plot_style) self._rax = plt.axes([0.27, 0.03, 0.15, 0.20]) bands_list = [] for i in range(1, self._nbands+1): bands_list.append('Band ' + str(i)) self._radio = RadioButtons(self._rax, tuple(bands_list)) self._radio.on_clicked(self.select_band) self._sfax = plt.axes([0.6, 0.19, 0.2, 0.03]) self._sqax = plt.axes([0.6, 0.12, 0.2, 0.03]) self._sdbax = plt.axes([0.6, 0.05, 0.2, 0.03]) self._fcslider = Slider(self._sfax, 'Cut-off frequency', 0, self._fs/2, valinit = self._params[self._selected_band]['center']) self._qslider = Slider(self._sqax, 'Q factor', 0.01, 10.0, valinit = self._params[self._selected_band]['resonance']) self._dbslider = Slider(self._sdbax, 'dB gain', -20.0, 20.0, valinit = self._params[self._selected_band]['dbgain']) self._fcslider.on_changed(self.set_center_frequency) self._qslider.on_changed(self.set_resonance) self._dbslider.on_changed(self.set_dbgain) def _rescale_plot(self): if self._plot_db: self._ax.set_ylim(-30, 30) else: self._ax.set_ylim(- 200, 200) plt.draw() def _plot_frequency_response(self, redraw=True): self._update_filter_response() self._y_axis = self._response[0:self._nfft] self._l_fr.set_ydata(self._y_axis) if redraw: plt.draw() def _plot_range_limits(self, redraw=True): self._l_center.set_ydata([0] * self._nfft) if redraw: plt.draw() def set_plot_style(self, style): if style == 'Phase': self._plot_db = False elif style == 'Amplitude': self._plot_db = True self._plot_range_limits(False) self._plot_frequency_response(False) self._rescale_plot() def select_band(self, band): idx = band.split(' ') self._selected_band = int(idx[1]) - 1 self._fcslider.set_val(self._params[self._selected_band]['center']) self._qslider.set_val(self._params[self._selected_band]['resonance']) self._dbslider.set_val(self._params[self._selected_band]['dbgain']) def set_center_frequency(self, val): self._params[self._selected_band]['center'] = val self._set_band(self._selected_band) self._plot_frequency_response() def set_resonance(self, val): self._params[self._selected_band]['resonance'] = val self._set_band(self._selected_band) self._plot_frequency_response() def set_dbgain(self, val): self._params[self._selected_band]['dbgain'] = val self._set_band(self._selected_band) self._plot_frequency_response() def _set_band(self, band): center = self._params[band]['center'] resonance = self._params[band]['resonance'] dbgain = self._params[band]['dbgain'] self._eq.set_band(band, center, resonance, dbgain) def _update_filter_response(self): self._impulse_response = impulse_response(self._eq, self._blocksize) self._freq_response_real, self._freq_response_imag = frequency_response(self._impulse_response) if self._plot_db: self._response = amplitude_response(self._freq_response_real, self._freq_response_imag) else: self._response = phase_response(self._freq_response_real, self._freq_response_imag)
freq_slider.on_changed(sliders_on_changed) # Add a button for resetting the parameters reset_button_ax = fig.add_axes([0.8, 0.025, 0.1, 0.04]) reset_button = Button(reset_button_ax, 'Reset', color=axis_color, hovercolor='0.975') def reset_button_on_clicked(mouse_event): freq_slider.reset() amp_slider.reset() reset_button.on_clicked(reset_button_on_clicked) # Add a set of radio buttons for changing color color_radios_ax = fig.add_axes([0.025, 0.5, 0.15, 0.15]) color_radios = RadioButtons(color_radios_ax, ('red', 'blue', 'green'), active=0) def color_radios_on_clicked(label): line.set_color(label) fig.canvas.draw_idle() color_radios.on_clicked(color_radios_on_clicked) plt.show()
def render(self): _, self.axes = self.plot.subplots() self.plot.subplots_adjust(left=0.15, bottom=0.30) self.plot.title('Gold per Time') self.line_blue, = self.axes.plot(self.times, self._blue, color='b') self.line_green, = self.axes.plot(self.times, self._green, color='g') self.line_yellow, = self.axes.plot(self.times, self._yellow, color='y') self.axes.legend(["Spellthief's Edge", 'Relic Shield', 'Ancient Coin'], loc='upper left') self.plot.xlabel('Time') ticks = range(0, self.times[-1] + 1, 60 * 5) self.plot.xticks(self.times, ['{}m'.format(t // 60) for t in ticks]) self.axes.set_xticks(ticks) self.axes.set_xticks(range(0, self.times[-1] + 1, 60), minor=True) self.plot.ylabel('Gold') self.axes.set_ylim(0) self.axes.grid(which='minor', alpha=0.3) self.axes.grid(which='major', alpha=0.6) # ADC Farm Rate Slider adc_fr_axis = self.plot.axes([0.25, 0.19, 0.65, 0.03]) slider_adc_farm_rate = self.plot.Slider(adc_fr_axis, 'ADC Farm Rate', 0.0, 1.0, valinit=self._adc_farm_rate) slider_adc_farm_rate.on_changed(self.update_adc_farm_rate) # Support Farm Rate Slider support_fr_axis = self.plot.axes([0.25, 0.14, 0.65, 0.03]) slider_support_farm_rate = self.plot.Slider( support_fr_axis, 'Support Farm Rate', 0.0, 1.0, valinit=self._support_farm_rate) slider_support_farm_rate.on_changed(self.update_support_farm_rate) # Support Poke Rate Slider support_pr_axis = self.plot.axes([0.25, 0.09, 0.65, 0.03]) slider_support_poke_rate = self.plot.Slider( support_pr_axis, 'Support Poke Rate', 0.0, 1.0, valinit=self._support_poke_rate) slider_support_poke_rate.on_changed(self.update_support_poke_rate) # Support Upgrade Item Lag Slider supp_uil_slider = self.plot.axes([0.25, 0.04, 0.65, 0.03]) slider_support_upgrade_item_lag = self.plot.Slider( supp_uil_slider, 'Upgrade Item Lag', 0, 1000, valinit=self._support_item_lag) slider_support_upgrade_item_lag.on_changed( self.update_support_item_lag) # Support Ranged Toggle from matplotlib.widgets import RadioButtons support_r_axis = self.plot.axes([0.725, 0.325, 0.15, 0.15]) buttom_support_ranged_toggle = RadioButtons( support_r_axis, ('Melee', 'Ranged'), active=int(self._ranged_support)) buttom_support_ranged_toggle.on_clicked(self.update_ranged_support) self.plot.savefig('gold-items-support.png') self.plot.show()
def drawffnet(net, biases = False): """ Takes a ffnet class instance and draws the network. Networkx layouts and maplotlib buttons are used to control layout. Note: This is very draft solution and it may not work for you. """ #Takes copies of network graphs G = net.graph.copy() if not biases: try: G.delete_node(0) except: G.remove_node(0) BG = net.bgraph.copy() ax = subplot(111) subplots_adjust(left=0.25) setp(ax, xticks=[], yticks=[]) try: layout = NX.graphviz_layout(G, prog='dot') active = 0 except: layout = NX.circular_layout(G) active = 5 NX.draw_networkx(G, layout) # Make radio buttons for layouts axcolor = 'lightgoldenrodyellow' rax = axes([0.025, 0.4, 0.18, 0.35], axisbg=axcolor) setp(rax, xticks=[], yticks=[]) text(0., 1., "Network layouts") radio_layout = RadioButtons(rax, \ ('dot', 'neato', 'fdp', 'twopi', 'circo', \ 'circular', 'random', 'spring', 'shell'), \ active=active) radio_layout.layout = layout def layoutfunc(label): ax.clear() setp(ax, xticks=[], yticks=[]) try: if label == 'dot': layout = NX.graphviz_layout(G, prog='dot') if label == 'neato': layout = NX.graphviz_layout(G, prog='neato') if label == 'fdp': layout = NX.graphviz_layout(G, prog='fdp') if label == 'twopi': layout = NX.graphviz_layout(G, prog='twopi') if label == 'circo': layout = NX.graphviz_layout(G, prog='circo') if label == 'circular': layout = NX.circular_layout(G) if label == 'random': layout = NX.random_layout(G) if label == 'spring': layout = NX.spring_layout(G, iterations=15) # if label == 'spectral': layout = NX.spectral_layout(G, iterations=50) if label == 'shell': layout = NX.shell_layout(G) radio_layout.layout = layout NX.draw_networkx(G, layout) draw() except: setp(ax, xlim = (0,1), ylim = (0,1)) text(0.5, 0.5, "Layout is not avilable.\n(Not working graphviz?) \n (Not installed pygraphviz?)", \ fontsize=14, color='r', horizontalalignment='center') radio_layout.on_clicked(layoutfunc) # Make a button for showing adjoint network (backpropagation network) bgraphax = axes([0.025, 0.3, 0.18, 0.04]) button1 = Button(bgraphax, 'Backprop graph', color=axcolor, hovercolor='0.975') def showbgraph(event): ax.clear() setp(ax, xticks=[], yticks=[]) layout = radio_layout.layout NX.draw_networkx(G, layout, alpha=0.1, labels={}) NX.draw_networkx(BG, layout, node_color='y') draw() button1.on_clicked(showbgraph) # Make a button for showing derivative networks dgraphax = axes([0.025, 0.2, 0.18, 0.04]) button2 = Button(dgraphax, 'Diff graphs', color=axcolor, hovercolor='0.975') def showdgraphs(event): def dsubgraph_nodes(inp, out, nbunch): pred = NX.predecessor(G, inp, out) nbunch += pred for node in pred: dsubgraph_nodes(inp, node, nbunch) return nbunch layout = radio_layout.layout import time for innode in net.inno: for outnode in net.outno: nbunch = [outnode] nbunch = dsubgraph_nodes(innode, outnode, nbunch) g = G.subgraph(nbunch) ax.clear() setp(ax, xticks=[], yticks=[]) NX.draw_networkx(G, layout, alpha=0.1, labels={}) NX.draw_networkx(g, layout, node_color='c') draw() time.sleep(3) button2.on_clicked(showdgraphs) axes()
except (TypeError, ValueError) as ex: print('Invalid value: {} !'.format(text)) else: factor = 0. print('selection factor: {}'.format(factor)) ax_button = plt.axes([0.81, 0.05, 0.1, 0.075]) adjust_button = Button(ax_button, 'Adjust') adjust_button.on_clicked(adjust_callback) ax_checkbox = plt.axes([0.7, 0.025, 0.15, 0.125], frameon=False) autoadjust_checkbox = CheckButtons(ax_checkbox, ['auto'], [True]) autoadjust_checkbox.on_clicked(autoadjust_callback) ax_selection = plt.axes([0.05, 0.025, 0.2, 0.125], frameon=False) stim_selection = RadioButtons(ax_selection, ['on', 'off']) stim_selection.on_clicked(selection_callback) ax_stim_value = plt.axes([0.26, 0.05, 0.1, 0.075]) stim_value = TextBox(ax_stim_value, 'VC (mV):', '-10') stim_value.on_submit(value_callback) def update(i): I = amplifier.acquire('I', V=Vc * factor) ## Calculate offset and resistance if abs(factor) > 0: I0 = median(I[:int(T0 / dt)]) # calculated on initial pause Ipeak = median( I[int((T0 + 2 * T1 / 3.) / dt):int((T0 + T1) / dt)]) # calculated on last third of the pulse R = V0 / (Ipeak - I0)
def display(self): """Method to create the plotting window and fill it with buttons.""" # Create matplotlib window dressing self.fig = plt.figure(figsize=(11, 9), facecolor='lightgoldenrodyellow') #self.fig = plt.figure(facecolor='lightgoldenrodyellow') self.fig.canvas.set_window_title('PyPop: Visualization') self.fig.clear() # put some buttons on the figure for the plot axes buttonW = 0.055 buttonH = 0.045 # default button sizes # arguments are button left, bottom, width, height and label # check box to do log scale buttonXLog = CheckButtons(plt.axes( [0.001, .3, 1.5 * buttonW, 1.5 * buttonH]), ['log x'], actives=[False]) self.xlog = False buttonYLog = CheckButtons(plt.axes( [0.001 + 2.5 * buttonW, .3, 1.5 * buttonW, 1.5 * buttonH]), ['log y'], actives=[False]) self.ylog = False # button to do plot buttonPlot = Button( plt.axes([0.001 + 2.0 * buttonW, 0.2, 1.5 * buttonW, buttonH]), 'Plot') self.fig.text(0.003, 0.98, 'PLOT SELECTION') self.fig.text(0.003, 0.95, 'X Axis') self.fig.text(0.003, 0.65, 'Y Axis') # radio buttons for x and y axis values radioXAxis = RadioButtons(plt.axes([ 0.001, 0.72, len(self.textlabels) * 0.02, len(self.textlabels) * 0.02 ]), self.textlabels, active=0, activecolor='blue') self.xindex = 0 radioYAxis = RadioButtons(plt.axes([ 0.001, 0.42, len(self.textlabels) * 0.02, len(self.textlabels) * 0.02 ]), self.textlabels, active=1, activecolor='blue') self.yindex = 1 # if radio button is clicked, change active X/Y index radioXAxis.on_clicked(self._radioXClick) radioYAxis.on_clicked(self._radioYClick) # add callback to the plot button(s?) buttonPlot.on_clicked(self._scatterplot) # callbacks for the log plot switches buttonXLog.on_clicked(self._logClick) buttonYLog.on_clicked(self._logClick) plt.show()
# Create axes for holding the radio selectors. # supply [left, bottom, width, height] in normalized (0, 1) units bax = plt.axes([0.3, 0.9, 0.4, 0.1]) radio = RadioButtons(bax, ('Weekly earnings', 'Unemployment rate')) # Define the function for updating the displayed values # when the radio button is clicked def radiofunc(label): # Select columns from dataframe depending on label if label == 'Weekly earnings': data = df["Median usual weekly earnings ($)"] ax.set_xlabel('Median weekly earnings (USD)') elif label == 'Unemployment rate': data = df["Unemployment rate (%)"] ax.set_xlabel('Unemployment rate (%)') # Update the bar heights for i, rect in enumerate(rects): rect.set_width(data[i]) # Rescale the x-axis range ax.set_xlim(xmin=0, xmax=data.max() * 1.1) # Redraw the figure plt.draw() radio.on_clicked(radiofunc) plt.show()
def GUI_plot(RMS, subjects_dir, subject): # subjects_dir = '/hpc/comco/basanisi.r/Databases/db_mne/meg_te/' # subject = 'subject_04' # RMS = np.array(([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], # [5, 4, 3, 2, 1, 10, 9, 8, 7, 6], # [6, 7, 8, 9, 10, 1, 2, 3, 4, 5]), dtype=float) bad_channels = [] bad_trials = [] tot_trials = RMS.shape[0] tot_channels = RMS.shape[1] channels_average = ((np.sum(RMS, axis=1)) / (tot_channels)) * 10**14 trials_average = ((np.sum(RMS, axis=0)) / (tot_trials)) * 10**14 channels_dev_std = np.std(RMS, axis=1) * 10**14 trials_dev_std = np.std(RMS, axis=0) * 10**14 RMS_zscore = zscore(RMS) ch_av_zscore = ((np.sum(RMS_zscore, axis=1)) / (tot_channels)) * 10**14 tr_av_zscore = ((np.sum(RMS_zscore, axis=0)) / (tot_trials)) * 10**14 plt.close('all') fig = plt.figure() ax1 = plt.subplot2grid((4, 6), (2, 0), colspan=4, rowspan=3) ax1.set_title('RMS') ax1.set_xlabel('Channels') ax1.set_ylabel('Trials') ax2 = plt.subplot2grid((4, 6), (0, 1), colspan=3, rowspan=2) ax2.set_title('Average RMS for Trial') ax2.set_xlabel('Trials') ax2.set_ylabel('Channels RMS Average *10^14') ax2.set_xlim([-1, tot_trials]) ax3 = plt.subplot2grid((4, 6), (0, 4), colspan=2, rowspan=4) ax3.set_title('Average of Trials for Channel') ax3.set_xlabel('Channels Average in Trials *10^14') ax3.set_ylabel('Channels') ax3.set_ylim([-1, tot_channels]) ax4 = plt.subplot2grid((4, 6), (0, 0)) line1 = ax1.imshow(RMS, interpolation='none', aspect='auto') line2, = ax2.plot(range(tot_trials), channels_average, 'o', picker=5) line3, = ax3.plot(trials_average, range(tot_channels), 'o', picker=5) button = RadioButtons(ax4, ('Average', 'Dev Std', 'Z Score')) plt.colorbar(line1, ax=ax1) plt.tight_layout() def FuncType(label): FuncDict = { 'Average': (channels_average, trials_average), 'Dev Std': (channels_dev_std, trials_dev_std), 'Z Score': (ch_av_zscore, tr_av_zscore) } ydata = FuncDict[label] line2.set_ydata(ydata[0]) line3.set_xdata(ydata[1]) if label == 'Average': ax2.set_title('Average RMS for Trial') ax2.set_ylabel('Channels RMS Average *10^14') ax2.set_ylim( [channels_average.min() - 1, channels_average.max() + 1]) ax3.set_title('Average of Trials for Channel') ax3.set_xlabel('Channels Average in Trials *10^14') ax3.set_xlim([trials_average.min() - 1, trials_average.max() + 1]) elif label == 'Dev Std': ax2.set_title('Dev. Std. for Trial') ax2.set_ylabel('Channels Dev. Std. *10^14') ax2.set_ylim( [channels_dev_std.min() - 1, channels_dev_std.max() + 1]) ax3.set_title('Dev. Std. of Trials for Channel') ax3.set_xlabel('Channels Dev. Std. in Trials *10^14') ax3.set_xlim([trials_dev_std.min() - 1, trials_dev_std.max() + 1]) elif label == 'Z Score': ax2.set_title('Average Z-score RMS for Trial') ax2.set_ylabel('Channels Average Z-score *10^14') ax2.set_ylim([ch_av_zscore.min() - 1, ch_av_zscore.max() + 1]) ax3.set_title('Average Z-score of Trials for Channel') ax3.set_xlabel('Channels Average Z-score in Trials *10^14') ax3.set_xlim([tr_av_zscore.min() - 1, tr_av_zscore.max() + 1]) plt.draw() button.on_clicked(FuncType) def onpick(event): if ics == 1: thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind if xdata[ind] in bad_trials: bad_trials.remove(xdata[ind]) print 'Trial', xdata[ ind], 'removed from rejection list, correspondent value: ', ydata[ ind] thisline.set_color('b') else: bad_trials.append(xdata[ind]) print 'Trial', xdata[ ind], 'added to rejection list, correspondent value: ', ydata[ ind] # thisline._edgecolors[event.ind, :] = (1, 0, 0, 1) elif ics == 2: thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind if ydata[ind] in bad_channels: bad_channels.remove(ydata[ind]) print 'Channel', ydata[ ind], 'removed from rejection list, correspondent value: ', xdata[ ind] thisline.set_color('b') else: bad_channels.append(ydata[ind]) print 'Channel', ydata[ ind], 'added to rejection list, correspondent value: ', xdata[ ind] thisline.set_color('r') # print('onpick points:', points) else: return def sub_click(event_check): global ics if event_check.inaxes in [ax2]: ics = 1 elif event_check.inaxes in [ax3]: ics = 2 else: return fig.canvas.mpl_connect('pick_event', onpick) fig.canvas.mpl_connect('button_press_event', sub_click) plt.show() channels_ar = open(subjects_dir + '{0}/channels_ar.txt'.format(subject), 'w') for car in bad_channels: channels_ar.write("%s \n" % car) channels_ar.close() trials_ar = open(subjects_dir + '{0}/trials_ar.txt'.format(subject), 'w') for tar in bad_trials: trials_ar.write("%s \n" % tar) trials_ar.close() if len(bad_trials) == 0 and len(bad_channels) == 0: artifact_rejection = (None, None) elif len(bad_trials) == 0: artifact_rejection = (np.concatenate(bad_channels), None) elif len(bad_channels) == 0: artifact_rejection = (None, np.concatenate(bad_trials)) else: artifact_rejection = (np.concatenate( (bad_channels)), np.concatenate((bad_trials))) return artifact_rejection
lyingSecondPoint = find_second_point_on_line(x1, y1, roundVal + SIDE_LENGTH) lyingSupportRib = [lyingFirstPoint, lyingSecondPoint] rotateAngle = ANGULAR_SCALE * (val - roundVal) rotateVertex = find_rotated_vertex(lyingSupportRib, SIDE_LENGTH, rotateAngle, up) supportRib = [ rotateVertex, find_second_point_on_line(x1, y1, roundVal + SIDE_LENGTH) ] draw_cyclogon(calc_vertex_coord(supportRib, VERTEX_NUM, EXTERIOR_ANGLE)) fig.canvas.draw_idle() # SET CALLBACK radius_slider.on_changed(slider_on_changed) def vertex_radios_on_clicked(num): radius_slider.set_val(0) fig.canvas.draw_idle() # SET CALLBACK vertex_radios.on_clicked(vertex_radios_on_clicked) plt.show()
bxl=0.02 bw=0.12 # width (for most) axcolor = 'lightgoldenrodyellow' #define the box where the buttons live rax = pl.axes([bxl, 0.87, bxl+bw, 0.11], axisbg=axcolor) radio = RadioButtons(rax, ('no marker', '40', '80', '120'),active=0) def msfunc(label): global y,NFFT,Fsamp,Fcentre,foverlap,detrend,_window, _type, fmod, marker_size msdict = {'no marker':0, '40':40, '80':80, '120':120} marker_size = msdict[label] print("marker_size", marker_size) callback.redraw() # really should add markers here! (this is a call without getting new data) radio.on_clicked(msfunc) rax = pl.axes([bxl, 0.68, bxl+bw, 0.18], axisbg=axcolor) radio = RadioButtons(rax, ('win 128', '256', '512', '1024','2048','4096'),active=2) def hzfunc(label): global y,NFFT,Fsamp,Fcentre,foverlap,detrend,_window, _type, fmod hzdict = {'win 128':128, '256':256, '512':512, '1024':1024, '2048':2048, '4096':4096} NFFT = hzdict[label] call_spec() radio.on_clicked(hzfunc) rax = pl.axes([bxl, 0.48, bxl+bw, 0.19], axisbg=axcolor)
class AlignmentInterface(BaseReviewInterface): """Custom interface for rating the quality of alignment between two 3d MR images""" def __init__(self, fig, rating_list=cfg.default_rating_list, next_button_callback=None, quit_button_callback=None, change_vis_type_callback=None, toggle_animation_callback=None, show_first_image_callback=None, show_second_image_callback=None, alpha_seg=cfg.default_alpha_seg): """Constructor""" super().__init__(fig, None, next_button_callback, quit_button_callback) self.rating_list = rating_list self.latest_alpha_seg = alpha_seg self.prev_axis = None self.prev_ax_pos = None self.zoomed_in = False self.next_button_callback = next_button_callback self.quit_button_callback = quit_button_callback self.change_vis_type_callback = change_vis_type_callback self.toggle_animation_callback = toggle_animation_callback self.show_first_image_callback = show_first_image_callback self.show_second_image_callback = show_second_image_callback self.add_radio_buttons_rating() self.add_radio_buttons_comparison_method() # this list of artists to be populated later # makes to handy to clean them all self.data_handles = list() self.unzoomable_axes = [ self.radio_bt_rating.ax, self.radio_bt_vis_type.ax, self.text_box.ax, self.bt_next.ax, self.bt_quit.ax, ] def add_radio_buttons_comparison_method(self): ax_radio = plt.axes(cfg.position_alignment_radio_button_method, facecolor=cfg.color_rating_axis, aspect='equal') self.radio_bt_vis_type = RadioButtons(ax_radio, cfg.choices_alignment_comparison, active=None, activecolor='orange') self.radio_bt_vis_type.on_clicked(self.change_vis_type_callback) for txt_lbl in self.radio_bt_vis_type.labels: txt_lbl.set(color=cfg.text_option_color, fontweight='normal') for circ in self.radio_bt_vis_type.circles: circ.set(radius=0.06) def add_radio_buttons_rating(self): ax_radio = plt.axes(cfg.position_alignment_radio_button_rating, facecolor=cfg.color_rating_axis, aspect='equal') self.radio_bt_rating = RadioButtons(ax_radio, self.rating_list, active=None, activecolor='orange') self.radio_bt_rating.on_clicked(self.save_rating) for txt_lbl in self.radio_bt_rating.labels: txt_lbl.set(color=cfg.text_option_color, fontweight='normal') for circ in self.radio_bt_rating.circles: circ.set(radius=0.06) def save_rating(self, label): """Update the rating""" # print(' rating {}'.format(label)) self.user_rating = label def get_ratings(self): """Returns the final set of checked ratings""" return self.user_rating def allowed_to_advance(self): """ Method to ensure work is done for current iteration, before allowing the user to advance to next subject. Returns False if atleast one of the following conditions are not met: Atleast Checkbox is checked """ return self.radio_bt_rating.value_selected is not None def reset_figure(self): "Resets the figure to prepare it for display of next subject." self.clear_data() self.clear_radio_buttons() self.clear_notes_annot() def clear_data(self): """clearing all data/image handles""" if self.data_handles: for artist in self.data_handles: artist.remove() # resetting it self.data_handles = list() def clear_radio_buttons(self): """Clears the radio button""" # enabling default rating encourages lazy advancing without review # self.radio_bt_rating.set_active(cfg.index_freesurfer_default_rating) for index, label in enumerate(self.radio_bt_rating.labels): if label.get_text() == self.radio_bt_rating.value_selected: self.radio_bt_rating.circles[index].set_facecolor( cfg.color_rating_axis) break self.radio_bt_rating.value_selected = None def clear_notes_annot(self): """clearing notes and annotations""" self.text_box.set_val(cfg.textbox_initial_text) # text is matplotlib artist self.annot_text.remove() def on_mouse(self, event): """Callback for mouse events.""" if self.prev_axis is not None: # include all the non-data axes here (so they wont be zoomed-in) if event.inaxes not in self.unzoomable_axes: self.prev_axis.set_position(self.prev_ax_pos) self.prev_axis.set_zorder(0) self.prev_axis.patch.set_alpha(0.5) self.zoomed_in = False # right click undefined if event.button in [3]: pass # double click to zoom in to any axis elif event.dblclick and event.inaxes is not None and \ event.inaxes not in self.unzoomable_axes: # zoom axes full-screen self.prev_ax_pos = event.inaxes.get_position() event.inaxes.set_position(cfg.zoomed_position) event.inaxes.set_zorder(1) # bring forth event.inaxes.set_facecolor('black') # black event.inaxes.patch.set_alpha(1.0) # opaque self.zoomed_in = True self.prev_axis = event.inaxes else: pass plt.draw() def on_keyboard(self, key_in): """Callback to handle keyboard shortcuts to rate and advance.""" # ignore keyboard key_in when mouse within Notes textbox if key_in.inaxes == self.text_box.ax or key_in.key is None: return key_pressed = key_in.key.lower() # print(key_pressed) if key_pressed in [ 'right', ]: self.next_button_callback() elif key_pressed in ['ctrl+q', 'q+ctrl']: self.quit_button_callback() elif key_pressed in [' ', 'space']: self.toggle_animation_callback() elif key_pressed in ['alt+1', '1+alt']: self.show_first_image_callback() elif key_pressed in ['alt+2', '2+alt']: self.show_second_image_callback() else: if key_pressed in cfg.default_rating_list_shortform: self.user_rating = cfg.map_short_rating[key_pressed] index_to_set = cfg.default_rating_list.index(self.user_rating) self.radio_bt_rating.set_active(index_to_set) else: pass plt.draw()
freq = sfreq.val l.set_ydata(amp * np.sin(2 * np.pi * freq * t)) fig.canvas.draw_idle() sfreq.on_changed(update) samp.on_changed(update) resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') def reset(event): sfreq.reset() samp.reset() button.on_clicked(reset) rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) def colorfunc(label): l.set_color(label) fig.canvas.draw_idle() radio.on_clicked(colorfunc) plt.show()
experimental, = ax.plot(xExperimental, yExperimental) #Displaying the difference between the two equations. xDifference = np.linspace(a, b, n) yDifference = [] for i in range(len(xControl)): yDifference.append(abs(yExperimental[i] - yControl[i])) difference, = ax.plot(xDifference, yDifference) ax.legend([control, experimental, difference], ['Control', 'Experimental', 'Difference']) euler() susceptibleGraph() axcolor = 'white' axSize = plt.axes([0.20, 0.1, 0.65, 0.03], axisbg=axcolor) xSize = Slider(axSize, 'Rate Increasing', 0.95, 1.05, valinit=rateIncrease) xSize.on_changed(updateRate) rax = plt.axes([0.025, 0.7, 0.18, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('Susceptible', 'Quarantined', 'Infected', 'Recovered'), active=0) radio.on_clicked(updateLineType) ax.grid(True) ax.axhline(0, color='black', lw=2) ax.axvline(0, color='black', lw=2) plt.show()
class interactive_chips: def __init__(self, default_stretch = 2.0, template_image = '', title = ''): self.title = title self.template_image = template_image self.kernel0 = 0 self.sd0 = default_stretch self.fig = plt.figure() self.plot_list = [] self.pt_list = [] self.an_list = [] self.ptn = 0 self.xy_list = [] self.bp_id = '' self.kp_id = '' self.color = 'hot' self.shp = '' def Display_chips(self, array_stack, info = '', img_name = ''): if info != '': self.info = info self.spat_coords = info['coords'] self.res = info['res'] else: self.spat_coords = '' self.res = '' if img_name != '': self.img_name = img_name else: self.img_name = '' self.array_stack = array_stack array_stack = None if numpy.ndim(self.array_stack) == 2: self.array_stack = [self.array_stack] plt.suptitle(self.title) self.dims = int(math.ceil(sqrt(len(self.array_stack)))) self.coords = [] for i1 in range(int(self.dims)): for i2 in range(int(self.dims)): self.coords.append([i1, i2]) #print 'coords', self.coords i = 0 self.i_list = [] self.i2_list = [] self.std_list = [] self.mean_list = [] #self.xy_list = [] #self.pt_no = 1 for array in self.array_stack: #print array name2 = "self.l22" + str(i) exec(name2 + " = plt.subplot2grid(shape = (int(self.dims),int(self.dims)), loc = self.coords[i])") #plt.subplot2grid(shape = (int(self.dims),int(self.dims)), loc = self.coords[i]) mean = float(numpy.mean(array[array!= ignore_value])) std = float(numpy.std(array[array!= ignore_value])) self.std_list.append(std) self.mean_list.append(mean) Min = float(mean) - float((std * self.sd0)) Max = float(mean) + float((std * self.sd0)) name = "self.l" + str(i) plt.show exec(name + " =imshow(array, cmap = get_cmap(self.color), picker = True)") exec(name + '.set_clim((Min, Max))') plt.text(-0.2, -0.2, i + 1) plt.axis('off') plt.subplots_adjust( hspace = 0.1,wspace = 0.005, top = 0.95, bottom = 0.01, left = 0.05, right = 0.99) self.i_list.append(name) self.i2_list.append(name2) #connect('button_press_event', self.submit_pts) #connect('key_press_event', self.plot_xys) i += 1 axcolor = 'red' axsd = axes([0.24, 0.01, 0.3, 0.02], axisbg=axcolor) axkernel = axes([0.24, 0.032, 0.3, 0.02], axisbg=axcolor) self.ssd = Slider(axsd, 'SD', 0.1, 5.0, valinit=self.sd0) self.skernel = Slider(axkernel, 'Kernel', 0, 10, valinit=self.kernel0) self.ssd.on_changed(self.update_sd) self.skernel.on_changed(self.update_kernel) self.ssd.poly self.rax = axes([0.01, 0.01, 0.15, 0.10], axisbg=axcolor) self.colors = RadioButtons(self.rax, ('autumn', 'bone', 'hot', 'RdYIBu_r'), active=2) self.colors.on_clicked(self.colorfunc) #self.fax = axes([0.65, 0.025, 0.75, 0.08], axisbg=axcolor) #self.functs = RadioButtons(fax, ('nd_image.gaussian_filter1d', 'lin.regress'), active=0) #functs_dict = {'nd_image.gaussian_filter1d':['sigma = .2', 'axis = 1', 'order = 3']} self.exax = axes([0.93, 0.015, 0.04, 0.029], axisbg=axcolor) self.ex = Button(self.exax, 'Exit') self.ex.on_clicked(self.exit_func) self.saveax = axes([0.93, 0.045, 0.05, 0.029], axisbg=axcolor) self.save = Button(self.saveax, 'Save') self.save.on_clicked(self.save_func) self.savexysax = axes([0.85, 0.015, 0.07, 0.029], axisbg=axcolor) self.savexys = Button(self.savexysax, 'Save Pts') self.savexys.on_clicked(self.save_xys) self.selectshpax = axes([0.85, 0.045, 0.07, 0.029], axisbg=axcolor) self.selectshp = Button(self.selectshpax, 'Load Shp') self.selectshp.on_clicked(self.select_shp) self.pixelclrax = axes([0.60, 0.047, 0.12, 0.029], axisbg=axcolor) self.pixelclr = Button(self.pixelclrax, 'Clr/Strt Pts') self.pixelclr.on_clicked(self.select_pts) self.pixelonax = axes([0.60, 0.015, 0.07, 0.029], axisbg=axcolor) self.pixelon = Button(self.pixelonax, 'On Pts') self.pixelon.on_clicked(self.connect) self.pixeloffax = axes([0.67, 0.015, 0.07, 0.029], axisbg=axcolor) self.pixeloff = Button(self.pixeloffax, 'Off Pts') self.pixeloff.on_clicked(self.disconnect) self.pixeldrawptsax = axes([0.75, 0.015, 0.07, 0.029], axisbg=axcolor) self.pixeldrawpts = Button(self.pixeldrawptsax, 'Plot Pts') self.pixeldrawpts.on_clicked(self.plot_xys) ## show() def disconnect(self, fill = ''): if self.kp_id != '': print 'Disconnecting key_press_event' disconnect(self.kp_id) if self.bp_id != '': print 'Disconnecting button_press_event' disconnect(self.bp_id) def connect(self, fill = ''): self.disconnect() print 'Connecting button_press_event' self.bp_id = connect('button_press_event', self.submit_pts) #print 'Connecting key_press_event' #self.kp_id = connect('key_press_event', self.plot_xys) def clear(self): self.xy_list = [] def save_plots(self, x): idir = '' if self.img_name != '': idir = os.path.dirname(self.img_name) elif self.shp != '': idir = os.path.dirname(self.shp) output_name = str(asksaveasfilename(title = 'Select output image name', initialdir = idir, filetypes=[("CSV","*.csv"),("TAB","*.txt")])) if os.path.splitext(output_name)[1] == '': output_name += '.csv' sep_dict = {'.csv' : ',', '.txt': '\t'} sep = sep_dict[os.path.splitext(output_name)[1]] fid = 0 out_lines = 'FID' + sep + 'x' + sep + 'y' + sep + sep+ 'Values\n' for coords, ys in self.out_plot_list: out_lines += str(fid) + sep + str(coords[0]) + sep + str(coords[1]) for y in ys: out_lines+= sep + str(y) out_lines+= '\n' fid += 1 print 'Writing:', os.path.basename(output_name) oo = open(output_name, 'w') oo.writelines(out_lines) oo.close() print 'Finished writing:', os.path.basename(output_name) def plot_xys(self, fills = '', title = ''): lp1 = dict(linewidth=1, color='blue', linestyle='-') lp2 = dict(linewidth=1, color='red', linestyle='o') fig = plt.figure() plt.suptitle(title) dims = dim_finder(self.xy_list) coord_list = dims_to_list(dims) i = 0 #gs = matplotlib.gridspec.GridSpec(len(dims), len(dims)) self.plot_list = [] self.out_plot_list = [] pi = 0 for xy in self.xy_list: if None not in xy: #try: nt = 'self.plotl' + str(pi) nt2 = 'self.plotm' + str(pi) ys = self.array_stack[:, int(xy[1]), int(xy[0])] xs = range(len(ys)) plt.show #call = 'plt.subplot(gs' + str(coord_list[i]) + ')' #eval(call) #plt.subplot(gs[i]) exec(nt2 + " = plt.subplot2grid(shape = (dims[0],dims[1]), loc = coord_list[i])") #plt.text(-0.02, -0.02, i + 1) #plt.subplots_adjust( hspace = 0.1,wspace = 0.05, top = 0.95, bottom = 0.01, left = 0.05, right = 0.99) exec(nt + " = plt.plot(xs, ys, linestyle = '-', color = 'r', marker = 'o')") #exec("axs = "+nt+".axes()") exec(nt2 + ".text(min(xs), max(ys), i + 1)") #exec(nt2 + " = plt.plot(xs, ys, 'o', color = 'red')") real_xys = array_coord_to_proj_coord(xy, self.spat_coords, self.res) #self.plot_list.append([real_xys, list(nt)]) self.out_plot_list.append([real_xys, list(ys)]) #plt.show pi += 1 #except: #print 'Could not plot', xy i += 1 self.saveplotsax = axes([0.85, 0.02, 0.12, 0.029], axisbg='red') self.saveplots = Button(self.saveplotsax, 'Save Plots') self.saveplots.on_clicked(self.save_plots) plt.show() def submit_pts(self, event, xyt = []): if xyt != []: xy = xyt x = xy[0] y = xy[1] else: x = event.xdata y = event.ydata xy = [x,y] if None not in xy and x >= 1 and y >= 1: self.xy_list.append(xy) try: self.ax.plot(event.xdata, event.ydata, 'ro') #plt.annotate(str(self.pt_no), xy = (x,y), textcoords = 'offset points') #plt.annotate(str(self.pt_no), xy = (x,y), xytext = (x, y)) self.ax.imshow(self.a) plt.annotate('hello', xy = (x,y)) except: #try: #plt.plot(event.xdata, event.ydata, 'ro') it = 0 for i in self.i2_list: ptn = 'self.pt_' + str(self.pt_no) + '_' + str(it) ann = 'self.an_' + str(self.pt_no) + '_' + str(it) exec(ptn + ' = ' + i + ".plot(x, y, 'ro')") exec(ann + ' = ' + i + ".annotate(str(self.pt_no), xy = (x,y))") #self.update_chips(self.array_stack) #exec(i + ".imshow(self.array_stack[it])") plt.subplots_adjust( hspace = 0.1,wspace = 0.005, top = 0.95, bottom = 0.01, left = 0.05, right = 0.99) self.pt_list.append(ptn) self.an_list.append(ann) it += 1 #except: #print 'Cannot plot pt', xy self.pt_no += 1 #print 'Pt coords are:', self.xy_list draw() def select_pts(self, array_stack = '', band = 0, pt_no = 1): self.pt_no = pt_no self.xy_list = [] self.plot_list = [] if array_stack != '': try: list(array_stack) self.array_stack = array_stack self.ax = subplot(111) self.a = numpy.sum(numpy.diff(self.array_stack, axis = 0), axis = 0)#self.array_stack[band] self.ax.imshow(self.a) plt.title('Press enter to submit points') self.exax = axes([0.93, 0.025, 0.04, 0.029], axisbg='red') self.ex = Button(self.exax, 'Exit') self.ex.on_clicked(self.exit_func) connect('button_press_event', self.submit_pts) connect('key_press_event', self.plot_xys) plt.show() array_stack = None except: print 'oops' self.connect() if len(self.pt_list) > 0: for pt in self.pt_list: ptt = pt + '[0]' exec(ptt + '.remove()') exec('del ' + ptt) exec('del ' + pt) rt = range(len(self.an_list)) no = len(self.an_list)/len(self.i2_list) rt2 = range(len(self.i2_list)) * no for i in rt: an = self.an_list[i] axt = self.i2_list[rt2[i]] exec(axt + '.texts.remove(' + an + ')') ## for an in self.an_list: ## ## #x = eval(an) ## #x.remove() ## #del x ## #print x ## ann = an + '[0]' ## #exec(ann + '.remove()') ## #exec('del ' + ann) ## exec('del ' + an) self.pt_list = [] self.an_list = [] #for i2 in self.i2_list: #self.l20.canvas.mpl_connect('button_press_event', self.submit_pts) #self.l20.connect('button_press_event', self.submit_pts) #plt.figure() ## ct = self.coords[-1] ## #ct = [0, ct[1] + 1] ## print ct ## self.ax = plt.subplot2grid(shape = (int(self.dims), int(self.dims)), loc = ct) ## self.a = self.array_stack[-1] ## self.ax.imshow(self.a) #axis([0, len(self.a[1,:])-0.5 , 0, len(self.a[:,1])-0.5]) #plt.subplots_adjust( hspace = 0.1,wspace = 0.00, top = 0.95, bottom = 0.01, left = 0.05, right = 0.99) #connect('key_press_event', plot_pts) ## def get_points(self, x): ## print self, x ## #plt.axis([0.,1.,0.,1.]) ## #plt.setp(plt.gca(),autoscale_on=False) ## happy = False ## while not happy: ## tellme('Hit the Enter key when finished slecting points') ## pts = numpy.asarray(plt.ginput(500, timeout = -1)) ## #for i in self.i_list: ## #exec(i + ".plot(pts[:,0], pts[:,1], 'ro')") ## ph = plt.plot(pts[:,0], pts[:,1], 'ro') ## print pts ## tellme('Hit the Enter key to accept these points\nMouse button to reject') ## happy = plt.waitforbuttonpress() ## if not happy: ## for p in ph: p.remove() ## else: ## print pts ## return pts ## def update_sd(self, sd): ## kernel = self.skernel.val ## sd = self.ssd.val ## ## #l.set_data(array) ## #l.set_filterrad(freq) ## #l.set_filternorm(freq) ## #, vmin = mean - (std * freq)) ## #l.check_update(array) ## #l = imshow(array, vmin = mean - (std * freq)) ## #axes([0, numpy.shape(array)[1], numpy.shape(array)[0], 0]) ## for i in self.i_list: std = self.std_list[int(i[6:])] mean = self.mean_list[int(i[6:])] Min = mean - (std * sd) Max = mean + (std * sd) ## ## exec(i + '.set_data(ndimage.gaussian_filter(array_stack['+i[1:]+'], kernel))') exec(i + '.set_clim((Min, Max))') draw() def update_kernel(self, kernel): for i in self.i_list: exec(i + '.set_data(ndimage.gaussian_filter(self.array_stack['+i[6:]+'], kernel))') #exec(i + '.set_clim((Min, Max))') draw() def update_chips(self, new_stack, title = ''): self.array_stack = new_stack #plt.suptitle(None) #plt.suptitle(title) self.std_list = [] self.mean_list = [] if numpy.ndim(new_stack) == 2: new_stack =[new_stack] for i in self.i_list[:len(self.array_stack)]: array = new_stack[+int(i[6:])] mean = float(numpy.mean(array[array!= ignore_value])) std = float(numpy.std(array[array!= ignore_value])) self.std_list.append(std) self.mean_list.append(mean) Min = float(mean) - float((std * self.sd0)) Max = float(mean) + float((std * self.sd0)) exec(i + '.set_data(new_stack['+i[6:]+'])') exec(i + '.set_clim((Min, Max))') draw() if self.xy_list != []: self.plot_xys(title = title) #Display_chips(self) def colorfunc(self, label): #l.set_color(label) self.color = label for i in self.i_list: exec(i + '.set_cmap(get_cmap(self.color))') draw() def select_shp(self, x): idir = '' if self.shp != '': idir = os.path.dirname(self.shp) elif self.img_name != '': idir = os.path.dirname(self.img_name) self.shp = str(askopenfilename(title = 'Select Point Shapefile',initialdir = idir, filetypes=[("Shapefile","*.shp")])) xys = xy_coords(self.shp, False) print 'There are', len(xys), 'points to plot' if len(xys) > 16: print 'There are more than 16 points in shapefile' print 'Randomly selecting 16 points from the shapefile' import random smp = random.sample(range(len(xys)), 16) xys = numpy.array(xys)[smp] if self.xy_list == []: self.select_pts() if self.spat_coords != '' and self.res != '': for xy in xys: if inside(xy, self.spat_coords): xyt = proj_coord_to_array_coord(xy, self.spat_coords, self.res) self.submit_pts(event = '',xyt = xyt) else: print 'Point', xy, 'falls outside of raster' def save_xys(self, x): idir = '' if self.shp != '': idir = os.path.dirname(self.shp) elif self.img_name != '': idir = os.path.dirname(self.img_name) output_name = str(asksaveasfilename(title = 'Select output shapefile name', initialdir = idir, filetypes=[("Shapefile","*.shp"),("CSV","*.csv"), ("KML","*.kml")])) if os.path.splitext(output_name)[1] == '': output_name += '.shp' xyo = [] for xy in self.xy_list: xyo.append(array_coord_to_proj_coord(xy, self.spat_coords, self.res)) if os.path.splitext(output_name)[1] == '.shp': list_to_point_shapefile(xyo, self.img_name, output_name) elif os.path.splitext(output_name)[1] == '.csv': write_xy_csv(xyo, output_name) elif os.path.splitext(output_name)[1] == '.kml' : zone = int(self.info['zone']) if zone in range(100): xy_list_to_kml(xyo, output_name, self.info['zone']) else: warning = showwarning('Cannot find zone', 'Please ensure the raster is in UTM to export KMLs') def save_func(self, x): idir = '' if self.img_name != '': idir = os.path.dirname(self.img_name) elif self.shp != '': idir = os.path.dirname(self.shp) print 'yay' #initialdir = idir output_name = str(asksaveasfilename(title = 'Select output image name', initialdir = idir, filetypes=[("IMAGINE","*.img"),("tif","*.tif")])) if os.path.splitext(output_name)[1] == '': output_name += '.img' try: Format = format_dict[os.path.splitext(output_name)[1]] except: warning = showwarning('Unsupported Format', 'Supported formats are:\n ' + str(list(format_dict))) stack(self.array_stack, output_name, self.template_image, dt = 'Float32',df = Format, array_list = True) def exit_func(self, x): self.array_list = None self.array_stack = None self.array = None self.a = None sys.exit()
def process(paths, is_limit_resource=False, max_dim=2000): #Get data process.cur_id = 0 process.data = read_fits_image(paths[process.cur_id], is_scale=is_limit_resource, scale=max_dim) #Setup plt process.inverse_mode = 1 # fig, ax = plt.subplots() fig, (ax_hist, ax) = plt.subplots(1, 2) plt.subplots_adjust(left=0.25, bottom=0.25) plt_im = plt.imshow(process.inverse_mode * boost(process.data), cmap='seismic') plt.colorbar() ax.margins(x=0) #Sliders axcolor = 'lightgoldenrodyellow' ax_satur = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor) ax_gamma = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor) s_satur = Slider(ax_satur, 'Saturate %', 0, 10, valinit=0, valstep=0.25) s_gamma = Slider(ax_gamma, 'Gamma', 0.001, 1.0, valinit=0.14) def update(val): print("Update: saturate=%d percent, gamma=%f" % (s_satur.val, s_gamma.val)) boost_data = process.inverse_mode * boost( process.data, saturate=s_satur.val / 100.0, gamma=s_gamma.val) plt_im.set_data(boost_data) plt_im.set_clim([boost_data.min(), boost_data.max()]) fig.canvas.draw_idle() ax_hist.clear() ax_hist.hist(boost_data.flatten(), bins=100, log=True, color='b') s_satur.on_changed(update) s_gamma.on_changed(update) update(0) #Buttons: reset, save, cmap resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) reset_button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') def reset(event): s_satur.reset() s_gamma.reset() reset_button.on_clicked(reset) saveax = plt.axes([0.65, 0.025, 0.1, 0.04]) save_button = Button(saveax, 'Save', color=axcolor, hovercolor='0.975') def save(event): # out_path = paths[process.cur_id].replace('.fits','_'+ radio.value_selected+'_plot.jpg') # plt.savefig(out_path, bbox_inches='tight',transparent=True, pad_inches=0) # print('saved ', out_path) # save to the same dir as source img out_path = paths[process.cur_id].replace('.fits', '.jpg') plt.imsave( out_path, process.inverse_mode * boost( process.data, saturate=s_satur.val / 100.0, gamma=s_gamma.val), cmap=radio.value_selected) print('saved ', out_path) # #Save directly to 'imgs_VIA' dir # out_path = 'imgs_VIA/' + paths[process.cur_id].split('/')[-1].replace('.fits', '.jpg') # plt.imsave(out_path, process.inverse_mode * boost(process.data, saturate=s_satur.val/100.0, gamma=s_gamma.val), cmap=radio.value_selected) # print('saved ', out_path) save_button.on_clicked(save) inverseax = plt.axes([0.525, 0.025, 0.1, 0.04]) inverse_button = Button(inverseax, 'Inverse', color=axcolor, hovercolor='0.975') def inverse(event): process.inverse_mode = -process.inverse_mode print('inverse_mode ', process.inverse_mode) update(None) inverse_button.on_clicked(inverse) prevax = plt.axes([0.25, 0.025, 0.1, 0.04]) prev_button = Button(prevax, 'Prev', color=axcolor, hovercolor='0.975') def prev(event): process.cur_id = (process.cur_id - 1) if process.cur_id > 0 else process.cur_id print('Back to ... %d/%d: %s' % (process.cur_id, len(paths), paths[process.cur_id])) process.data = read_fits_image(paths[process.cur_id], is_scale=is_limit_resource, scale=max_dim) update(None) prev_button.on_clicked(prev) nextax = plt.axes([0.4, 0.025, 0.1, 0.04]) next_button = Button(nextax, 'Next', color=axcolor, hovercolor='0.975') def next(event): process.cur_id = ( process.cur_id + 1) if (process.cur_id + 1) < len(paths) else process.cur_id print('Next to ... %d/%d: %s' % (process.cur_id, len(paths), paths[process.cur_id])) process.data = read_fits_image(paths[process.cur_id], is_scale=is_limit_resource, scale=max_dim) update(None) next_button.on_clicked(next) rax = plt.axes([0.025, 0.5, 0.15, 0.20], facecolor=axcolor) radio = RadioButtons(rax, ('gray', 'seismic'), active=1) def colorfunc(label): plt_im.set_cmap(label) fig.canvas.draw_idle() radio.on_clicked(colorfunc) plt.show()
fig, ax = plt.subplots() l, = ax.plot(t, s0, lw=2, color='red') plt.subplots_adjust(left=0.3) axcolor = 'lightgoldenrodyellow' rax = plt.axes([0.05, 0.7, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz')) def hzfunc(label): hzdict = {'2 Hz': s0, '4 Hz': s1, '8 Hz': s2} ydata = hzdict[label] l.set_ydata(ydata) plt.draw() radio.on_clicked(hzfunc) rax = plt.axes([0.05, 0.4, 0.15, 0.15], axisbg=axcolor) radio2 = RadioButtons(rax, ('red', 'blue', 'green')) def colorfunc(label): l.set_color(label) plt.draw() radio2.on_clicked(colorfunc) rax = plt.axes([0.05, 0.1, 0.15, 0.15], axisbg=axcolor) radio3 = RadioButtons(rax, ('-', '--', '-.', 'steps', ':')) def stylefunc(label):
def genFigure(arrPattern, arrCoEle, arrAzi, arrFreq) -> None: r""" This function should not need much modification. First, we setup the GUI, plot the initial data slice and finally create some GUI events that trigger the redrawing of the figure with the respective data slice. """ # some mpl magic nobody gets fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.margins(x=0) plt.subplots_adjust(left=0.25, bottom=0.25) # make the sliders and radio buttons real axColor = "lightgoldenrodyellow" axFreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axColor) axElem = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axColor) axPol = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axColor) axE = plt.axes([0.025, 0.7, 0.15, 0.15], facecolor=axColor) # generate a slider for the excitation frequencies and # for the elements sldFreq = Slider( axFreq, "Freq", 0, arrPattern.shape[2] - 1, valinit=0, valfmt="%i" ) sldElem = Slider( axElem, "Element", 0, arrPattern.shape[-1] - 1, valinit=0, valfmt="%i" ) # we also throw in a radio button to switch between the polariations rdPol = RadioButtons(axPol, ("0", "1"), active=0) rdE = RadioButtons(axE, ("0", "1"), active=0) # this allows to switch between the two field quantities. lstFun = [xp.real, xp.imag] # draw the initial image img = ax.imshow( xp.real(arrPattern[:, :, 0, 0, 0]), vmin=-xp.max(xp.abs(arrPattern)), vmax=xp.max(xp.abs(arrPattern)), extent=[arrAzi[0], arrAzi[-1], arrCoEle[0], arrCoEle[-1]], ) # this function is triggered whenever something in the GUI changes def update(val): freq = sldFreq.val elem = sldElem.val pol = rdPol.value_selected # select real or imaginary part fun = lstFun[int(rdE.value_selected)] img.set_data(fun(arrPattern[:, :, int(freq), int(pol), int(elem)])) fig.canvas.draw_idle() # attach GUI events to the update function rdPol.on_clicked(update) rdE.on_clicked(update) sldFreq.on_changed(update) sldElem.on_changed(update) fig.colorbar(img, ax=ax) plt.show()
elif label == 'Nek0': rotList = frontal elif label == 'Nek1': rotList = rotateY(frontal, -22) rotList = rotateX(rotList, 22) elif label == 'Nek2': rotList = rotateY(frontal, -45) rotList = rotateX(rotList, 45) elif label == 'Nek3': rotList = rotateY(frontal, -45) rotList = rotateX(rotList, 30) elif label == 'Nek4': rotList = rotateY(frontal, -45) rotList = rotateX(rotList, 35.2) update(depth) radio.on_clicked(setPattern) #### Axes for spectrum #### axSpect = fig.add_axes([.1, .05/winAspect, .7/winAspect, .15]) axSpect.set_xlim([-2., 2.]) axSpect.set_ylim([0., 1000.]) plotFreq = plotTime - np.pi line, = axSpect.semilogy(plotFreq, plotData) axSpect.set_yscale('symlog', linthreshy=PLOTWIDTH**0.5) # Keypress 'q' to quit def keypress(event): global ptList, data, mute if event.key == 'q': stream.stop_stream()
radio = RadioButtons(rax,('Linear','Log')) def radio_click(label): if label== 'Linear': plt.title( 'linear',loc = 'right') logx ==0 logy ==0 elif label== 'Log': plt.title( 'log',loc='right') logx ==1 logy ==1 radio.on_clicked(radio_click) ############################################################################### # Calculation button: # Plots the results and prints the x and y value ################################################################################ x,y = calculation(xmin, xmax, ymin, ymax, xaxis, yaxis, logx, logy, xdata, ydata) bax = plt.axes([0.01,0.19,0.1,0.03]) calc_button = Button(bax,'Calculate',image = None, color = '0.95',hovercolor = '0.65') def calculate_button(event): x,y= calculation(xmin, xmax, ymin, ymax, xaxis, yaxis, logx, logy, xdata, ydata) print x,y plt.figure() plt.plot(x, y) plt.show()
axcolor = 'lightgoldenrodyellow' axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axamp = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0) samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0) def update(val): amp = samp.val freq = sfreq.val l.set_ydata(amp*np.sin(2*np.pi*freq*t)) fig.canvas.draw_idle() sfreq.on_changed(update) samp.on_changed(update) resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') def reset(event): sfreq.reset() samp.reset() button.on_clicked(reset) rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor) radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) def colorfunc(label): l.set_color(label) fig.canvas.draw_idle() radio.on_clicked(colorfunc) plt.show()
Button2_ax = plt.axes([0.2, 0.02, 0.1, 0.03]) Button2 = Button(Button2_ax, 'Display') Button2.on_clicked(button2_press) #button3 Button3_ax = plt.axes([0.3, 0.02, 0.1, 0.03]) Button3 = Button(Button3_ax, 'Change') Button3.on_clicked(button3_press) #button4 Button4_ax = plt.axes([0.4, 0.02, 0.1, 0.03]) Button4 = Button(Button4_ax, 'Exit') Button4.on_clicked(button4_press) #radio1 axcolor = 'lightgoldenrodyellow' Rax = plt.axes([0.01, 0.01, 0.08, 0.06], axisbg=axcolor) Radio = RadioButtons(Rax, ('Red', 'Blue', 'Green')) Radio.on_clicked(radio_press) #slider1 slider1_ax = plt.axes([0.55 , 0.01, 0.3, 0.02], axisbg=axcolor) slider1 = Slider(slider1_ax, 'Bound', 0.1, 200, valinit=100) slider1.on_changed(slider_updata) #slider2 slider2_ax = plt.axes([0.55, 0.03, 0.3, 0.02], axisbg=axcolor) slider2 = Slider(slider2_ax, 'Base', 0.1, 1000, valinit=500) slider2.on_changed(slider_updata) #Tk Control = tk.Tk() Control.title('Control') #Restart_button Control_Restart = tk.Button(Control,text = 'Restart',command = Restart) Control_Restart.grid(column=2,row=1) #Heart_base number input