def __init__(self,image,tiling,imginfo={},fnext=None,verbosity=0): """ image ... 2D Array for background image tiling ... Tiling instance imginfo... (opt) dictionary with image parameters (see ImageBrowser) self.bDual.on_clicked(self.Dual); verbosity. (opt) quiet (0), verbose (3), debug (4) """ import matplotlib.collections as c; # init ImageBrowser super(TilingBrowser,self).__init__(image,imginfo,fnext,verbosity); self.axis.set_title('TilingBrowser: %s' % self.imginfo['desc']); # draw edges self.tiling= tiling; segments = [self.tiling.points[e] for e in self.tiling.edges]; self.LineCol = c.LineCollection(segments); self.LineCol.set_color('blue'); self.axis.add_collection(self.LineCol); # add buttons axEdit = self.fig.add_axes([0.85, 0.85,0.1, 0.04]); axSave = self.fig.add_axes([0.85, 0.8, 0.1, 0.04]); axLoad = self.fig.add_axes([0.85, 0.75,0.1, 0.04]); self.bEdit = Button(axEdit,'Edit'); self.bSave = Button(axSave,'Save'); self.bLoad = Button(axLoad,'Load'); self.bEdit.on_clicked(self.ToggleEdit); self.bSave.on_clicked(self.Save); self.bLoad.on_clicked(self.Load); self._update();
def setup_controls(self): """ Set up button axes""" buttons = [[('Auto levels', self.do_autolevels), ('Levels1', self.do_levels_test), ('Oldie', self.do_levels_old), ('Clip', self.do_levels_clip)], [('Blur uniform', self.do_blur), ('Blur gaussian', self.do_blur_gaussian), ('Sharpen', self.do_sharpen), ('Unsharp', self.do_unsharp), ('Edge detection', self.do_edges)], [('Apply', self.apply), ('Reset', self.reset), ('Save', self.save), ('Quit', self.quit)]] max_cols = max(len(row) for row in buttons) padding = 0.01 start, end = 0.03, 0.97 hspace = (end - start) / max_cols row_height = 0.03 vspace = row_height + 0.003 for j, row in enumerate(buttons): for i, b in enumerate(row): box = [start + i*hspace, 0.01 + j*vspace, hspace - padding, row_height] print box axis = self.fig.add_axes(box) button = Button(axis, b[0]) self.axes.append(axis) button.on_clicked(b[1]) self.buttons.append(button)
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 __init__(self, image, low, high): self.image_name = image self.low = low self.high = high self.filter = None self.output = None self.filter_type = None self.padRows = None self.padCols = None original_input = cv2.imread(image,0) rows, cols = original_input.shape if(rows < cols): original_input = cv2.transpose(original_input) self.transposed = True else: self.transposed = False rows, cols = original_input.shape optimalRows = cv2.getOptimalDFTSize(rows) optimalCols = cv2.getOptimalDFTSize(cols) self.padRows = optimalRows - rows self.padCols = optimalCols - cols self.input = np.zeros((optimalRows,optimalCols)) self.input[:rows,:cols] = original_input self.dftshift = get_dft_shift(self.input) plt.subplots_adjust(left=0, bottom=0.05, right=1, top=1, wspace=0, hspace=0) plt.subplot(131) plt.axis('off') plt.title('original image') plt.imshow(self.input, cmap = 'gray',interpolation='nearest') self.axslow = plt.axes([0.05, 0.01, 0.5, 0.02]) self.slow = Slider(self.axslow, 'low', 0.01, 1, valinit=self.low) self.slow.on_changed(self.updateLow) self.axhigh = plt.axes([0.05, 0.03, 0.5, 0.02]) self.shigh = Slider(self.axhigh, 'high', 0.01, 1, valinit=self.high) self.shigh.on_changed(self.updateHigh) self.slow.slidermax=self.shigh self.shigh.slidermin=self.slow self.axfilter = plt.axes([0.62, 0.01, 0.15, 0.04]) self.rfilter = RadioButtons(self.axfilter, ('Gaussian Filter', 'Ideal Filter')) self.rfilter.on_clicked(self.updateFilterType) self.filter_type = self.rfilter.value_selected self.axprocess = plt.axes([0.8, 0.01, 0.08, 0.04]) self.bprocess = Button(self.axprocess, 'Process') self.bprocess.on_clicked(self.process) self.axsave = plt.axes([0.88, 0.01, 0.08, 0.04]) self.bsave = Button(self.axsave, 'Save') self.bsave.on_clicked(self.save)
def __init__(self, viewer, Npoints, data): self.viewer = viewer self.Npoints = Npoints self.data = data self.pointsh = [] plt.sca(self.viewer.ax) axclick = plt.axes([0.09, 0.15, 0.1, 0.075]) self.bclick = Button(axclick, 'Click') self.bclick.on_clicked(self.click) axreset = plt.axes([0.20, 0.15, 0.1, 0.075]) self.breset = Button(axreset, 'Reset') self.breset.on_clicked(self.reset) axfileload = plt.axes([0.09, 0.05, 0.1, 0.075]) self.bfileload = Button(axfileload, 'Load...') self.bfileload.on_clicked(self.fileLoad) axfilesave = plt.axes([0.20, 0.05, 0.1, 0.075]) self.bfilesave = Button(axfilesave, 'Save...') self.bfilesave.on_clicked(self.fileSave) self.showPoints()
def main(): from matplotlib import pyplot as plt import utils fig = utils.createfig() a = WSin(fig, [0.1, 0.5, 0.8, 0.3] , nps=5) b = WSin(fig, [0.1, 0.1, 0.8, 0.3], nps=3, om=3) args11 = (dict(k=0, am=1, ph=0, t='v', n='1'), dict(k=-1.5, am=0.1, ph=0.5, t='v', n='3'),) args12 = (dict(k=1,am=2,ph=1,t='i',n='2'),) args13 = (dict(k=100,am=3,ph=2,t='i',n='no',v=False),) args2 = (dict(k=0,am=1,ph=0,t='v',n='1'),dict(k=1,am=2,ph=1,t='i',n='2'), dict(k=-1.5,am=0.1,ph=0,t='v',n='3'),\ dict(k=100,am=3,ph=2,t='i',n='no',v=False),) a.new(100, args11, args12, ()) b.new(101, *args2) #b.set_anim(True) # bottone from matplotlib.widgets import Button box = fig.add_axes([0.05, 0.90, 0.05, 0.05]) but = Button(box, 'next') def func(wtf): #args2 = _r_args(4) #print args2 #b.new(100, *args2) b.set_anim(not b.get_anim()) but.on_clicked(func) plt.show()
def initUI(self): self.fig, self.ax = plt.subplots() self.fig.canvas.set_window_title('Numerik DGL 2 - Schattenprojektion') self.fig.suptitle('Vorwaertsproblem') plt.subplots_adjust(bottom=0.3) plt.axis([0, 200, -100, 100]) plt.axis('equal') axColor = 'lightgoldenrodyellow' # Slider - Phi axPhi = plt.axes([0.18, 0.2, 0.65, 0.03], axisbg=axColor) self.sliderPhi = Slider(axPhi, 'Phi', 0, 360, valinit=self.phi, valfmt='%1d') self.sliderPhi.on_changed(self.onUpdate) # Slider - Delta Phi axDeltaPhi = plt.axes([0.18, 0.15, 0.65, 0.03], axisbg=axColor) self.sliderDeltaPhi = Slider(axDeltaPhi, 'Delta Phi', 5, 360, valinit=self.delta_phi, valfmt='%1d') self.sliderDeltaPhi.on_changed(self.onUpdate) # Slider - Psi axPsi = plt.axes([0.18, 0.1, 0.65, 0.03], axisbg=axColor) self.sliderPsi = Slider(axPsi, 'Psi', 0, 180, valinit=self.psi, valfmt='%1d') self.sliderPsi.on_changed(self.onUpdate) # Button - Previous axPrev = plt.axes([0.18, 0.03, 0.1, 0.05]) self.buttonPrev = Button(axPrev, 'Previous') self.buttonPrev.on_clicked(self.onPrevious) # Button - Next axNext = plt.axes([0.29, 0.03, 0.1, 0.05]) self.buttonNext = Button(axNext, 'Next') self.buttonNext.on_clicked(self.onNext) # Button - Reset axReset = plt.axes([0.73, 0.03, 0.1, 0.05]) self.buttonReset = Button(axReset, 'Reset') self.buttonReset.on_clicked(self.onReset) self.onDraw()
def __setup_plots(self): # Some actual plots. self.plot_axis_z = plt.subplot2grid((6, 20), (0, 0), colspan=18) self.plot_axis_n = plt.subplot2grid((6, 20), (1, 0), colspan=18) self.plot_axis_e = plt.subplot2grid((6, 20), (2, 0), colspan=18) self.misfit_axis = plt.subplot2grid((6, 20), (3, 0), colspan=11, rowspan=3) self.colorbar_axis = plt.subplot2grid((6, 20), (3, 12), colspan=1, rowspan=3) #self.adjoint_source_axis = plt.subplot2grid((6, 8), (4, 0), colspan=4, #rowspan=1) self.map_axis = plt.subplot2grid((6, 20), (3, 13), colspan=8, rowspan=3) # Plot the map and the beachball. bounds = self.project.domain["bounds"] self.map_obj = visualization.plot_domain(bounds["minimum_latitude"], bounds["maximum_latitude"], bounds["minimum_longitude"], bounds["maximum_longitude"], bounds["boundary_width_in_degree"], rotation_axis=self.project.domain["rotation_axis"], rotation_angle_in_degree=self.project.domain["rotation_angle"], plot_simulation_domain=False, show_plot=False, zoom=True) visualization.plot_events([self.event], map_object=self.map_obj) # All kinds of buttons [left, bottom, width, height] self.axnext = plt.axes([0.90, 0.95, 0.08, 0.03]) self.axprev = plt.axes([0.90, 0.90, 0.08, 0.03]) self.axreset = plt.axes([0.90, 0.85, 0.08, 0.03]) self.bnext = Button(self.axnext, 'Next') self.bprev = Button(self.axprev, 'Prev') self.breset = Button(self.axreset, 'Reset Station')
def param_gui(letter_name, shapeModeler): global sliders, mainPlot, fig, pca_params fig, ax = plt.subplots() whiteSpace = 0.15 + num_params*0.05 plt.subplots_adjust( bottom=whiteSpace) plt.axis('equal') #plot of initial shape params = np.zeros((num_params,1)) shape = shapeModeler.makeShape(params) shape = ShapeModeler.normaliseShape(shape) numPointsInShape = len(shape)/2 x_shape = shape[0:numPointsInShape] y_shape = shape[numPointsInShape:] mainPlot, = plt.plot(x_shape, -y_shape) plt.axis([-1, 1, -1, 1],autoscale_on=False, aspect='equal') plt.title(letter_name) #add sliders to modify parameter values parameterVariances = shapeModeler.getParameterVariances() sliders = [0]*num_params for i in range(num_params): slider = Slider(plt.axes([0.25, 0.1+0.05*(num_params-i-1), 0.65, 0.03], axisbg=axcolor), 'Parameter '+str(i+1), -5*parameterVariances[i], 5*parameterVariances[i], valinit=0) slider.on_changed(partial(update, shapeModeler)) sliders[i] = slider resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') button.on_clicked(reset) plt.show() return pca_params
def _setup_display(self): """ Sets up the Matplotlib figures and axes required for the visualization. """ self.network_fig = figure(figsize=(20, 20)) self.network_fig.canvas.set_window_title("Hopfield Network Visualization") gs = gridspec.GridSpec(2, 4) self.main_network = subplot(gs[:,:2]) self.main_network.set_title("Network Diagram") self.main_network.get_xaxis().set_ticks([]) self.main_network.get_yaxis().set_ticks([]) self.energy_diagram = subplot(gs[0,2], projection='Fovea3D') self.energy_diagram.set_title("Energy Function") self.contour_diagram = subplot(gs[0,3]) self.contour_diagram.set_title("Energy Contours") self.state_diagram = subplot(gs[1,2]) self.state_diagram.set_title("Current Network State") self.state_diagram.get_xaxis().set_ticks([]) self.state_diagram.get_yaxis().set_ticks([]) self.weight_diagram = subplot(gs[1,3]) self.weight_diagram.set_title("Weight Matrix Diagram") self.weight_diagram.get_xaxis().set_ticks([]) self.weight_diagram.get_yaxis().set_ticks([]) self.network_fig.suptitle("Hopfield Network Visualization", fontsize=14) self.mode = self.network_fig.text(0.4, 0.95, "Current Mode: Initialization", fontsize=14, horizontalalignment='center') self.iteration = self.network_fig.text(0.6, 0.95, "Current Iteration: 0", fontsize=14, horizontalalignment='center') # Widget Functionality view_wf = axes([.53, 0.91, 0.08, 0.025]) self.view_wfbutton = Button(view_wf, 'Wireframe') view_attract = axes([.615, 0.91, 0.08, 0.025]) self.view_attractbutton = Button(view_attract, 'Attractors')
def debug_plot(a, b, nodes, fs, coeffs): global _debug_fig, _debug_cancelled if _debug_cancelled: return if 'show' not in locals(): from pylab import axes, subplot, subplots_adjust, figure, draw, plot, axvline, xlim, title, waitforbuttonpress, gcf from matplotlib.widgets import Button if _debug_fig is None: #curfig = gcf() #print dir(curfig) _debug_fig = figure() ax = _debug_fig.add_subplot(111) #subplots_adjust(bottom=0.15) butax = axes([0.8, 0.015, 0.1, 0.04]) button = Button(butax, 'Debug', hovercolor='0.975') def debug(event): import pdb; pdb.set_trace() button.on_clicked(debug) _debug_fig.sca(ax) draw() #figure(curfig) _debug_fig.gca().clear() plot(nodes, fs, linewidth=5, figure = _debug_fig) axvline(a, color="r", figure = _debug_fig) axvline(b, color="r", figure = _debug_fig) d = 0.05 * (b-a) _debug_fig.gca().set_xlim(a-d, b+d) title("press key in figure for next debugplot or close window to continue") try: while not _debug_cancelled and not _debug_fig.waitforbuttonpress(-1): pass except: _debug_cancelled = True
class NavField: def __init__(self, pltinfo): self.fld = -1 self.nflds = len(pltinfo.selindices['field']) self.pltinfo = pltinfo prevwidth = 0.13 nextwidth = 0.12 butheight = 0.05 butleft = 0.7 butbot = 0.025 butgap = 0.5 * butbot self.nextloc = [butleft + prevwidth + butgap, butbot, nextwidth, butheight] self.prevloc = [butleft, butbot, prevwidth, butheight] self.inactivecolor = '#99aaff' self.activecolor = '#aaffcc' def _draw_buts(self): if self.fld < self.nflds - 1: axnext = pl.axes(self.nextloc) self.bnext = Button(axnext, 'Next fld >', color=self.inactivecolor, hovercolor=self.activecolor) self.bnext.on_clicked(self.next) if self.fld > 0: axprev = pl.axes(self.prevloc) self.bprev = Button(axprev, '< Prev fld', color=self.inactivecolor, hovercolor=self.activecolor) self.bprev.on_clicked(self.prev) #pl.show() def _do_plot(self): didplot = plotfield(self.pltinfo.selindices['field'][self.fld], self.pltinfo) if didplot: self._draw_buts() return didplot def next(self, event): didplot = False startfld = self.fld while self.fld < self.nflds - 1 and not didplot: self.fld += 1 didplot = self._do_plot() if not didplot: print "You are on the last field with any selected baselines." self.fld = startfld #plotfield(self.pltinfo.selindices['field'][self.fld], # self.pltinfo, self.mytb) def prev(self, event): didplot = False startfld = self.fld while self.fld > 0 and not didplot: self.fld -= 1 didplot = self._do_plot() if not didplot: print "You are on the first field with any selected baselines." self.fld = startfld
def preparePlot(shapeModeler): global sliders, mainPlot, fig fig, ax = plt.subplots(); whiteSpace = 0.15 + numParams*0.05; plt.subplots_adjust( bottom=whiteSpace); plt.axis('equal'); #plot of initial shape params = np.zeros((numParams,1)); shape = shapeModeler.makeShape(params); shape = ShapeModeler.normaliseShape(shape); numPointsInShape = len(shape)/2; x_shape = shape[0:numPointsInShape]; y_shape = shape[numPointsInShape:]; mainPlot, = plt.plot(x_shape, -y_shape); plt.axis([-1, 1, -1, 1],autoscale_on=False, aspect='equal'); #add sliders to modify parameter values parameterVariances = shapeModeler.getParameterVariances(); sliders = [0]*numParams; for i in range(numParams): slider = Slider(plt.axes([0.25, 0.1+0.05*(numParams-i-1), 0.65, 0.03], axisbg=axcolor), 'Parameter '+str(i+1), -5*parameterVariances[i], 5*parameterVariances[i], valinit=0); slider.on_changed(update); sliders[i] = slider; resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') button.on_clicked(reset) plt.show()
def __init__(self, title, instances, quadrants, clusters): self.title = title self.instances = instances self.quadrants = quadrants self.clusters = clusters self.overlay = False self.trend = False self.fig = plt.figure() # Button axes self.axtrends = self.fig.add_axes([0.75, 0.4, 0.2, 0.05]) self.btrends = Button(self.axtrends, 'Trends') self.btrends.on_clicked(self.trends) self.axalerts = self.fig.add_axes([0.75, 0.3, 0.2, 0.05]) self.balerts = Button(self.axalerts, 'Alerts') self.balerts.on_clicked(self.alerts) self.axoverlays = self.fig.add_axes([0.75, 0.2, 0.2, 0.05]) self.boverlays = Button(self.axoverlays, 'Overlays') self.boverlays.on_clicked(self.overlays) # Axes are defined [left, bottom, width, height] self.canvas = self.fig.add_axes([0.1, 0.1, 0.6, 0.8]) self.draw_canvas_instances() self.draw_canvas_quadrants_vanilla() self.info = self.fig.add_axes([0.75, 0.5, 0.2, 0.4]) plt.setp(self.info, xticks=[], yticks=[]) cid = self.fig.canvas.mpl_connect('button_press_event', self.onclick)
def __init__(self,image,points,imginfo={},fnext=None,verbosity=0): """ image ... 2D Array for background image points ... initial list of peak positions shape(N,2) imginfo... (opt) dictionary with image parameters (see ImageBrowser) self.bDual.on_clicked(self.Dual); verbosity. (opt) quiet (0), verbose (3), debug (4) """ # init ImageBrowser super(PointBrowser,self).__init__(image,imginfo,fnext,verbosity); self.axis.set_title('PointBrowser: %s' % self.imginfo['desc']); # draw point list self.points = np.asarray(points); assert( self.points.ndim==2 and self.points.shape[1]==2 ); self.Line2D, = self.axis.plot(self.points[:,0], self.points[:,1],\ 'ro',picker=5); #self.axis.set_xlim(*self.imginfo['extent'][0:2]); #self.axis.set_ylim(*self.imginfo['extent'][2:4]); # add buttons axEdit = self.fig.add_axes([0.85, 0.85,0.1, 0.04]); axSave = self.fig.add_axes([0.85, 0.8, 0.1, 0.04]); axLoad = self.fig.add_axes([0.85, 0.75,0.1, 0.04]); self.bEdit = Button(axEdit,'Edit'); self.bSave = Button(axSave,'Save'); self.bLoad = Button(axLoad,'Load'); self.bEdit.on_clicked(self.ToggleEdit); self.bSave.on_clicked(self.Save); self.bLoad.on_clicked(self.Load); self._update();
def show(self): plot_idx = 0 self.current_plot_idx = plot_idx self.plots[plot_idx].set_visible(True) self.set_data_cursor() if(len(self.plots) > 1 and self.use_matplotlib_widget is True): button_width = .05 index_width = .03*len(str(len(self.plots)-1)) button_height = .05 button_bottom = .025 center = .5 margin = .005 axes_prev_rect = [center - index_width/2 - margin - button_width, button_bottom, button_width, button_height] axes_prev = self.figure.add_axes(axes_prev_rect) self.button_prev = Button(axes_prev, '<') self.button_prev.on_clicked(self.show_prev_plot) self.index_text = self.figure.text( center - index_width/2, (button_bottom+button_height)/2, "{}/{}".format(self.current_plot_idx, len(self.plots)-1) ) axes_next_rect = [center + index_width/2 + margin, button_bottom, button_width, button_height] axes_next = self.figure.add_axes(axes_next_rect) self.button_next = Button(axes_next, '>') self.button_next.on_clicked(self.show_next_plot) self.figure.show()
def __init__(self, px, mx, kx): self.buttonP = Button(px, '+') self.buttonM = Button(mx, '-') self.stVal = kx self.buttonP.on_clicked(self.button_handler_p) self.buttonM.on_clicked(self.button_handler_m)
class slider(): def __init__(self,res): self.res=res def slider_bar(self,res): #setupthe slider axcolor = 'lightgoldenrodyellow' self.axtime = plt.axes([0.1, 0.05, 0.8, 0.03], axisbg=axcolor) self.stime = Slider(self.axtime, 'Timestep', 0, len(res.resobj.fils.fid.dimensions['Time']), valinit=0) def update(val,res): t = self.stime.val res.refresh_plot(t) self.stime.on_changed(update(self,res)) def foward_button(self,res): self.fwdax = plt.axes([0.1, 0.1, 0.1, 0.04]) self.fwdb = Button(self.fwdax, 'forward', color='lightgoldenrodyellow', hovercolor='0.975') self.fwdb.on_clicked(slider.update(res.resobj.timestep-1,res))
def _init_ui(self): self.click_ev = self.fig.canvas.mpl_connect('button_press_event', self._onclick) self.motion_ev = self.fig.canvas.mpl_connect('motion_notify_event', self._onmotion) self.release_ev = self.fig.canvas.mpl_connect('button_release_event', self._onrelease) ax_load_img = self.fig.add_subplot(self.gs[1,:]) ax_load = self.fig.add_subplot(self.gs[2,0]) ax_save = self.fig.add_subplot(self.gs[2,1]) ax_reset = self.fig.add_subplot(self.gs[2,2]) self.fig.add_subplot(ax_load_img) self.fig.add_subplot(ax_load) self.fig.add_subplot(ax_save) self.fig.add_subplot(ax_reset) self._load_img_button = Button(ax_load_img, 'Load image') self._load_img_button.on_clicked(self._on_load_image) self._load_button = Button(ax_load, 'Load LMs') self._load_button.on_clicked(self._on_load_landmarks) self._save_button = Button(ax_save, 'Save LMs') self._save_button.on_clicked(self._on_save_landmarks) self._reset_button = Button(ax_reset, 'Reset LMs') self._reset_button.on_clicked(self._on_reset_landmarks)
def __init__(self, image_sequence): # Fix the size of subplot self.fig, self.axes = plt.subplots(2, sharey=True, figsize=(10, 5)) # Set background to be gray self.fig.patch.set_facecolor('#333333') # Store image sequence in self.seq and display the sequence self.seq = image_sequence self.image = self.seq.init_image() self.image2 = self.seq.init_image_original() self.image_figure = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=2) self.image_figure.axis('off') self.image_plot = self.image_figure.imshow(self.image) self.image_figure.set_title('Dinic', color='white') self.init_figure = plt.subplot2grid((3, 3), (2, 1)) self.init_figure.axis('off') self.init_plot = plt.imshow(self.image2) self.init_figure.set_title('Flow Graph', color = 'white' ) self.text_figure = plt.subplot2grid((3, 3), (2, 2)) self.text_figure.axis('off') self.text_figure.set_title('',color = 'white') plt.subplots_adjust(bottom=0.2) axnext = plt.axes([0.81, 0.05, 0.1, 0.075]) bnext = Button(axnext, 'Next') bnext.on_clicked(self.next) plt.show()
def __init__(self): '''variable definitions''' SEGMENTS = int(3) #number of segments #could probably make these lists instead of arrays self.l = np.array([0, 100, 100, 80])# actual measurements of segment length in mm self.w = np.array([0]*SEGMENTS,dtype=float) #horizontal coordinate self.z = np.array([0]*SEGMENTS,dtype=float) #vertical coordinate self.x = np.array([0]*SEGMENTS,dtype=float) #x axis components self.y = np.array([0]*SEGMENTS,dtype=float) #y axis components self.a = np.array([np.pi]*SEGMENTS,dtype=float) #angle for the link, reference is previous link self.gripper_angle = np.array([0, -45, -90, 45, 90])#preselected gripper angles self.current_gripper = 2 #gripper angle selection self.tw = 30.0 # w axis position depth self.tz = 20.0 # z axis starting position height self.l12 = 0.0 # hypotenuse belween a1 & a2 self.a12 = 0.0 #inscribed angle between hypotenuse, w self.fig = plt.figure("CS 4TE3 Robot Simulator") #create the frame self.ax = plt.axes([0.05, 0.2, 0.90, .75], projection='3d') #3d ax panel self.axe = plt.axes([0.25, 0.85, 0.001, .001])#panel for error message self.count = 0 self.coords = ((20,30),(50,60),(30,40),(70,100),(70,150)) self.display_error() self.draw_robot() butval = plt.axes([0.35, 0.1, 0.1, 0.075]) but = Button(butval, 'move') but.on_clicked(self.move_click) #error = dist(1,2); #print (error) plt.show()#end of constructor
class ButtonClickProcessor(object): def __init__(self, axes, label, color, viewer): self.groups = viewer.groups self.fig_text = viewer.fig_text self.button = Button(axes, label=label, color=color) self.button.on_clicked(self.print_group) def print_group(self, event): print(self.button.label.get_text()) group = self.groups[int(self.button.label.get_text())] self.fig_text.clf() self.ax_text = self.fig_text.add_subplot(111) # plt.rcParams['text.usetex'] = True y_write = np.linspace(0, 0.9, len(group.keys())) for ii, key in enumerate(group.keys()): self.ax_text.text(0, y_write[ii], str(key) + ' : ' + str(group[key]), fontsize=15, fontstyle='oblique') #Show it self.fig_text.canvas.draw()
def __init__(self, camera_matrix, dist_coeffs, homography, rvec, tvec, angspeed, center, axis): self.cm = camera_matrix self.dc = dist_coeffs self.homography = homography self.rvec = rvec self.tvec = tvec self.angspeed = angspeed self.center = center self.axis = axis # Socket self.HOST = "localhost" self.PORT = 8888 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Struct object for the linescan self.linescan_struct = struct.Struct(2048*'H') # Matplotlib plot setup self.fig = pylab.figure(1) self.ax = self.fig.add_subplot(111) self.ax.grid(True) self.ax.set_title('Linescan plotter') self.ax.axis([0, 2048, 1088, 0]) self.range = pylab.arange(0, 2048, 1) self.line1, = self.ax.plot(2048, 1088) self.manager = pylab.get_current_fig_manager() # Mouse input self.cid = self.fig.canvas.mpl_connect('button_press_event', self.on_click) # Buttons # Save button self.save_button_ax = pylab.axes([0.8, 0.91, 0.1, 0.075]) self.save_button = Button(self.save_button_ax, 'Save') self.save_button.on_clicked(self.save_scanlines) # Stop button self.stop_button_ax = pylab.axes([0.23, 0.91, 0.1, 0.075]) self.stop_button = Button(self.stop_button_ax, 'Stop') self.stop_button.on_clicked(self.stop_scan) # Start button self.start_button_ax = pylab.axes([0.125, 0.91, 0.1, 0.075]) self.start_button = Button(self.start_button_ax, 'Start') self.start_button.on_clicked(self.start_scan) # Timer thread self.timer = self.fig.canvas.new_timer(interval=20) self.timer.add_callback(self.callback, ()) self.timer.start() # Scan variables self.scan_range = [] self.scanlines = [] self.scanline_times = [] self.start_scan_time = None self.stop_scan_time = None self.scan_time = None self.scanning = False # Get transforms self.get_laser_to_turntable_transform() # Start pylab.show()
def __init__(self,*arg,**kwargs): """Optional parameters: - fig: the matplotlib figure to use ("current" if left blank) z-slice selector slider; otherwise use array index. """ fig = kwargs.get('fig', None ) if fig==None: fig = plt.gcf() self.fig=fig fig.clf() self.text = fig.text(0,.99,"",va='top') self.num = len(arg) self.row,self.col = [1,1] fig.subplots_adjust(left=0.05, bottom=0.25,top=0.95,right=0.95,wspace=0.1,hspace=0.15) args = [] self.zs = [] self.image_index = 0 # initialize using an array of images for a in arg: args.append(a) self.zs.append(np.arange(len(a))) maxz = max([max(z) for z in self.zs]) minz = min([min(z) for z in self.zs]) self.data = args self.im = [] self.ax = [] for i in range(len(self.data)): self.ax.append(fig.add_subplot(self.row,self.col,i+1)) self.im.append(self.ax[-1].imshow(self.data[i][0],origin='upper',cmap=cmap,aspect='equal')) self.cmap=cmap axcolor = 'lightgoldenrodyellow' self.sliceax = fig.add_axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) self.minax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) self.maxax = fig.add_axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor) self.sli = 0 self.sli_wid = Slider(self.sliceax, 'Slice', minz, maxz, valinit=minz,valfmt="%i") self.vmin = Slider(self.minax, 'min', 0, 100, valinit=0,valfmt="%i") self.vmax = Slider(self.maxax, 'max', 0, 100, valinit=100,valfmt="%i") self.sli_wid.on_changed(self.update) self.vmin.on_changed(self.update) self.vmax.on_changed(self.update) self.multi = XYMultiCursor(self.fig.canvas, self.ax, color='b', lw=1, ls=':') self.fig.canvas.mpl_connect('button_press_event',self.key) self.fig.canvas.draw() self.points = {} # defines the positions of the previous/next slice buttons axprev = plt.axes([0.81, 0.9, 0.1, 0.075]) axnext = plt.axes([0.81, 0.8, 0.1, 0.075]) self.bprev = Button(axprev, 'Previous') self.bnext = Button(axnext, 'Next') # previous/next slice select buttons self.bprev.on_clicked(self.next_image) self.bnext.on_clicked(self.prev_image) pprint(self.data[0][0])
class MButton(object): """Custom button.""" def __init__(self, fig, rect, label, func, fargs=None, c='#0DE51B', hc='#5CFF67'): """init function Parameters: fig: matplotlib.figure.Figure instance rect: [left, bottom, width, height] each of which in 0-to-1-fraction i.e. 0<=x<=1 label: string button label func: function function called when button is clicked fargs: array, optional, default: None (optional) arguments for func c: a matplotlib color i.e. string color i.e. background color hc: a matplotlib color i.e. string hovercolor i.e. background color when cursor is on button """ self.fig = fig self._rect = rect self._label = label self._func = func self._fargs = fargs self.axes = self.fig.add_axes(rect) self.button = Button(self.axes, label, color=c, hovercolor=hc) self.button.label.set_fontsize('x-small') self.button.label.set_family('monospace') self.button.on_clicked(self._onclick) def _onclick(self, wtf): """Actual function called when button is clicked.""" if self.get_visible(): if self._func is not None: # not necessary if self._fargs is not None: self._func(*self._fargs) else: self._func() self.fig.canvas.draw() def set_visible(self, b): """Set its visibility. Parameters: b: boolean """ self.axes.set_visible(b) def get_visible(self): """Get its visibility. Returns: b b: boolean """ return self.axes.get_visible()
def __init__(self, interval=1): self.interval = interval self.fig, self.ax = plt.subplots() self.ax.set_xlim(-2.6, 2.6) self.ax.set_ylim(-2, 2) plt.subplots_adjust(left=0.25, bottom=0.25) self.line, = self.ax.plot([], [], lw=.5); self.c1line, = self.ax.plot([], [], lw=.5); self.c2line, = self.ax.plot([], [], lw=.5); self.xdata, self.ydata = [], [] self.frame = 0 # [left, bottom, width, height] in normalized (0, 1) units w = 0.1 h = 0.03 l0 = 0.05 dl = 0.2 b0 = 0.05 db = 0.05 self.slider = dict() # r1, r2 # xr1 xw1 xp1 # xr2 xw2 xp2 # yr1 yw1 yp1 # yr2 yw2 yp2 p2 = np.pi * 2 sliders = ((0, 0, 0, 2, 1.5, 'r1'), (0, 1, 0, 2, 1.5, 'r2'), (1, 0, 0, 2, 1, 'xr1'), (1, 1, 0, .1, .01, 'xw1'), (1, 2, 0, p2, 0, 'xp1'), (2, 0, 0, 2, 0.3, 'xr2'), (2, 1, 0, .1, 0.05, 'xw2'), (2, 2, 0, p2, 0, 'xp2'), (3, 0, 0, 2, 1, 'yr1'), (3, 1, 0, .1, 0.01, 'yw1'), (3, 2, 0, p2, 1.5, 'yp1'), (4, 0, 0, 2, 0.3, 'yr2'), (4, 1, 0, .1, 0.05, 'yw2'), (4, 2, 0, p2, 0, 'yp2')) for x, y, v0, v1, vi, n in sliders: l = x * dl + l0 b = y * db + b0 ax = plt.axes([l, b, w, h]) self.slider[n] = Slider(ax, n, v0, v1, valinit=vi) ax = plt.axes([0, 0.5, 0.1, 0.04]) self.rndbut = Button(ax, 'Rand') self.rndbut.on_clicked(self.rand) ax = plt.axes([0, 0.6, 0.1, 0.04]) self.resetbut = Button(ax, 'Reset') self.resetbut.on_clicked(self.init) ax = plt.axes([0, 0.7, 0.1, 0.04]) self.savebut = Button(ax, 'Save') self.savebut.on_clicked(self.save)
def __init__(self, scope): self.num_events = scope.num_events self.event_ind = 0 self.toggle_volts = True self.toggle_offset = False self.fig = mp.subplot(2, 2, 1) xlabel('Time (s)') ylabel('Volts (V)') self.num_waves = scope.events[self.event_ind].num_waves self.lines = [] for wave_ind in range(self.num_waves): y = scope.events[self.event_ind].waves[wave_ind].volts t = scope.events[self.event_ind].waves[wave_ind].times line, = plot(t, y, label = 'Channel ' + str(wave_ind+1) ) legend() self.lines.append(line) self.fig2 = mp.subplot(2, 2, 2) xlabel('Frequency (Hz)') ylabel('Power (dB)') self.lines2 = [] for wave_ind in range(self.num_waves): p = scope.events[self.event_ind].waves[wave_ind].pow_spec_dB f = scope.events[self.event_ind].waves[wave_ind].freqs line, = plot(f, p, label = 'Channel ' + str(wave_ind+1) ) self.lines2.append(line) legend() self.fig3 = mp.subplot(2, 2, 3) self.fig3.set_title(scope_name + ' Event Header Information') axis('off') self.info = [] self.update() self.axprev = mp.axes([0.7, 0.05, 0.1, 0.075]) self.axnext = mp.axes([0.81, 0.05, 0.1, 0.075]) self.axvolt = mp.axes([0.1, 0.05, 0.1, 0.075]) self.axoff = mp.axes([0.19, 0.05, 0.1, 0.075]) self.bnext = Button(self.axnext, 'Next') self.bnext.on_clicked(self.next) self.bprev = Button(self.axprev, 'Previous') self.bprev.on_clicked(self.prev) self.bvolts = Button(self.axvolt, 'Volts/ADC') self.bvolts.on_clicked(self.volts_toggle) self.bvoff = Button(self.axoff, 'Offset') self.bvoff.on_clicked(self.offset_toggle) mp.show()
def main(argv): """Test maximum density.""" print(len(argv)) if len(argv) < 1: shot_number=int(open('shot_number.txt','r').read()) else: if (len(argv) == 1) & ("py" in argv[0]): shot_number=int(open('shot_number.txt','r').read()) else: shot_number = int(argv[1]) fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.25) shot = ppb.ProcProfile(shot_number) shot.reference_gd(all_shot=1) cluster = 20 shot.plasma_gd(1, cluster, 1) ax.pcolormesh(shot.X['K'], shot.Y['K'], shot.matrix_k_mean) ax.pcolormesh(shot.X['Ka'], shot.Y['Ka'], shot.matrix_ka_mean) plt.plot(shot.X['K'], shot.Y['K'][shot.matrix_k_mean.argmax(axis=0)] - 3.36, color='b', linewidth=2.0) plt.plot(shot.X['Ka'], shot.Y['Ka'][shot.matrix_ka_mean.argmax(axis=0)] - 3.36, color='b', linewidth=2.0) plt.plot(shot.X['K'], shot.Y['K'][shot.matrix_k_mean.argmax(axis=0)], color='b', linewidth=2.0) plt.plot(shot.X['Ka'], shot.Y['Ka'][shot.matrix_ka_mean.argmax(axis=0)], color='b', linewidth=2.0) l, = plt.plot(shot.X['K'], shot.Y['K'][shot.matrix_k_mean.argmax(axis=0)], color='r', linewidth=2.0) m, = plt.plot(shot.X['Ka'], shot.Y['Ka'][shot.matrix_ka_mean.argmax(axis=0)], color='r', linewidth=2.0) plt.xlabel("freq (GHz)") plt.ylabel("group delay (ns)") plt.title("# %s - time: %s ms" % (shot.shot, shot.sweep2time(shot.sweep_cur))) plt.ylim(0, 12) plt.xlim(shot.X['K'].min(), shot.X['Ka'].max()) axcolor = 'lightgoldenrodyellow' axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) sweep = Slider(axfreq, 'Sweep', 1, len(shot.points) - 1 - cluster, valinit=1, valfmt='%1.f') def update(val): shot.plasma_gd(int(sweep.val), cluster, 1) ax.pcolormesh(shot.X['K'], shot.Y['K'], shot.matrix_k_mean) ax.pcolormesh(shot.X['Ka'], shot.Y['Ka'], shot.matrix_ka_mean) l.set_ydata(shot.Y['K'][shot.matrix_k_mean.argmax(axis=0)]) m.set_ydata(shot.Y['Ka'][shot.matrix_ka_mean.argmax(axis=0)]) ax.set_title("# %s - time: %.3f ms" % (shot.shot, shot.sweep2time(shot.sweep_cur))) fig.canvas.draw_idle() sweep.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): sweep.reset() button.on_clicked(reset) plt.show()
def connect(self): self.axfron = self.axs['Fron'] self.axprev = self.axs['Prev'] self.axnext = self.axs['Next'] self.axlast = self.axs['Last'] self.axzoba = self.axs['Zoba'] self.axshdo = self.axs['Shdo'] self.axshfp = self.axs['Shfp'] self.axshod = self.axs['Shod'] self.axquit = self.axs['Quit'] self.bnfron = Button(self.axfron, 'Front') self.bnprev = Button(self.axprev, 'Prev') self.bnnext = Button(self.axnext, 'Next') self.bnlast = Button(self.axlast, 'Last') self.bnzoba = Button(self.axzoba, 'Zoom \n Back') self.bnshdo = Button(self.axshdo, 'Save') self.bnshfp = Button(self.axshfp, 'Save \n Params') self.bnshod = Button(self.axshod, 'Save \n Override') self.bnquit = Button(self.axquit, 'Quit') self.cidfron = self.bnfron.on_clicked(self.fron) self.cidprev = self.bnprev.on_clicked(self.prev) self.cidnext = self.bnnext.on_clicked(self.next) self.cidlast = self.bnlast.on_clicked(self.last) self.cidzoba = self.bnzoba.on_clicked(self.zoba) self.cidshdo = self.bnshdo.on_clicked(self.shdo) self.cidshfp = self.bnshfp.on_clicked(self.shfp) self.cidshod = self.bnshod.on_clicked(self.shod) self.cidquit = self.bnquit.on_clicked(self.quit) self.cidpress = self.axpp.figure.canvas.mpl_connect('key_press_event', self.on_zoom)
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()
else: l2.set_ydata( np.sqrt(a1**2 + a2**2 + 2 * a1 * a2 * s(t, f2 - 1, 1, phi))) # elif(a1>a2): # l2.set_ydata(np.abs(a1-a2)+np.abs(s(t,(f2-1)/2.0,2*a2,phi/2.0))) # else: # l2.set_ydata(np.abs(a2-a1)+np.abs(s(t,(f2-1)/2.0,2*a1,phi/2.0))) ax.axes.axis([0, 100, 1.1 * min(y), 1.1 * max(y)]) py.draw() sld_amplitude1 = py.axes([0.2, 0.1, 0.7, 0.03], axisbg='grey') sld_amplitude2 = py.axes([0.2, 0.15, 0.7, 0.03], axisbg='grey') sld_frequence2 = py.axes([0.2, 0.2, 0.7, 0.03], axisbg='grey') sld_phase2 = py.axes([0.2, 0.25, 0.7, 0.03], axisbg='grey') amplitude1 = Slider(sld_amplitude1, 'amplitude 1', 0.0, 2.0, valinit=1) amplitude2 = Slider(sld_amplitude2, 'amplitude 2', 0, 2.0, valinit=1) frequence2 = Slider(sld_frequence2, r'$f_2/f_1$', 0.9, 1.1, valinit=1) phase = Slider(sld_phase2, r'$\varphi_2-\varphi_1$', 1, 5.0, valinit=0) button_demarre = py.axes([0.7, 0.02, 0.2, 0.05]) button = Button(button_demarre, 'animation', color='grey', hovercolor='white') button.on_clicked(rebond) py.show() os.system("pause")
def __init__(self, print_manager, combo_prints, hulls_df, print_numb, vid_panel, invert_axes=True): self.root = tk.Tk() self.root.wm_title("Split the Selected Print") self.fig = Figure(figsize=(10, 8), dpi=100) self.canvas = FigureCanvasTkAgg(self.fig, master=self.root) # A tk.DrawingArea. self.canvas.draw() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.root) self.toolbar.update() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.print_manager = print_manager self.combo_prints = combo_prints self.print_numb = print_numb self.first_frame = self.combo_prints.first_frame[print_numb] n_frames = (self.combo_prints.last_frame[print_numb] - self.first_frame) + 1 grid_size = int(np.ceil(np.sqrt(n_frames))) self.axes = [] self.fig.set_size_inches(16, 9) button_axes = self.fig.add_axes([.01, .01, .05, .05]) self.button = Button(button_axes, 'Split') self.button.on_clicked(self.create_new_hulls) these_hulls = hulls_df[hulls_df.print_numb == print_numb] self.collections = {} self.xyes = {} for i in range(0, n_frames): ax = self.fig.add_subplot(grid_size, grid_size, i + 1) self.axes.append(ax) ax.set_axis_off() frame = vid_panel.get_frame(self.first_frame + i) X = self.combo_prints.X[print_numb] Y = self.combo_prints.Y[print_numb] ax.imshow(frame) xes = [] yes = [] for c in (these_hulls.contours[these_hulls.frame == self.first_frame + i].values[0]): #add all to a single list to make one collection xes = xes + list(c[:, 0, 0]) yes = yes + list(c[:, 0, 1]) self.collections[ax] = ax.scatter(xes, yes) self.xyes[ax] = self.collections[ax].get_offsets() #set it to have list of facecolors so that selection works facecolors = self.collections[ax].get_facecolors() npts = len(self.xyes[ax]) facecolors = np.tile(facecolors, npts).reshape(npts, -1) self.collections[ax].set_facecolor(facecolors) if invert_axes: ax.set_xlim(X + 50, X - 50) else: ax.set_xlim(X - 50, X + 50) ax.set_ylim(Y - 50, Y + 50) ax.set_title('Frame ' + str(self.first_frame + i)) self.axes = np.asarray(self.axes) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.canvas.draw() tk.mainloop()
# Add a time slider if len(all_times) > 1: axfreq = plt.axes([0.1, 0.0, 0.5, 0.03]) time_slider = Slider(axfreq, 'ix', 0., len(all_times) - 1, 0.) time_slider.on_changed(update) # Add buttons to go to next/previous variable and snapshot, and one to switch # between primitive axprev_iw = plt.axes([0.8, 0.0, 0.075, 0.05]) axnext_iw = plt.axes([0.875, 0.0, 0.075, 0.05]) axprim = plt.axes([0.95, 0.0, 0.05, 0.05]) axprev_file = plt.axes([0.0, 0.0, 0.05, 0.05]) axnext_file = plt.axes([0.7, 0.0, 0.05, 0.05]) bnext_iw = Button(axnext_iw, '+iw') bnext_iw.on_clicked(next_var) bprev_iw = Button(axprev_iw, '-iw') bprev_iw.on_clicked(prev_var) bnext_file = Button(axnext_file, '+') bnext_file.on_clicked(next_file) bprev_file = Button(axprev_file, '-') bprev_file.on_clicked(prev_file) bprim = Button(axprim, 'P/C') bprim.on_clicked(switch_cons_prim) # Initial state i_var = 1 i_file = 0 is_conservative = True
def held_karp(dists): """ Implementation of Held-Karp, an algorithm that solves the Traveling Salesman Problem using dynamic programming with memoization. Parameters: dists: distance matrix Returns: A tuple, (cost, path). """ n = len(dists) C = {} for k in range(1, n): C[(1 << k, k)] = (dists[0][k], 0) for subset_size in range(2, n): for subset in itertools.combinations(range(1, n), subset_size): # Set bits for all nodes in this subset bits = 0 for bit in subset: bits |= 1 << bit # Find the lowest cost to get to this subset for k in subset: prev = bits & ~(1 << k) res = [] for m in subset: if m == 0 or m == k: continue res.append((C[(prev, m)][0] + dists[m][k], m)) C[(bits, k)] = min(res) bits = (2**n - 1) - 1 res = [] for k in range(1, n): res.append((C[(bits, k)][0] + dists[k][0], k)) opt, parent = min(res) path = [] for i in range(n - 1): path.append(parent) new_bits = bits & ~(1 << parent) _, parent = C[(bits, parent)] bits = new_bits path.append(0) return opt, list(reversed(path)) def solve(event): global n, trucks, solver, li, ax, warehouses, loc_x, loc_y, lines_x, lines_y, obj_value, exec_value global distances, distances2 print("solving...") ax.clear() ax.set_xlim(0,1000) ax.set_ylim(0,1000) plot_data(ax, loc_x, loc_y, warehouses) ax.text(400, 1075, "solving...", family="serif", horizontalalignment='left', verticalalignment='top') plt.draw() fig.canvas.draw() start_time = time.time() # Calculate constraint for Li total_l = 0 total_c = 0.0 paths = 0 slack = False while total_c < n or paths < trucks: c1 = min(c,n) total_c += c1 total_l += c1*(c1+1)/2 paths += 1 if total_c > n: slack = True if solver=="cbc" or solver=="glpk" or solver=="gurobi": # Objective function z = pulp.LpProblem('Test', pulp.LpMinimize) # Generate decision variables x = {} y = {} variables = [] l = {} s = {} for i in range(n+warehouses): for j in range(n+warehouses): if i==j: continue x[i,j] = pulp.LpVariable('x_' + str(i) + '_' + str(j), 0, 1, pulp.LpInteger) if i >= warehouses: l[i] = pulp.LpVariable('l_' + str(i), 1, min(n,c), pulp.LpInteger) # Objective function z += pulp.lpSum([distances[i][j] * x[i,j] for i in range(n+warehouses) for j in list(range(i)) + list(range(i+1,n+warehouses))]) # Constraints constraintSeq = [] constraintTrucks = [] for i in range(n+warehouses): if i>=warehouses: constraintSeq.append(l[i]) constraintFrom = [] constraintTo = [] for j in range(n+warehouses): if i==j: continue if i>=warehouses and j>=warehouses: z += pulp.lpSum([l[i], -1*l[j], n*x[i,j], -n+1]) <= 0 if i>=warehouses: constraintFrom.append(x[i,j]) constraintTo.append(x[j,i]) if i<warehouses: constraintTrucks.append(x[j,i]) if i>=warehouses: z += pulp.lpSum(constraintFrom) == 1 # paths from location z += pulp.lpSum(constraintTo) == 1 # paths to location if i==warehouses and (paths > 1 or warehouses>1): z += pulp.lpSum(constraintTrucks) == paths # paths to warehouse if not slack: z += pulp.lpSum(constraintSeq) == total_l else: z += pulp.lpSum(constraintSeq) <= total_l # Solve if solver=="cbc": status = z.solve() if solver=="glpk": status = z.solve(pulp.GLPK()) if solver=="gurobi": status = z.solve(pulp.GUROBI_CMD()) # should be 'Optimal' if pulp.LpStatus[status]!="Optimal": print("RESULT: ".pulp.LpStatus[status]) print("Objective function value: "+str(z.objective.value())) # Print variables & save path lines_x = [] lines_y = [] li = [0] * n for i in range(n+warehouses): if i>=warehouses: li[i-warehouses] = pulp.value(l[i]) for j in range(n+warehouses): if i==j: continue if pulp.value(x[i,j]) == 1: lines_x.append(loc_x[i]) lines_x.append(loc_x[j]) lines_y.append(loc_y[i]) lines_y.append(loc_y[j]) lines_x.append(np.nan) lines_y.append(np.nan) obj_value = "c=" + str(round(z.objective.value(),2)) elif solver=="cut plane": model = Model("tsp") model.hideOutput() x = {} l = {} for i in range(n+warehouses): for j in range(n+warehouses): if i != j: x[i,j] = model.addVar(ub=1, name="x(%s,%s)"%(i,j)) if (paths > 1 or warehouses > 1) and i >= warehouses: l[i] = model.addVar(ub=min(c,n),lb=1, name="l(%s)"%(i)) if paths == 1 and warehouses == 1: # SYMMETRIC DISTANCE MATRIX ONLY #for i in range(n+warehouses): #model.addCons(quicksum(x[j,i] for j in range(n+warehouses) if j != i) + \ # quicksum(x[i,j] for j in range(n+warehouses) if j != i) == 2,"Degree(%s)"%i) # ASYMMETRIC DISTANCE MATRIX for i in range(n+warehouses): model.addCons(quicksum(x[j,i] for j in range(n+warehouses) if j != i) == 1,"In(%s)"%i) model.addCons(quicksum(x[i,j] for j in range(n+warehouses) if j != i) == 1,"Out(%s)"%i) else: for i in range(warehouses, n+warehouses): model.addCons(quicksum(x[j,i] for j in range(n+warehouses) if j != i) == 1,"In(%s)"%i) model.addCons(quicksum(x[i,j] for j in range(n+warehouses) if j != i) == 1,"Out(%s)"%i) for i in range(warehouses, n+warehouses): for j in range(warehouses, n+warehouses): if i!=j: model.addCons(l[i] -l[j] +n*x[i,j] <= n-1, "Li(%s,%s)"%(i,j)) model.addCons(quicksum(x[j,i] for i in range(warehouses) for j in range(n+warehouses) if i!=j) == paths, "Paths(%s)"%paths) if not slack: model.addCons(quicksum(l[i] for i in range(warehouses,n+warehouses)) == total_l,"TotalL") else: model.addCons(quicksum(l[i] for i in range(warehouses,n+warehouses)) <= total_l, "TotalL") model.setObjective(quicksum(distances2[i,j]*x[i,j] for (i,j) in x), "minimize") EPS = 1.e-6 isMIP = False model.setPresolve(SCIP_PARAMSETTING.OFF) while True: model.optimize() #edges = [] lines_x = [] lines_y = [] edges = [] li = [0] * n for (i,j) in x: # i=j already skipped if model.getVal(x[i,j]) > EPS: #edges.append( (i,j) ) lines_x.append(loc_x[i]) lines_x.append(loc_x[j]) lines_y.append(loc_y[i]) lines_y.append(loc_y[j]) lines_x.append(np.nan) lines_y.append(np.nan) edges.append( (i,j) ) if paths>1 or warehouses>1: for i in range(warehouses, n+warehouses): li[i-warehouses] = int(model.getVal(l[i])) obj_value = "c=" + str(round(model.getObjVal(),2)) ax.clear() ax.set_xlim(0,1000) ax.set_ylim(0,1000) plot_data_lines(lines_x,lines_y) plot_data(ax, loc_x, loc_y, warehouses) ax.text(400, 1075, "solving...", family="serif", horizontalalignment='left', verticalalignment='top') fig.canvas.draw() if addcut(edges,model,x,warehouses) == False: if isMIP: # integer variables, components connected: solution found break model.freeTransform() for (i,j) in x: # all components connected, switch to integer model model.chgVarType(x[i,j], "B") if paths > 1 or warehouses > 1: for i in range(warehouses,n+warehouses): model.chgVarType(l[i], "I") isMIP = True sol_li = [0] * (n+warehouses) sol_xij = {} print('solved.') elif solver == 'held-karp': li = [0] * n opt, path = held_karp(distances) print(path) obj_value = "c=" + str(round(opt,2)) x = [[0 for x in range(n+warehouses)] for y in range(n+warehouses)] for idx, val in enumerate(path): if idx < (len(path)-1): x[val][path[idx+1]] = 1; elif idx == (len(path)-1): x[val][path[0]] = 1; for i in range(n+warehouses): for j in range(n+warehouses): if x[i][j] == 1: #edges.append( (i,j) ) lines_x.append(loc_x[i]) lines_x.append(loc_x[j]) lines_y.append(loc_y[i]) lines_y.append(loc_y[j]) lines_x.append(np.nan) lines_y.append(np.nan) #edges.append( (i,j) ) # Print computation time time2 = time.time() - start_time exec_value = time2 units = 'secs' if time2 > 60: time2 /= 60 units = 'mins' if time2 > 60: time2 /= 60 units = 'hours' time2 = round(time2,2) exec_value = "exec=" + str(time2) + " " + units print("--- " + str(time2) + " " + units + " ---") # Redraw points ax.clear() ax.set_xlim(0,1000) ax.set_ylim(0,1000) plot_data_lines(lines_x,lines_y) plot_data(ax, loc_x, loc_y, warehouses) ax.text(350, 1075, obj_value, family="serif", horizontalalignment='right', verticalalignment='top') ax.text(450, 1075, exec_value, family="serif", horizontalalignment='left', verticalalignment='top') fig.canvas.draw() axsolve = plt.axes([0.87, 0.905, 0.1, 0.075]) bsolve = Button(axsolve, 'Solve') bsolve.on_clicked(solve) plt.show()
def init_graphes(self): ''' Inititialise les graphiques ''' ### IMAGE REMUTRACE image_capteur = plt.imread('capteur.png') self.image_capteur_plot = self.fig.add_subplot(233) self.image_capteur_plot.set_axis_off() self.image_capteur_plot.imshow(image_capteur) ### 3D (non implementé) #self.3D = figure3D().add_subplot(233) #self.3D = self.fig.add_subplot(233) ### GRAPHE XYZ #self.xyz=self.fig.add_subplot(231) #self.xyz.set_xlabel('Temps') #self.xyz.set_ylabel('x,y,z') #self.xyz.plot(self.dates, self.acc_Xs, label='acc_X') #self.xyz.plot(self.dates, self.acc_Ys, label='acc_Y') #self.xyz.plot(self.dates, self.acc_Zs, label='acc_Z') #self.xyz.legend() #self.xyz_line = False ### GRAPHE GxGyGz self.GxGyGz = self.fig.add_subplot(231) #, sharex = self.xyz) self.GxGyGz.set_title(u'Vitesse angulaire') self.GxGyGz.set_xlabel(u'Temps') self.GxGyGz.set_ylabel(u'Deg/s') self.GxGyGz.plot(self.dates, self.gyro_Xs, label='gyro_X') self.GxGyGz.plot(self.dates, self.gyro_Ys, label='gyro_Y') self.GxGyGz.plot(self.dates, self.gyro_Zs, label='gyro_Z') #self.GxGyGz.set_xticks(self.dates) self.GxGyGz.xaxis.set_major_locator(mdates.DayLocator()) #self.GxGyGz.xaxis.set_minor_locator(mdates.HourLocator()) self.GxGyGz.xaxis.set_major_formatter( ticker.FormatStrFormatter("%d %b")) self.GxGyGz.legend() self.GxGyGz_line = False #self.fig.autofmt_xdate() #plt.xticks(rotation=90) logging.debug("GRAPHE GxGyGz ok") ### GRAPHE INCLINAISON self.Inclinaison = self.fig.add_subplot(234, sharex=self.GxGyGz) self.Inclinaison.plot(self.dates, self.angle_Ys, label='Inclinaison') #self.Inclinaison.legend() self.Inclinaison.set_title(u'Inclinaison') self.Inclinaison.set_xlabel(u'Temps') self.Inclinaison.set_ylabel(u'Deg') self.Inclinaison_line = False ### GRAPHE ROTATION self.Rotation = self.fig.add_subplot(235, sharex=self.GxGyGz) self.Rotation.plot(self.dates, self.angle_Xs, label='Rotation') #self.Rotation.legend() self.Rotation.set_title(u'Rotation') self.Rotation.set_xlabel(u'Temps') self.Rotation.set_ylabel(u'Deg') self.Rotation_line = False ### PHOTO self.image_plot = self.fig.add_subplot(232) self.image_plot.set_axis_off() self.image_plot.set_title(u'Caméra') ### BOUTONS self.fig.canvas.mpl_connect('button_press_event', self.on_click) self.bt_lecture = Button(plt.axes([0.65, 0.3, 0.05, 0.03]), 'lecture') self.bt_lecture.on_clicked(self.on_bt_lecture_click) self.bt_lecture10 = Button(plt.axes([0.65, 0.2, 0.05, 0.03]), 'lecturex10') self.bt_lecture10.on_clicked(self.on_bt_lecture_click10) #self.tb_vitesse = TextBox(plt.axes([0.9, 0.8, 0.05, 0.03]),'Vitesse', initial = '1') #self.tb_vitesse.on_submit(self.on_tb_vitesse_submit) ### Détail étape axe_etape = self.fig.add_axes([0.65, 0.4, 0.03, 0.03]) axe_etape.set_axis_off() self.etape = plt.text(0, 3, u'Etape n° ?') self.etape_debut_mvt = plt.text(0, 2, u'Début : --') self.etape_fin_mvt = plt.text(0, 1, u'Fin : --') self.etape_acceleration_max = plt.text(0, 0, u'Accélération max : --') ### LEGENDE : FILEUROPE-CMP legende = self.fig.add_axes([0.75, 0.07, 0.2, 0.3]) legende.set_axis_off() #rect = Rectangle((0,0),1,1,fill=True, color= 'blue') #legende.add_patch(rect) logo_img = plt.imread('logo.png') legende.imshow(logo_img) text_legende = plt.text(0.05, 0.05, u"Remutrace - Brevet déposé.") self.fig.canvas.mpl_connect('key_press_event', self.press)
ax[i].set_xlabel('Freq (MHz)') ax[i].set_yticklabels([]) ax[i].yaxis_date() ax[0].set_ylabel('Local Time') ax[0].yaxis_date() ax[0].yaxis.set_major_formatter(date_format) cbar_ax = f.add_axes([0.85, 0.15, 0.05, 0.7]) c = f.colorbar(p[0], cax=cbar_ax) c.set_label('Power (dB, arbitrary)') from matplotlib.widgets import Slider, Button rax = plt.axes([0.82, 0.03, 0.15, 0.04]) check = Button(rax, 'Med Subtract') def func(event): global medsub, check, colorscale medsub = not medsub if medsub: check.label.set_text("Med Subtracted") colorscale = [-0.5, 0.5] else: check.label.set_text("Raw Power") colorscale = [-10, 10] check.on_clicked(func)
def submit(self): if (self.type == game.SheetType.MATCH): #If the match is empty, reset the data and display fields if self.matchData['Team'] == 0: print("Found an empty match, skipping") self.matchData = dict(game.SCOUT_FIELDS) self.display = cv2.cvtColor(self.sheet, cv2.COLOR_GRAY2BGR) return #Open the database and check if the match has already been processed datapath = 'data_' + CURRENT_EVENT + '.db' conn = sql.connect(datapath) conn.row_factory = sql.Row cursor = conn.cursor() history = cursor.execute( 'SELECT * FROM scout WHERE Team=? AND Match=?', (str(self.matchData['Team']), str( self.matchData['Match']))).fetchall() if history and not self.matchData['Replay']: print("Already processed this match, skipping") self.data = dict(game.SCOUT_FIELDS) self.display = cv2.cvtColor(self.sheet, cv2.COLOR_GRAY2BGR) return elif (self.type == game.SheetType.PIT): if self.pitData['Team'] == 0: print("Found an empty pit sheet, skipping") self.pitData = dict(game.PIT_SCOUT_FIELDS) self.display = cv2.cvtColor(self.sheet, cv2.COLOR_GRAY2BGR) return datapath = 'data_' + CURRENT_EVENT + '.db' conn = sql.connect(datapath) conn.row_factory = sql.Row cursor = conn.cursor() history = cursor.execute('SELECT * FROM pitScout WHERE Team=?', (str(self.pitData['Team']), )).fetchall() if history: print("Already processed this team, skipping") self.pitData = dict(game.PIT_SCOUT_FIELDS) self.display = cv2.cvtColor(self.sheet, cv2.COLOR_GRAY2BGR) return #Create and open the GUI to verify data print("Found new data, opening") output = '' if self.type == game.SheetType.MATCH: for key, value in self.matchData.items(): output += key + "=" + str(value) + '\n' elif self.type == game.SheetType.PIT: for key, value in self.pitData.items(): output += key + "=" + str(value) + '\n' fig = plt.figure('PiScout') fig.subplots_adjust(left=0, right=0.6) plt.subplot(111) plt.imshow(self.display) plt.title('Scanned Sheet') plt.text(600, 784, output, fontsize=12) upload = Button(plt.axes([0.68, 0.31, 0.15, 0.07]), 'Upload Data') upload.on_clicked(self.upload) save = Button(plt.axes([0.68, 0.24, 0.15, 0.07]), 'Save Data Offline') save.on_clicked(self.save) edit = Button(plt.axes([0.68, 0.17, 0.15, 0.07]), 'Edit Data') edit.on_clicked(self.edit) cancel = Button(plt.axes([0.68, 0.1, 0.15, 0.07]), 'Cancel') cancel.on_clicked(self.cancel) mng = plt.get_current_fig_manager() try: mng.window.state('zoomed') except AttributeError: print("Window resizing exploded, oh well.") plt.show() self.matchData = dict(game.SCOUT_FIELDS) self.pitData = dict(game.PIT_SCOUT_FIELDS) self.display = cv2.cvtColor(self.sheet, cv2.COLOR_GRAY2BGR)
class simulate(): """ Class that simulates a dvhb object based on diferent inputs in sliders obs: funtions for this class are only used by the class itself and will not work outside of animation context args: dvhb: dvhb object already configured with mtrix and joints returns: perform the simulation of the robot with sliders to represent the inputs of the joint """ def __init__(self, dvhb): from IPython import get_ipython ipy = get_ipython() if ipy != None: ipy.run_line_magic('matplotlib', 'auto') self.dvhb = deepcopy(dvhb) self.limits = self.get_limits() self.scale = self.limits[1] * 0.1 self.fig = plt.figure() self.ax = self.fig.add_subplot(111, projection='3d') plt.subplots_adjust(left=0.25, bottom=0.40, top=1) self.variables = [] for n, variable in enumerate(self.dvhb.joints): joint_slider_loc = plt.axes([0.25, 0.30 - 0.05 * n, 0.65, 0.03], facecolor=axcolor) if variable[1] == "r": joint = Slider(joint_slider_loc, f'Joint {variable[0]}', 0, 360, valinit=self.dvhb.get_curr_theta(variable[0])) elif variable[1] == "t": joint = Slider(joint_slider_loc, f'Joint {variable[0]}', 0, 5, valinit=self.dvhb.get_curr_d(variable[0])) joint.on_changed(self.update) self.variables.append(joint) resetax = plt.axes([0.1, 0.4, 0.1, 0.04]) self.button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') self.button.on_clicked(self.reset) self.update(None, init=True) plt.show() def get_limits(self): # Verifica quais são todos os pontos de dados all_points = [] for cordsys in trace(self.dvhb.to_cordsys()): all_points.append(cordsys[:3, 3]) all_points = np.array(all_points) maxs, mins = all_points.max(axis=0), all_points.min(axis=0) abs_max = max(max(abs(maxs)), min(abs(mins))) vec_scale = 0.1 * abs_max space = 2 * vec_scale return [-abs_max - space, abs_max + space] def get_points(self): # Verifica quais são todos os pontos de dados all_points = [] for cordsys in trace(self.dvhb.to_cordsys()): all_points.append(cordsys[:3, 3]) all_points = np.array(all_points) # Liga os pontos com uma linha return [all_points[:, 0], all_points[:, 1], all_points[:, 2]] def update(self, val, init=False): if not init: new_pos = [variable.val for variable in self.variables] self.dvhb.recalculate_joints(new_pos) x, y, z = self.get_points() self.ax.cla() # For the body of the robot self.ax.plot(x, y, z, lw=2) self.ax.plot(x[1:], y[1:], z[1:], "bo") # For the origin marker self.ax.plot([0], [0], [0], "ro") # For the coodnates in the tip of the robot matrix = self.dvhb.final_position() cord_x = matrix[:3, 0] cord_y = matrix[:3, 1] cord_z = matrix[:3, 2] x, y, z = matrix[:3, 3] self.ax.quiver(x, y, z, *cord_x * self.scale, color="red") self.ax.quiver(x, y, z, *cord_y * self.scale, color="green") self.ax.quiver(x, y, z, *cord_z * self.scale, color="blue") # For the ax limits self.ax.set_xlim(*self.limits) self.ax.set_ylim(*self.limits) self.ax.set_zlim(*self.limits) # For the ax labels self.ax.set_xlabel("X") self.ax.set_ylabel("Y") self.ax.set_zlabel("Z") self.fig.canvas.draw_idle() plt.pause(0.0001) def reset(self, event): for variable in self.variables: variable.reset()
# False negative else: errors.append(fn) # Correct prediction else: errors.append(0) total_error = sum(errors) results.append((total_error, threshold)) optimal_p = sorted(results)[0][1] optimal_costs = sorted(results)[0][0] print('Optimal probability threshold = {} \twith costs = {}'.format(round(optimal_p, 4), round(optimal_costs, 1))) y, x = zip(*results) l.set_ydata(y) fig.canvas.draw_idle() c_fp.on_changed(update) c_fn.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): c_fp.reset() c_fn.reset() button.on_clicked(reset) plt.show()
if state == 3: if adjacent[1]: prex, prey = random.choice(adjacent[1]) states[prex][prey] = 3 ages[prex][prey] = age + 1 ages[i][j] = age + 1 lock.release() age = age + 1 sleep(0.01) rabbit_slider = Slider(plt.axes([0.25, 0.15, 0.65, 0.03]), 'Rabbits starting population', 0.0, 1.0, valinit=0.2) wolf_slider = Slider(plt.axes([0.25, 0.10, 0.65, 0.03]), 'Wolves starting population', 0.0, 1.0, valinit=0.05) start_button = Button(plt.axes([0.10, 0.05, 0.1, 0.03]), 'Start') setup(0.2, 0.05) t1 = threading.Thread(target=show) t2 = threading.Thread(target=draw) t1.start() t2.start() def update(val): rabbits_population = rabbit_slider.val wolves_population = wolf_slider.val ax.clear() ax.axis('off') lock.acquire() setup(rabbits_population, wolves_population) lock.release()
min_y = data.min() max_y = data.max() ax2.set_ylim(min_y, max_y) from matplotlib.widgets import Button fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.2) axcenter = plt.axes([0.59, 0.05, 0.1, 0.075]) axpause = plt.axes([0.7, 0.05, 0.1, 0.075]) axclear = plt.axes([0.81, 0.05, 0.1, 0.075]) timer = fig.canvas.new_timer(interval=50) timer.add_callback(update_graph, ax) timer.start() bnpause = Button(axpause, 'Pause') bnpause.on_clicked(pause) bnclear = Button(axclear, 'Clear') bnclear.on_clicked(clear) bncenter = Button(axcenter, 'Center') bncenter.on_clicked(center) if args.type == 'pid': axis_hdls = plot_pid(args.topic) if args.type == 'vector': axis_hdls = plot_vec(args.topic) plt.show()
#ax_prd.plot(cell_nums,new_hds[1,:],lw=1.5,color='0.5',alpha=0.5) ax_prd.scatter([cell_nums[7]], [new_hds[1, 7]], marker='s', color='0.05', alpha=0.5, s=30) prd.set_ydata(new_hds[1, :]) ax_prd.set_xlim(0, 100) fig.canvas.draw_idle() s_K.on_changed(update) resetax = plt.axes([0.15, 0.4, 0.25, 0.04]) button = Button(resetax, 'Start Uncertainty Analysis', color='0.75', hovercolor='0.5') def reset(event): plt.sca(ax_prd) plt.cla() tracked = [] new_hds = np.loadtxt(HDS_PATH) ax_prd.plot(cell_nums, initial_hds[1, :], lw=1.5, color='0.5', ls="--") ax_prd.text(50, 7.5, "Forecast", fontsize=15, ha="center") prd, = ax_prd.plot(cell_nums, new_hds[1, :], lw=1.5, color='b', marker='.',
sGain = Slider(axGain, 'Gain', -1, 6, valinit=gain) def update(val): # this function updates the exposure and gain values cap.set(cv2.CAP_PROP_EXPOSURE, sExp.val) cap.set(cv2.CAP_PROP_GAIN, sGain.val) fig.canvas.draw_idle() sExp.on_changed(update) # call for update everytime the cursors change sGain.on_changed(update) ### define buttons here RECax = plt.axes([0.01, (0.15 + rat) / 2, 0.05, 0.05]) # define size and position button = Button(RECax, 'REC', color='red', hovercolor='0.975') # define button def REC( event ): # when called, read "nbr_images" and save them as .tiff in save_directory t0 = time.time() last_t = 0 i = 0 while (i < nbr_images): if set_FPS == True and last_t != 0: #This loop is used to set the FPS while (time.time() - last_t) < 1. / FPS: indent = True last_t = time.time() ret, frame = cap.read() image = sitk.GetImageFromArray(frame)
def FindLidarPoints(): fig = plt.figure() ax = fig.add_subplot(111, projection="3d") ax.set_xlabel('X', fontsize=10) ax.set_ylabel('Y', fontsize=10) ax.set_zlabel('Z', fontsize=10) plt.subplots_adjust(left=0.05, bottom=0.2) marker_size, grid_length = (6, 8), 0.075 Rx, Ry, Rz = 0, 0, 0 global chess, corn, t, points, corners3D, axis_on, col plotInit, plotSmoothed, plotFinal = False, False, True points, Cloud3D = getPointCoud(ax=ax, plotInit=plotInit, plotSmoothed=plotSmoothed, plotFinal=plotFinal) axis_on, col = True, False R, t = [0, 0, 0], [0, 0, 0] t = np.mean(Cloud3D, axis=0) / grid_length chess, corn, corners3D = chessBoard(ax=ax, org=t, scale=grid_length) Rx_Slider = Slider(plt.axes([0.25, 0.15, 0.65, 0.03]), 'Rx', -180, 180.0, valinit=Rx) Ry_Slider = Slider(plt.axes([0.25, 0.1, 0.65, 0.03]), 'Ry', -180, 180.0, valinit=Ry) Rz_Slider = Slider(plt.axes([0.25, 0.05, 0.65, 0.03]), 'Rz', -180, 180.0, valinit=Rz) def update(val): Rx, Ry, Rz = Rx_Slider.val, Ry_Slider.val, Rz_Slider.val #print('Rx:{}, Ry:{}, Rz:{}'.format(Rx, Ry, Rz)) global chess, corn, corners3D chess.remove() corn.remove() R = [np.deg2rad(Rx), np.deg2rad(Ry), np.deg2rad(Rz)] chess, corn, corners3D = chessBoard(ax=ax, org=t, R=R, scale=grid_length) #yellow = ax.scatter(corners3D[:, 0], corners3D[:, 1], corners3D[:, 2], c='yellow', marker='o', s=5) fig.canvas.draw_idle() Rx_Slider.on_changed(update) Ry_Slider.on_changed(update) Rz_Slider.on_changed(update) check = CheckButtons(plt.axes([0.03, 0.3, 0.15, 0.08]), ('Axes', 'Black'), (True, False)) def func_CheckButtons(label): global col, axis_on if label == 'Axes': if axis_on: ax.set_axis_off() axis_on = False else: ax.set_axis_on() axis_on = True elif label == 'Black': if col: col = False ax.set_facecolor((1, 1, 1)) else: col = True ax.set_facecolor((0, 0, 0)) fig.canvas.draw_idle() check.on_clicked(func_CheckButtons) class Index(object): step = 1 def Tx(self, event): t[0] += self.step update(0) def Tx_(self, event): t[0] -= self.step update(0) def Ty(self, event): t[1] += self.step update(0) def Ty_(self, event): t[1] -= self.step update(0) def Tz(self, event): t[2] += self.step update(0) def Tz_(self, event): t[2] -= self.step update(0) callback = Index() Tx = Button(plt.axes([0.05, 0.15, 0.04, 0.045]), '+Tx', color='white') Tx.on_clicked(callback.Tx) Tx_ = Button(plt.axes([0.12, 0.15, 0.04, 0.045]), '-Tx', color='white') Tx_.on_clicked(callback.Tx_) Ty = Button(plt.axes([0.05, 0.1, 0.04, 0.045]), '+Ty', color='white') Ty.on_clicked(callback.Ty) Ty_ = Button(plt.axes([0.12, 0.1, 0.04, 0.045]), '-Ty', color='white') Ty_.on_clicked(callback.Ty_) Tz = Button(plt.axes([0.05, 0.05, 0.04, 0.045]), '+Tz', color='white') Tz.on_clicked(callback.Tz) Tz_ = Button(plt.axes([0.12, 0.05, 0.04, 0.045]), '-Tz', color='white') Tz_.on_clicked(callback.Tz_) def getClosestPoints(arg): global chess, corn, points, corners3D print('Cloud3D:{}, corners3D:{}'.format(np.shape(Cloud3D), np.shape(corners3D))) dist_mat, k = distance_matrix(corners3D, Cloud3D), 1 neighbours = np.argsort(dist_mat, axis=1)[:, 0] finaPoints = np.asarray(Cloud3D[neighbours, :]).squeeze() points[1].remove() chess.remove() corn.remove() ax.scatter(finaPoints[:, 0], finaPoints[:, 1], finaPoints[:, 2], c='g', marker='o', s=7) #ax.plot_wireframe(finaPoints[:, 0], finaPoints[:, 1], finaPoints[:, 2], markersize=2) corn = ax.scatter(corners3D[:, 0], corners3D[:, 1], corners3D[:, 2], c='tab:blue', marker='x', s=6) fig.canvas.draw_idle() savePoints = Button(plt.axes([0.03, 0.45, 0.15, 0.04], ), 'save points', color='white') savePoints.on_clicked(getClosestPoints) def reset(args): ax.cla() global chess, corn, corners3D, points points, Cloud3D = getPointCoud(ax=ax, plotInit=plotInit, plotSmoothed=plotSmoothed, plotFinal=plotFinal) t = np.mean(Cloud3D, axis=0) / grid_length chess, corn, corners3D = chessBoard(ax=ax, org=t, scale=grid_length) fig.canvas.draw_idle() resetBtn = Button(plt.axes([0.03, 0.25, 0.15, 0.04], ), 'reset', color='white') resetBtn.on_clicked(reset) def auto_fitChessboard(args): # estimate 3D-R and 3D-t between chess and PointCloud global chess, corn, points, corners3D # Inital guess of the transformation x0 = np.array([0, 0, 0, 0, 0, 0]) def f_min(x): global corners3D R = [np.deg2rad(x[0]), np.deg2rad(x[1]), np.deg2rad(x[2])] t = [x[3], x[4], x[5]] _, _, corners3D = chessBoard(ax=ax, org=t, R=R, scale=grid_length, plot=False) dist_mat = distance_matrix(corners3D, Cloud3D) err_func = dist_mat.sum(axis=1) # 63 x 1 #print('x:{}, err_func:{}, sum of errors = {}, dist_mat:{} corners3D:{},Cloud3D:{}'.format([], np.shape(err_func),round(np.sum(err_func),2),np.shape(dist_mat), np.shape(corners3D), np.shape(Cloud3D))) return err_func sol, status = leastsq(f_min, x0, ftol=1.49012e-06, xtol=1.49012e-06) print('sol:{}, status:{}'.format(sol, status)) R = [np.deg2rad(sol[0]), np.deg2rad(sol[1]), np.deg2rad(sol[2])] t = [sol[3], sol[4], sol[5]] chess.remove() corn.remove() chess, corn, corners3D = chessBoard(ax=ax, org=t, R=R, scale=grid_length) fig.canvas.draw_idle() #37073.64 fitChessboard = Button(plt.axes([0.03, 0.66, 0.15, 0.04], ), 'auto fit', color='white') fitChessboard.on_clicked(auto_fitChessboard) radio = RadioButtons(plt.axes([0.03, 0.5, 0.15, 0.15], ), ('Final', 'Smoothed', 'Init'), active=0) def colorfunc(label): plotInit, plotSmoothed, plotFinal = False, False, False if label == 'Init': plotInit = True elif label == 'Smoothed': plotSmoothed = True else: plotFinal = True global points [p.remove() for p in points] points, Cloud3D = getPointCoud(ax=ax, plotInit=plotInit, plotSmoothed=plotSmoothed, plotFinal=plotFinal) fig.canvas.draw_idle() radio.on_clicked(colorfunc) plt.show()
ax_time = plt.axes([0.25, 0.1, 0.5, 0.03], axisbg='lightgoldenrodyellow') slider_time = Slider(ax_time, 'timestep', 0.0, N_t, valinit=0, valfmt='%i') ax._widgets = [slider_time] # Avoids garbage collection def format_coord(theta, r): value = intpol(theta, r, sigma[:, :].cgs) return r'theta=%1.4f rad, R=%1.4f AU, Sigma=%1.4f g/cm2' % (theta, r, value) ax.format_coord = format_coord # Create movie button ax_button = plt.axes([0.25, 0.04, 0.17, 0.04]) button_movie = Button(ax_button, 'Create movie', hovercolor='0.975') ax._widgets += [button_movie] # Avoids garbage collection plt.show() # Show plot ##### FUNCTIONS #################################################################################################################### def update(val): i = int(np.floor(slider_time.val)) # Slider position try: sigma[:, :] = np.fromfile(data_dir + '/gasvrad' + repr(i) + '.dat').reshape(N_R, N_theta) * np.sqrt( aconst.G * aconst.M_sun / u.AU) except: print 'Could not load gasvrad' + repr(i) + '.dat'
class MisfitGUI: def __init__(self, event, seismogram_generator, project, window_manager, adjoint_source_directory=None): self.event = event self.event_latitude = event.origins[0].latitude self.event_longitude = event.origins[0].longitude self.project = project self.adjoint_source_dir = adjoint_source_directory self.seismogram_generator = seismogram_generator self.window_manager = window_manager self.__setup_plots() self.__connect_signals() self.next() plt.tight_layout() plt.show() def __setup_plots(self): # Some actual plots. self.plot_axis_z = plt.subplot2grid((6, 20), (0, 0), colspan=18) self.plot_axis_n = plt.subplot2grid((6, 20), (1, 0), colspan=18) self.plot_axis_e = plt.subplot2grid((6, 20), (2, 0), colspan=18) self.misfit_axis = plt.subplot2grid((6, 20), (3, 0), colspan=11, rowspan=3) self.colorbar_axis = plt.subplot2grid((6, 20), (3, 12), colspan=1, rowspan=3) #self.adjoint_source_axis = plt.subplot2grid((6, 8), (4, 0), colspan=4, #rowspan=1) self.map_axis = plt.subplot2grid((6, 20), (3, 13), colspan=8, rowspan=3) # Plot the map and the beachball. bounds = self.project.domain["bounds"] self.map_obj = visualization.plot_domain( bounds["minimum_latitude"], bounds["maximum_latitude"], bounds["minimum_longitude"], bounds["maximum_longitude"], bounds["boundary_width_in_degree"], rotation_axis=self.project.domain["rotation_axis"], rotation_angle_in_degree=self.project.domain["rotation_angle"], plot_simulation_domain=False, show_plot=False, zoom=True) visualization.plot_events([self.event], map_object=self.map_obj) # All kinds of buttons [left, bottom, width, height] self.axnext = plt.axes([0.90, 0.95, 0.08, 0.03]) self.axprev = plt.axes([0.90, 0.90, 0.08, 0.03]) self.axreset = plt.axes([0.90, 0.85, 0.08, 0.03]) self.bnext = Button(self.axnext, 'Next') self.bprev = Button(self.axprev, 'Prev') self.breset = Button(self.axreset, 'Reset Station') def __connect_signals(self): self.bnext.on_clicked(self.next) self.bprev.on_clicked(self.prev) self.breset.on_clicked(self.reset) self.plot_axis_z.figure.canvas.mpl_connect('button_press_event', self._onButtonPress) self.plot_axis_n.figure.canvas.mpl_connect('button_press_event', self._onButtonPress) self.plot_axis_e.figure.canvas.mpl_connect('button_press_event', self._onButtonPress) self.plot_axis_z.figure.canvas.mpl_connect('resize_event', self._on_resize) def _on_resize(self, *args): plt.tight_layout() def next(self, *args): while True: try: data = self.seismogram_generator.next() except StopIteration: return if not data: continue break self.data = data self.update() def prev(self, *args): while True: try: data = self.seismogram_generator.prev() except StopIteration: return if not data: continue break self.data = data self.update() def update(self): self.selected_windows = {"Z": [], "N": [], "E": []} self.plot() for trace in self.data["data"]: windows = self.window_manager.get_windows(trace.id) if not windows or "windows" not in windows or \ not windows["windows"]: continue for window in windows["windows"]: self.plot_window(component=windows["channel_id"][-1], starttime=window["starttime"], endtime=window["endtime"]) plt.draw() def plot_window(self, component, starttime, endtime): if component == "Z": axis = self.plot_axis_z elif component == "N": axis = self.plot_axis_n elif component == "E": axis = self.plot_axis_e else: raise NotImplementedError trace = self.data["synthetics"][0] ymin, ymax = axis.get_ylim() rect = Rectangle((starttime - trace.stats.starttime, ymin), endtime - starttime, ymax - ymin, color="0.6", alpha=0.5, edgecolor="0.5") axis.add_patch(rect) def reset(self, event): for trace in self.data["data"]: self.window_manager.delete_windows(trace.id) self.update() def plot(self): self.misfit_axis.cla() self.misfit_axis.set_xticks([]) self.misfit_axis.set_yticks([]) self.colorbar_axis.cla() self.colorbar_axis.set_xticks([]) self.colorbar_axis.set_yticks([]) try: self.misfit_axis.twin_axis.cla() self.misfit_axis.twin_axis.set_xticks([]) self.misfit_axis.twin_axis.set_yticks([]) del self.misfit_axis.twin_axis except: pass try: del self.rect except: pass self.rect = None # Clear all three plot axes. self.plot_axis_z.cla() self.plot_axis_n.cla() self.plot_axis_e.cla() s_stats = self.data["synthetics"][0].stats time_axis = np.linspace(0, s_stats.npts * s_stats.delta, s_stats.npts) def plot_trace(axis, component): real_trace = self.data["data"].select(component=component) synth_trace = self.data["synthetics"].select(component=component) if real_trace: axis.plot(time_axis, real_trace[0].data, color="black") if synth_trace: axis.plot(time_axis, synth_trace[0].data, color="red") if real_trace: text = real_trace[0].id axis.text(x=0.01, y=0.95, s=text, transform=axis.transAxes, bbox=dict(facecolor='white', alpha=0.5), verticalalignment="top") else: text = "No data, component %s" % component axis.text(x=0.01, y=0.95, s=text, transform=axis.transAxes, bbox=dict(facecolor='red', alpha=0.5), verticalalignment="top") axis.set_xlim(time_axis[0], time_axis[-1]) axis.set_ylabel("m/s") axis.grid() plot_trace(self.plot_axis_z, "Z") plot_trace(self.plot_axis_n, "N") plot_trace(self.plot_axis_e, "E") self.plot_axis_e.set_xlabel("Seconds since Event") try: self.greatcircle[0].remove() self.greatcircle = None except: pass try: self.station_icon.remove() self.station_icon = None except: pass self.greatcircle = self.map_obj.drawgreatcircle( self.data["coordinates"]["longitude"], self.data["coordinates"]["latitude"], self.event_longitude, self.event_latitude, linewidth=2, color='green', ax=self.map_axis) lng, lats = self.map_obj([self.data["coordinates"]["longitude"]], [self.data["coordinates"]["latitude"]]) self.station_icon = self.map_axis.scatter(lng, lats, color="blue", edgecolor="black", zorder=10000, marker="^", s=40) plt.draw() def _onButtonPress(self, event): if event.button != 1: # or event.inaxes != self.plot_axis_z: return # Store the axis. if event.name == "button_press_event": if event.inaxes == self.plot_axis_z: data = self.data["data"].select(component="Z") if not data: return self.rect = WindowSelectionRectangle(event, self.plot_axis_z, self._onWindowSelected) if event.inaxes == self.plot_axis_n: data = self.data["data"].select(component="N") if not data: return self.rect = WindowSelectionRectangle(event, self.plot_axis_n, self._onWindowSelected) if event.inaxes == self.plot_axis_e: data = self.data["data"].select(component="E") if not data: return self.rect = WindowSelectionRectangle(event, self.plot_axis_e, self._onWindowSelected) def _onWindowSelected(self, window_start, window_width, axis): """ Function called upon window selection. """ if window_width <= 0: return if axis is self.plot_axis_z: data = self.data["data"].select(component="Z")[0] synth = self.data["synthetics"].select(component="Z")[0] elif axis is self.plot_axis_n: data = self.data["data"].select(component="N")[0] synth = self.data["synthetics"].select(component="N")[0] elif axis is self.plot_axis_e: data = self.data["data"].select(component="E")[0] synth = self.data["synthetics"].select(component="E")[0] else: return if not data: return trace = data time_range = trace.stats.endtime - trace.stats.starttime plot_range = axis.get_xlim()[1] - axis.get_xlim()[0] starttime = trace.stats.starttime + (window_start / plot_range) * \ time_range endtime = starttime + window_width / plot_range * time_range self.window_manager.write_window( trace.id, starttime, endtime, 1.0, "cosine", "TimeFrequencyPhaseMisfitFichtner2008") # Window the data. data_trimmed = data.copy() data_trimmed.trim(starttime, endtime) data_trimmed.taper() data_trimmed.trim(synth.stats.starttime, synth.stats.endtime, pad=True, fill_value=0.0) synth_trimmed = synth.copy() synth_trimmed.trim(starttime, endtime) synth_trimmed.taper() synth_trimmed.trim(synth.stats.starttime, synth.stats.endtime, pad=True, fill_value=0.0) t = np.linspace(0, synth.stats.npts * synth.stats.delta, synth.stats.npts) self.misfit_axis.cla() self.colorbar_axis.cla() try: self.misfit_axis.twin_axis.cla() self.misfit_axis.twin_axis.set_xticks([]) self.misfit_axis.twin_axis.set_yticks([]) except: pass t = np.require(t, dtype="float64", requirements="C") data_d = np.require(data_trimmed.data, dtype="float64", requirements="C") synth_d = np.require(synth_trimmed.data, dtype="float64", requirements="C") adsrc = adsrc_tf_phase_misfit(t, data_d, synth_d, 5.0, 50.0, 0.00000001, axis=self.misfit_axis, colorbar_axis=self.colorbar_axis) plt.tight_layout() plt.draw() # Also save the adjoint source function. #self.write_adj_src(adsrc["adjoint_source"], synth.id, starttime, #endtime) def _write_adj_src(self, adj_src, channel_id, starttime, endtime): filename = "adjoint_source_%s_%s_%s.npy" % (channel_id, str(starttime), str(endtime)) filename = os.path.join(self.adjoint_source_dir, filename)
class RotatableAxes: def __init__(self, fig: mpl.figure.Figure, axes: mpl.axes.Axes, rect_angle: list, rect_reset: list): self.fig = fig # Suppose that there exists an image in the axes self.axes = axes self.renderer = self.axes.figure.canvas.get_renderer() self.axes_img_instance = self.axes.get_images()[0] self.original_axes_img = self.axes_img_instance.make_image( self.renderer, unsampled=True)[0] self.axes_for_angle_slider = self.fig.add_axes(rect_angle) self.axes_for_reset_button = self.fig.add_axes(rect_reset) self.angle_slider = Slider(self.axes_for_angle_slider, 'Angle(Degree)', 0.0, 359.0, valinit=0.0, valstep=0.1) self.angle_slider.on_changed(self.update_img) self.reset_button = Button(self.axes_for_reset_button, 'Reset') self.reset_button.on_clicked(self.reset) def connect(self) -> None: # connect to all the events we need self.fig.canvas.mpl_connect('button_press_event', self.onclick) def disconnect(self) -> None: # disconnect all the stored connection ids self.fig.canvas.mpl_disconnect(self.onclick) def update_la_img(self): self.axes_img_instance = self.axes.get_images()[0] self.original_axes_img = self.axes_img_instance.make_image( self.renderer, unsampled=True)[0] self.angle_slider.reset() def onclick(self, event: mpl.backend_bases.Event) -> None: if self.axes == event.inaxes: cur_img = self.axes_img_instance.make_image(self.renderer, unsampled=True)[0] if event.button == mpl.backend_bases.MouseButton.LEFT and event.inaxes is not None: rotated_image = ndimage.rotate(cur_img, 90.0, reshape=False) self.axes_img_instance.set_data(rotated_image) elif event.button == mpl.backend_bases.MouseButton.RIGHT and event.inaxes is not None: flipped_img = cur_img[:, ::-1] self.axes_img_instance.set_data(flipped_img) self.axes.figure.canvas.draw() self.axes.figure.canvas.flush_events() def update_img(self, new_angle: float) -> None: axes_images_list = self.axes.get_images() rotated_img = ndimage.rotate(self.original_axes_img, new_angle, reshape=False) axes_images_list[0].set_data(rotated_img) self.axes.figure.canvas.update() self.axes.figure.canvas.flush_events() def reset(self, event: mpl.backend_bases.Event): self.angle_slider.reset()
plotMin = np.min(adatok.iloc[:, i]) plotMax = np.max(adatok.iloc[:, i]) uniques = pd.unique(adatok.iloc[:, i]) if plotMax == plotMin: output.write(str(i) + "\t" + adatok.columns[i] + "\t" + str(plotMin)) output.write('\n') else: output.write( str(i) + "\t" + adatok.columns[i] + "\t\t" + str(plotMin) + "\t" + str(plotMax) + "\t" + str(uniques)) output.write('\n') # Close the output file output.close() #Endregion # Create the scatter plot and add labels plt.scatter(adatok.loc[:, 'Relativzeit'], adatok.iloc[:, index]) plt.xlabel(adatok.columns[index]) plt.ylabel('Relativzeit') # Create the 'next' nextButton subax = plt.axes([0.8, 0.025, 0.1, 0.04]) nextButton = Button(subax, 'Next', color='red', hovercolor='0.975') # Enter the update method when clicked nextButton.on_clicked(update) # Show plot plt.show()
class gyro_ui(object): '''Classe pour interface graphique de visualisation des données de remuage ''' format_date = "%d %b %Y %H:%M:%S" date_formatter = mdates.DateFormatter("%d %b") # For axis #date_formatter = ticker.FormatStrFormatter('%d %b') # for axis ratio_gyro = 131.0 #Gyro : 1/131 degrés/secondes ratio_acceleration = 16384.0 #Acceleration : 1/16384 g (g=9.81 N.s-2) seuil_gyro_mvt = 200.0 / 131.0 #Seuil au delà duquel une vitesse angulaire est considéré comme un mvt accel_detect = 1000.0 / 131.0 trig_detect = datetime.timedelta(minutes=10) def __init__(self, bdd, images_folder=None): '''Initialisation - bdd : base de données gyro_db ''' self.bdd = bdd self.dates = [] self.acc_Xs = [] self.acc_Ys = [] self.acc_Zs = [] self.gyro_Xs = [] self.gyro_Ys = [] self.gyro_Zs = [] self.angle_Xs = [] self.angle_Ys = [] #self.angle_Zs = [] self.angle_X = 0 self.angle_Y = 0 self.angle_Z = 0 self.lecture_donnees() self.scan_images(images_folder) self.fig = plt.figure() self.fig.canvas.set_window_title('Fileurope - CMP - FGYRO') self.init_graphes() self.lecture = False self.th_lecture_image = None self.vitesse_lecture = 1 def run(self): '''Run the ui ''' plt.show() def lecture_donnees(self): '''lecture de la base de données et correction des données ''' logging.info('Lecture des donnees') for data in self.bdd.mesures(): try: self.dates.append(gyro_db.utc_to_local(data['date'])) self.acc_Xs.append(data['acc_X'] / gyro_ui.ratio_acceleration) self.acc_Ys.append(data['acc_Y'] / gyro_ui.ratio_acceleration) self.acc_Zs.append(data['acc_Z'] / gyro_ui.ratio_acceleration) self.gyro_Xs.append(data['gyro_X'] / gyro_ui.ratio_gyro) self.gyro_Ys.append(data['gyro_Y'] / gyro_ui.ratio_gyro) self.gyro_Zs.append(data['gyro_Z'] / gyro_ui.ratio_gyro) ###Calculs angulaires # Accélération totale : c'est la pesanteur acc = sqrt(data['acc_X']**2 + data['acc_Y']**2 + data['acc_Z']**2) #Rotation autour de l'axe de la bouteille (c'est le roulis) self.angle_Xs.append(asin(data['acc_Z'] / acc) * 180 / pi) #Inclinaison de la bouteille vers le bas (c'est le tanguage) self.angle_Ys.append(acos(data['acc_X'] / acc) * 180 / pi) #self.angle_Zs.append(0) except Exception as e: print(e) logging.info("%s mesures trouvees." % (len(self.dates))) #Moyenne des vitesses angulaires pour auto-calibration try: corr_gyro_Xs = sum(self.gyro_Xs) / len(self.gyro_Xs) except: corr_gyro_Xs = 0 try: corr_gyro_Ys = sum(self.gyro_Ys) / len(self.gyro_Ys) except: corr_gyro_Ys = 0 try: corr_gyro_Zs = sum(self.gyro_Zs) / len(self.gyro_Zs) except: corr_gyro_Zs = 0 logging.info( "Correction des moyennes des vitesses angulaires : x:%s, y:%s, z:%s" % (corr_gyro_Xs, corr_gyro_Ys, corr_gyro_Zs)) nb_supp_mesures_angle = 0 for i in range(len(self.dates)): #Correction des vitesses angulaires self.gyro_Xs[i] -= corr_gyro_Xs self.gyro_Ys[i] -= corr_gyro_Ys self.gyro_Zs[i] -= corr_gyro_Zs # "Suppression" des mesures d'angle quand il y a une vitesses angulaire if i > 0 and (abs(self.gyro_Xs[i]) > gyro_ui.seuil_gyro_mvt or abs(self.gyro_Ys[i]) > gyro_ui.seuil_gyro_mvt or abs(self.gyro_Zs[i]) > gyro_ui.seuil_gyro_mvt): self.angle_Xs[i] = self.angle_Xs[i - 1] self.angle_Ys[i] = self.angle_Ys[i - 1] #self.angle_Zs[i] = self.angle_Zs[i-1] nb_supp_mesures_angle += 1 logging.info("%s mesures d'angle supprimees" % nb_supp_mesures_angle) # Recherche des phases self.phases = [] # Un enregistrement par phase self.etapes = [] # A chaque point, la phase correspondante i = 0 while i < len(self.dates): acceleration = sqrt(self.gyro_Xs[i]**2 + self.gyro_Ys[i]**2 + self.gyro_Zs[i]**2) if acceleration > gyro_ui.accel_detect: acceleration_max = acceleration date_debut_mouvement = self.dates[i] date_fin_mouvement = date_debut_mouvement date_fin_trig = date_debut_mouvement + gyro_ui.trig_detect while self.dates[i] < date_fin_trig: acceleration = sqrt(self.gyro_Xs[i]**2 + self.gyro_Ys[i]**2 + self.gyro_Zs[i]**2) acceleration_max = max(acceleration_max, acceleration) if acceleration > gyro_ui.accel_detect: date_fin_phase = self.dates[i] i += 1 self.phases.append({ 'debut_mvt': date_debut_mouvement, 'fin_mvt': date_fin_mouvement, 'acceleration_max': acceleration_max }) logging.info("Phase detectee : no %s : debut = %s, fin = %s" % (len(self.phases), date_debut_mouvement, date_fin_mouvement)) else: i += 1 self.etapes.append(len(self.phases)) self.export_xls() def export_xls(self, filename=None): '''Exporte les données vers un fichier excel ''' #TODO mettre menu dans interface if filename is None: filename = "gyro.xlsx" import xlsxwriter workbook = xlsxwriter.Workbook(filename) worksheet = workbook.add_worksheet("phases") format_date = workbook.add_format({'num_format': 'dd/mm/yy hh:mm:ss'}) col = 0 for key in self.phases[0]: row = 0 worksheet.write(row, col, key) row += 1 for item in self.phases: if "date" in key: worksheet.write_datetime(row, col, self.phases[row - 1][key], format_date) else: worksheet.write(row, col, self.phases[row - 1][key]) row += 1 col += 1 workbook.close() def init_graphes(self): ''' Inititialise les graphiques ''' ### IMAGE REMUTRACE image_capteur = plt.imread('capteur.png') self.image_capteur_plot = self.fig.add_subplot(233) self.image_capteur_plot.set_axis_off() self.image_capteur_plot.imshow(image_capteur) ### 3D (non implementé) #self.3D = figure3D().add_subplot(233) #self.3D = self.fig.add_subplot(233) ### GRAPHE XYZ #self.xyz=self.fig.add_subplot(231) #self.xyz.set_xlabel('Temps') #self.xyz.set_ylabel('x,y,z') #self.xyz.plot(self.dates, self.acc_Xs, label='acc_X') #self.xyz.plot(self.dates, self.acc_Ys, label='acc_Y') #self.xyz.plot(self.dates, self.acc_Zs, label='acc_Z') #self.xyz.legend() #self.xyz_line = False ### GRAPHE GxGyGz self.GxGyGz = self.fig.add_subplot(231) #, sharex = self.xyz) self.GxGyGz.set_title(u'Vitesse angulaire') self.GxGyGz.set_xlabel(u'Temps') self.GxGyGz.set_ylabel(u'Deg/s') self.GxGyGz.plot(self.dates, self.gyro_Xs, label='gyro_X') self.GxGyGz.plot(self.dates, self.gyro_Ys, label='gyro_Y') self.GxGyGz.plot(self.dates, self.gyro_Zs, label='gyro_Z') #self.GxGyGz.set_xticks(self.dates) self.GxGyGz.xaxis.set_major_locator(mdates.DayLocator()) #self.GxGyGz.xaxis.set_minor_locator(mdates.HourLocator()) self.GxGyGz.xaxis.set_major_formatter( ticker.FormatStrFormatter("%d %b")) self.GxGyGz.legend() self.GxGyGz_line = False #self.fig.autofmt_xdate() #plt.xticks(rotation=90) logging.debug("GRAPHE GxGyGz ok") ### GRAPHE INCLINAISON self.Inclinaison = self.fig.add_subplot(234, sharex=self.GxGyGz) self.Inclinaison.plot(self.dates, self.angle_Ys, label='Inclinaison') #self.Inclinaison.legend() self.Inclinaison.set_title(u'Inclinaison') self.Inclinaison.set_xlabel(u'Temps') self.Inclinaison.set_ylabel(u'Deg') self.Inclinaison_line = False ### GRAPHE ROTATION self.Rotation = self.fig.add_subplot(235, sharex=self.GxGyGz) self.Rotation.plot(self.dates, self.angle_Xs, label='Rotation') #self.Rotation.legend() self.Rotation.set_title(u'Rotation') self.Rotation.set_xlabel(u'Temps') self.Rotation.set_ylabel(u'Deg') self.Rotation_line = False ### PHOTO self.image_plot = self.fig.add_subplot(232) self.image_plot.set_axis_off() self.image_plot.set_title(u'Caméra') ### BOUTONS self.fig.canvas.mpl_connect('button_press_event', self.on_click) self.bt_lecture = Button(plt.axes([0.65, 0.3, 0.05, 0.03]), 'lecture') self.bt_lecture.on_clicked(self.on_bt_lecture_click) self.bt_lecture10 = Button(plt.axes([0.65, 0.2, 0.05, 0.03]), 'lecturex10') self.bt_lecture10.on_clicked(self.on_bt_lecture_click10) #self.tb_vitesse = TextBox(plt.axes([0.9, 0.8, 0.05, 0.03]),'Vitesse', initial = '1') #self.tb_vitesse.on_submit(self.on_tb_vitesse_submit) ### Détail étape axe_etape = self.fig.add_axes([0.65, 0.4, 0.03, 0.03]) axe_etape.set_axis_off() self.etape = plt.text(0, 3, u'Etape n° ?') self.etape_debut_mvt = plt.text(0, 2, u'Début : --') self.etape_fin_mvt = plt.text(0, 1, u'Fin : --') self.etape_acceleration_max = plt.text(0, 0, u'Accélération max : --') ### LEGENDE : FILEUROPE-CMP legende = self.fig.add_axes([0.75, 0.07, 0.2, 0.3]) legende.set_axis_off() #rect = Rectangle((0,0),1,1,fill=True, color= 'blue') #legende.add_patch(rect) logo_img = plt.imread('logo.png') legende.imshow(logo_img) text_legende = plt.text(0.05, 0.05, u"Remutrace - Brevet déposé.") self.fig.canvas.mpl_connect('key_press_event', self.press) def scan_images(self, rep): '''Scan le repertoire des images et peuble le dict self.images : {date:nom_fichier _image} ''' #logging.info("Scan du repertoir images : %s ..."%(rep)) self.images = {} self.images_dates = {} if rep: for fichier in os.listdir(rep): if os.path.isfile(os.path.join(rep, fichier)): try: self.images[datetime.datetime.strptime( fichier[3:-4], "%Y-%m-%d %H-%M-%S.%f")] = os.path.join( rep, fichier) except: pass self.images_dates = self.images.keys() self.images_dates.sort() logging.info("%s images trouvees." % (len(self.images))) self.xdate_index = 0 def show_image(self): '''Update the image and the cursors and the etape ''' if len(self.images) > 0: date = self.images_dates[self.xdate_index] image_path = self.images[date] #logging.debug("Image %s"%(image_path)) image_file = cbook.get_sample_data(image_path) image = plt.imread(image_file) self.image_plot.clear() self.image_plot.set_axis_off() self.image_plot.imshow(image) self.image_plot.set_title(u'Caméra') self.image_plot.text( 0, 800, "Date : " + self.dates[self.xdate_index].strftime(gyro_ui.format_date)) if self.GxGyGz_line: self.GxGyGz_line.remove() self.GxGyGz_line = self.GxGyGz.vlines( date, self.GxGyGz.get_ylim()[0] * 0.75, self.GxGyGz.get_ylim()[1] * 0.75) if self.Inclinaison_line: self.Inclinaison_line.remove() self.Inclinaison_line = self.Inclinaison.vlines( date, self.Inclinaison.get_ylim()[0] * 0.75, self.Inclinaison.get_ylim()[1] * 0.75) if self.Rotation_line: self.Rotation_line.remove() self.Rotation_line = self.Rotation.vlines( date, self.Rotation.get_ylim()[0] * 0.75, self.Rotation.get_ylim()[1] * 0.75) etape = self.etapes[self.xdate_index] self.etape.set_text(u"Etape n° %s" % etape) self.etape_debut_mvt.set_text( u"Début : " + self.phases[etape]["debut_mvt"].strftime(gyro_ui.format_date)) self.etape_fin_mvt.set_text( u"Fin : " + self.phases[etape]["fin_mvt"].strftime(gyro_ui.format_date)) self.etape_acceleration_max.set_text( u"Accél. max : %s" % self.phases[etape]["acceleration_max"]) # TODO et plus d'info self.fig.canvas.draw() # C'est ici que c'est long (0.3 s) def on_click(self, event): '''callback function when click on graphe ''' #logging.debug('button=%d, inaxes = %s, x=%d, y=%d, xdata=%f, ydata=%f' %(event.button, event.inaxes, event.x, event.y, event.xdata, event.ydata)) if len(self.images) > 0: if event.inaxes in [self.GxGyGz, self.Inclinaison, self.Rotation]: date = mdates.num2date(event.xdata).replace(tzinfo=None) #try: self.xdate_index = self.images_dates.index( min(self.images_dates, key=lambda d: abs(d - date))) logging.debug(self.xdate_index) self.show_image() # except: # pass # Attention : bricolage+++ def on_bt_lecture_click10(self, event): self.vitesse_lecture = 10 self.on_bt_lecture_click_all(event) def on_bt_lecture_click(self, event): ''' ''' self.vitesse_lecture = 1 self.on_bt_lecture_click_all(event) def on_bt_lecture_click_all(self, event): if self.lecture: self.lecture = False self.bt_lecture.Label = matplotlib_text.Text(text='lecture') logging.info("Pause") self.th_lecture_image.stop() self.fig.canvas.draw() else: self.lecture = True self.bt_lecture.Label = matplotlib_text.Text(text='pause') logging.info("Lecture") self.fig.canvas.draw() self.th_lecture_image = f_thread(self.lecture_images) self.th_lecture_image.start() # Fin du bricolage def lecture_images(self, sens=1): ''' affichage de l'image suivante Utilisation : en threading : f_thread(self.lecture_images) ''' self.xdate_index += sens * self.vitesse_lecture if self.xdate_index > len(self.images_dates): self.xdate_index = 0 self.lecture = False self.show_image() time.sleep(0.05) #Pour donner la main à l'affichage def press(self, event): ''' Quand une fleche droite ou gauche est appuyée : image suivante ou précédente ''' print("Key pressed : " + event.key) sys.stdout.flush() if event.key == "down": self.lecture_images(1) elif event.key == "up": self.lecture_images(-1) elif event.key == "pagedown": self.lecture_images(10) elif event.key == "pageup": self.lecture_images(-10) def on_tb_vitesse_submit(self, text): ''' quand changement vitesse de lecture ''' try: self.vitesse_lecture = int(text) except: pass
def __init__(self, load_path, save_path=None): # init manipulator self.savepath = save_path self.filepaths = self._load_paths( load_path) # load all scans filepaths in path self.fileindex = 0 self.manipulator = scan_manipulator() self.manipulator.load_target_scan(self.filepaths[self.fileindex]) self.hist_state = True self.inject_coords = [] self.remove_coords = [] # init plot self.eq = histEq(self.manipulator.scan) self.slices, self.cols, self.rows = self.manipulator.scan.shape self.ind = self.slices // 2 self.pause_start = 0 self.fig, self.ax = plt.subplots(1, 1, dpi=100) self.fig.suptitle( 'CT-GAN: Malicious Tampering of 3D Medical Imagery using Deep Learning\nTool by Yisroel Mirsky', fontsize=14, fontweight='bold') plt.subplots_adjust(bottom=0.2) self.ani_direction = 'down' self.animation = None self.animation_state = True self.plot() self.ax.set_title(os.path.split( self.filepaths[self.fileindex])[-1]) #filename # register click/scroll events self.action_state = 'inject' #default state self.fig.canvas.mpl_connect('button_press_event', self.onclick) self.fig.canvas.mpl_connect('scroll_event', self.onscroll) # register buttons axanim = plt.axes([0.1, 0.21, 0.2, 0.075]) self.banim = Button(axanim, 'Toggle Animation') self.banim.on_clicked(self.toggle_animation) axinj = plt.axes([0.1, 0.05, 0.1, 0.075]) axrem = plt.axes([0.21, 0.05, 0.1, 0.075]) self.binj = Button(axinj, 'Inject') self.binj.on_clicked(self.inj_on) self.brem = Button(axrem, 'Remove') self.brem.on_clicked(self.rem_on) axhist = plt.axes([0.35, 0.05, 0.2, 0.075]) self.bhist = Button(axhist, 'Toggle HistEQ') self.bhist.on_clicked(self.hist) axprev = plt.axes([0.59, 0.05, 0.1, 0.075]) axsave = plt.axes([0.7, 0.05, 0.1, 0.075]) axnext = plt.axes([0.81, 0.05, 0.1, 0.075]) self.bnext = Button(axnext, 'Next') self.bnext.on_clicked(self.next) self.bprev = Button(axprev, 'Previous') self.bprev.on_clicked(self.prev) self.bsave = Button(axsave, 'Save') self.bsave.on_clicked(self.save) self.maximize_window() self.update() plt.show()
T = Tvals[Tind] point.set_data(Tvals[Tind], states[Tind]) val_slider.set_val(states[Tind]) ax.set_ylim([ np.min(W.States[0:N_slider.val]) - 1, np.max(W.States[0:N_slider.val]) + 1 ]) fig.canvas.draw_idle() N_slider.on_changed(sliders_on_changed) t_slider.on_changed(sliders_on_changed) # Add a button for resetting the parameters reset_button_ax = fig.add_axes([0.8, 0.02, 0.1, 0.01]) reset_button = Button(reset_button_ax, 'Reset', color=axis_color, hovercolor='0.975') def reset_button_on_clicked(mouse_event): N_slider.reset() reset_button.on_clicked(reset_button_on_clicked) plt.show()
class GUI(object): # If load_path is to a *.dcm or *.mhd file then only this scan is loaded # If load_path is to a directory, then all scans are loaded. It is assumed that each scan is in its own subdirectory. # save_path is the directory to save the tampered scans (as dicom) def __init__(self, load_path, save_path=None): # init manipulator self.savepath = save_path self.filepaths = self._load_paths( load_path) # load all scans filepaths in path self.fileindex = 0 self.manipulator = scan_manipulator() self.manipulator.load_target_scan(self.filepaths[self.fileindex]) self.hist_state = True self.inject_coords = [] self.remove_coords = [] # init plot self.eq = histEq(self.manipulator.scan) self.slices, self.cols, self.rows = self.manipulator.scan.shape self.ind = self.slices // 2 self.pause_start = 0 self.fig, self.ax = plt.subplots(1, 1, dpi=100) self.fig.suptitle( 'CT-GAN: Malicious Tampering of 3D Medical Imagery using Deep Learning\nTool by Yisroel Mirsky', fontsize=14, fontweight='bold') plt.subplots_adjust(bottom=0.2) self.ani_direction = 'down' self.animation = None self.animation_state = True self.plot() self.ax.set_title(os.path.split( self.filepaths[self.fileindex])[-1]) #filename # register click/scroll events self.action_state = 'inject' #default state self.fig.canvas.mpl_connect('button_press_event', self.onclick) self.fig.canvas.mpl_connect('scroll_event', self.onscroll) # register buttons axanim = plt.axes([0.1, 0.21, 0.2, 0.075]) self.banim = Button(axanim, 'Toggle Animation') self.banim.on_clicked(self.toggle_animation) axinj = plt.axes([0.1, 0.05, 0.1, 0.075]) axrem = plt.axes([0.21, 0.05, 0.1, 0.075]) self.binj = Button(axinj, 'Inject') self.binj.on_clicked(self.inj_on) self.brem = Button(axrem, 'Remove') self.brem.on_clicked(self.rem_on) axhist = plt.axes([0.35, 0.05, 0.2, 0.075]) self.bhist = Button(axhist, 'Toggle HistEQ') self.bhist.on_clicked(self.hist) axprev = plt.axes([0.59, 0.05, 0.1, 0.075]) axsave = plt.axes([0.7, 0.05, 0.1, 0.075]) axnext = plt.axes([0.81, 0.05, 0.1, 0.075]) self.bnext = Button(axnext, 'Next') self.bnext.on_clicked(self.next) self.bprev = Button(axprev, 'Previous') self.bprev.on_clicked(self.prev) self.bsave = Button(axsave, 'Save') self.bsave.on_clicked(self.save) self.maximize_window() self.update() plt.show() def _load_paths(self, path): filepaths = [] # load single scan? if (path.split('.')[-1] == "dcm") or (path.split('.')[-1] == "mhd"): filepaths.append(path) return filepaths # try load directory of scans... files = os.listdir(path) for file in files: if os.path.isdir(file): subdir = os.path.join(path, file) subdir_files = os.listdir(subdir) if subdir_files[0].split( '.')[-1] == "dcm": #folder contains dicom filepaths.append(os.path.join(path, subdir)) elif (subdir_files[0].split('.')[-1] == "mhd") or (subdir_files[0].split('.')[-1] == "raw"): # MHD filepaths.append( os.path.join(path, subdir, subdir_files[0])) elif file.split('.')[-1] == "mhd": filepaths.append(os.path.join(path, file)) return filepaths def onclick(self, event): # print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % # ('double' if event.dblclick else 'single', event.button, # event.x, event.y, event.xdata, event.ydata)) if event.xdata is not None: coord = np.array([self.ind, event.ydata, event.xdata], dtype=int) if coord[1] > 0 and coord[2] > 0: self.pause_start = np.Inf #pause while working if self.action_state == 'inject': self.ax.set_title("Injecting...") self.im.axes.figure.canvas.draw() self.manipulator.tamper(coord, action='inject', isVox=True) self.inject_coords.append(coord) else: self.ax.set_title("Removing...") self.im.axes.figure.canvas.draw() self.manipulator.tamper(coord, action='remove', isVox=True) self.remove_coords.append(coord) self.pause_start = time.time( ) #pause few secs to see result before continue self.ax.set_title( os.path.split( self.filepaths[self.fileindex])[-1]) # filename self.update() def onscroll(self, event): if event.button == 'up': self.ind = (self.ind + 1) % self.slices else: self.ind = (self.ind - 1) % self.slices self.update() def toggle_animation(self, event): self.animation_state = not self.animation_state if self.animation_state: self.pause_start = 0 else: self.pause_start = np.Inf def inj_on(self, event): self.action_state = 'inject' def rem_on(self, event): self.action_state = 'remove' def hist(self, event): self.hist_state = not self.hist_state self.plot() self.update() def next(self, event): self.fileindex = (self.fileindex + 1) % len(self.filepaths) self.loadscan(self.fileindex) def prev(self, event): self.fileindex = (self.fileindex - 1) % len(self.filepaths) self.loadscan(self.fileindex) def save(self, event): if self.savepath is not None: self.ax.set_title("Saving...") self.im.axes.figure.canvas.draw() uuid = os.path.split(self.filepaths[self.fileindex])[-1][:-4] #save scan self.manipulator.save_tampered_scan(os.path.join( self.savepath, uuid), output_type='dicom') #save coords file_exists = False if os.path.exists( os.path.join(self.savepath, "tamper_coordinates.csv")): file_exists = True f = open(os.path.join(self.savepath, "tamper_coordinates.csv"), "a+") load_filename = os.path.split(self.filepaths[self.fileindex])[-1] if not file_exists: f.write("filename, x, y, z, tamper_type\n") #header for coord in self.inject_coords: f.write(load_filename + ", " + str(coord[2]) + ", " + str(coord[1]) + ", " + str(coord[0]) + ", " + "inject\n") for coord in self.remove_coords: f.write(load_filename + ", " + str(coord[2]) + ", " + str(coord[1]) + ", " + str(coord[0]) + ", " + "remove\n") f.close() self.ax.set_title(load_filename) # filename self.im.axes.figure.canvas.draw() def update(self): if self.hist_state: self.im.set_data( self.eq.equalize(self.manipulator.scan[self.ind, :, :])) else: self.im.set_data(self.manipulator.scan[self.ind, :, :]) self.ax.set_ylabel('slice %s' % self.ind) self.im.axes.figure.canvas.draw() def loadscan(self, fileindex): #load screen self.im.set_data(np.ones((self.cols, self.rows)) * -1000) self.ax.set_title("Loading...") self.im.axes.figure.canvas.draw() self.remove_coords.clear() self.inject_coords.clear() #load scan self.manipulator.load_target_scan(self.filepaths[fileindex]) self.slices, self.cols, self.rows = self.manipulator.scan.shape self.ind = self.slices // 2 self.ax.clear() self.eq = histEq(self.manipulator.scan) self.plot() self.ax.set_title(os.path.split( self.filepaths[fileindex])[-1]) #filename self.ax.set_ylabel('slice %s' % self.ind) self.im.axes.figure.canvas.draw() def plot(self): self.ax.clear() if self.hist_state: self.im = self.ax.imshow( self.eq.equalize(self.manipulator.scan[self.ind, :, :]), cmap="bone") #, cmap="bone", vmin=-1000, vmax=1750) else: self.im = self.ax.imshow(self.manipulator.scan[self.ind, :, :], cmap="bone", vmin=-1000, vmax=1750) self.animation = animation.FuncAnimation(self.fig, self.animate, interval=100) def animate(self, i): if self.animation_state: if time.time() - self.pause_start > 1: if self.ind == self.slices - 1: self.ani_direction = 'up' elif self.ind == 0: self.ani_direction = 'down' if self.ani_direction == 'up': self.ind -= 1 else: self.ind += 1 self.update() def maximize_window(self): try: #'QT4Agg' figManager = plt.get_current_fig_manager() figManager.window.showMaximized() except: try: #'TkAgg' mng = plt.get_current_fig_manager() mng.window.state('zoomed') except: try: #'wxAgg' mng = plt.get_current_fig_manager() mng.frame.Maximize(True) except: print("Could not maximize window")
def calibrate(self): plt.clf() self.img = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB) plt.imshow(self.img) self.anounce( 'You will define a rectangle in the image \n by selecting its corners, click to begin' ) plt.waitforbuttonpress() while True: pts = [] while len(pts) < 3: self.anounce( 'Select 4 corners of the rectangle in the following order:\n top left, top right, bottom left, bottom right' ) pts = np.asarray(plt.ginput(4, timeout=-1)) if len(pts) < 4: self.anounce('Too few points, starting over') self.anounce('Happy? Key click for yes, mouse click for no') fill_pts = np.copy(pts) fill_pts[[2, 3]] = fill_pts[[3, 2]] print(pts) print(fill_pts) ph = plt.fill(fill_pts[:, 0], fill_pts[:, 1], 'r', lw=2) if plt.waitforbuttonpress(): break for p in ph: p.remove() pts = pts.tolist() for pt in pts: pt[0] = round(pt[0]) pt[1] = round(pt[1]) self.corners = pts def submitWidth(text): self.width = eval(text) def submitHeight(text): self.height = eval(text) def submit(event): print("Corners: {}".format(self.corners)) print("Width is {}m".format(self.width)) print("Height is {}m".format(self.height)) print("Calibration is complete") plt.close('all') self.anounce( "Enter the width and height (in metres) in the fields below \n Width: top left corner to top right corner \n Height: top left corner to bottom left corner" ) width_box = TextBox(plt.axes([0.2, 0.02, 0.2, 0.05]), 'Width:', initial='') width_box.on_text_change(submitWidth) height_box = TextBox(plt.axes([0.6, 0.02, 0.2, 0.05]), 'Height:', initial='') height_box.on_text_change(submitHeight) submit_button = Button(plt.axes([0.85, 0.02, 0.1, 0.05]), 'Submit') submit_button.on_clicked(submit) plt.show()
def __init__(self, mov, roi, traces, images={}, cmap=pl.cm.viridis, **kwargs): """ Args: mov : 3d np array, 0'th axis is time/frames roi : 3d np array, one roi per item in 0'th axis, each of which is a True/False mask indicating roi (True=inside roi) traces : 2d np array, 0'th axis is time, 1st axis is sources images: dictionary of still images Attributes: roi_kept : boolean array of length of supplied roi, indicating whether or not roi should be kept based on user input """ self.mov = mov self.roi_idxs = np.array([np.argwhere(r.flat).squeeze() for r in roi]) self.roi_centers = np.array( [np.mean(np.argwhere(r), axis=0) for r in roi]) self.roi_orig = roi.copy() self.roi = pretty_roi(roi) self.roi_kept = np.ones(len(self.roi_idxs)).astype(bool) self.traces = traces self.images = images # figure setup self.cmap = cmap self.fig = pl.figure() NR, NC = 128, 32 gs = gridspec.GridSpec(nrows=NR, ncols=NC) gs.update(wspace=0.1, hspace=0.1, left=.04, right=.96, top=.98, bottom=.02) # movie axes self.ax_contrast0 = self.fig.add_subplot(gs[0:5, 0:NC // 3]) self.ax_contrast1 = self.fig.add_subplot(gs[5:10, 0:NC // 3]) self.ax_mov = self.fig.add_subplot(gs[10:55, 0:NC // 3]) self.ax_mov.axis('off') self.ax_img = self.fig.add_subplot(gs[55:100, 0:NC // 3]) self.ax_img.axis('off') self.axs_imbuts = [ self.fig.add_subplot(gs[110:128, idx * 2:idx * 2 + 2]) for idx, i in enumerate(self.images) ] # trace axes self.ax_trcs = self.fig.add_subplot(gs[0:64, NC // 2:]) self.ax_trc = self.fig.add_subplot(gs[65:85, NC // 2:]) self.ax_trc.set_xlim([0, len(self.traces)]) self.ax_nav = self.fig.add_subplot(gs[85:90, NC // 2:]) self.ax_nav.set_xlim([0, len(self.traces)]) self.ax_nav.axis('off') self.ax_rm = self.fig.add_subplot(gs[95:110, NC // 2:]) # interactivity self.c0, self.c1 = 0, 100 self.sl_contrast0 = Slider(self.ax_contrast0, 'Low', 0., 255.0, valinit=self.c0, valfmt='%d') self.sl_contrast1 = Slider(self.ax_contrast1, 'Hi', 0., 255.0, valinit=self.c1, valfmt='%d') self.sl_contrast0.on_changed(self.evt_contrast) self.sl_contrast1.on_changed(self.evt_contrast) self.img_buttons = [ Button(ax, k) for k, ax in zip(list(self.images.keys()), self.axs_imbuts) ] self.but_rm = Button(self.ax_rm, 'Remove All ROIs Currently in FOV') # display initial things self.movdata = self.ax_mov.imshow(self.mov[0]) self.movdata.set_animated(True) self.roidata = self.ax_mov.imshow(self.roi, cmap=self.cmap, alpha=0.5, vmin=np.nanmin(self.roi), vmax=np.nanmax(self.roi)) self.trdata, = self.ax_trc.plot(np.zeros(len(self.traces))) self.navdata, = self.ax_nav.plot([-2, -2], [-1, np.max(self.traces)], 'r-') if len(self.images): lab, im = list(self.images.items())[0] self.imgdata = self.ax_img.imshow(im) self.ax_img.set_ylabel(lab) self.plot_current_traces() # callbacks for ib, lab in zip(self.img_buttons, list(self.images.keys())): ib.on_clicked(lambda evt, lab=lab: self.evt_imbut(evt, lab)) self.but_rm.on_clicked(self.remove_roi) self.fig.canvas.mpl_connect('button_press_event', self.evt_click) self.ax_mov.callbacks.connect('xlim_changed', self.evt_zoom) self.ax_mov.callbacks.connect('ylim_changed', self.evt_zoom) # runtime self._idx = -1 self.t0 = time.clock() self.always_draw = [self.movdata, self.roidata, self.navdata] self.blit_clear_axes = [self.ax_mov, self.ax_nav] # parent init animation.TimedAnimation.__init__(self, self.fig, interval=40, blit=True, **kwargs)
def draw(self): while True: try: _ = self.xMl break except: time.sleep(5) self.fig = plt.figure() self.ax = self.fig.add_subplot(1, 1, 1) plt.subplots_adjust(bottom=0.25) axnext = plt.axes([0.6, 0.05, 0.1, 0.075]) bnext = Button(axnext, 'Refresh') bnext.on_clicked(self.refresh_func) while True: if self.refresh: self.ax.lines = list() self.ax.texts = list() self.ax.plot(self.xM, self.yM, color="black", linewidth=1) for n, xpos, ypos, value in zip(self.Nl, self.xMl, self.yMl, self.slope_list): self.ax.text(xpos - 1, ypos + 0.0005, str(abs(value)), fontsize=6, color="gray", fontweight="bold") for x_slice, y_slice, x_point, y_point, sig_type in self.signal_list: self.ax.plot(x_slice, y_slice, color="steelblue", linewidth=1) self.ax.text(x_point, self.y_min - 0.002, sig_type, fontsize=5, color="steelblue", fontweight="bold") for xpos, ypos, close_type, x, start_price in self.close_list: self.ax.plot([ xpos, ], [ ypos, ], "*k", markersize=5) if ypos != start_price: if close_type == "long": color = "red" if ypos > start_price else "green" y_2_points = [start_price, ypos] else: color = "red" if ypos < start_price else "green" y_2_points = [start_price, 2 * start_price - ypos] self.ax.plot([x, x + 0.001], y_2_points, color=color, linewidth=2) if self.long_trigger_price is not None: self.ax.plot(self.xM, [ self.long_trigger_price, ] * len(self.xM), "--r", linewidth=0.5) if self.short_trigger_price is not None: self.ax.plot(self.xM, [ self.short_trigger_price, ] * len(self.xM), "--g", linewidth=0.5) self.ax.set_title(str(round(self.pnl, 3))) plt.pause(30) else: plt.pause(120)
class GUI(animation.TimedAnimation): """ interface for viewing a movie and its associated roi, traces, other things implementation is only through matplotlib, and is non-blocking backend affects performance somewhat dramatically. have achieved decent performance with qt5agg and tkagg Methods: ------- Attributes: ---------- roi_kept : boolean array of length of supplied roi, indicating whether or not roi should be kept based on user input """ #todo: todocument *14 def __init__(self, mov, roi, traces, images={}, cmap=pl.cm.viridis, **kwargs): """ Args: mov : 3d np array, 0'th axis is time/frames roi : 3d np array, one roi per item in 0'th axis, each of which is a True/False mask indicating roi (True=inside roi) traces : 2d np array, 0'th axis is time, 1st axis is sources images: dictionary of still images Attributes: roi_kept : boolean array of length of supplied roi, indicating whether or not roi should be kept based on user input """ self.mov = mov self.roi_idxs = np.array([np.argwhere(r.flat).squeeze() for r in roi]) self.roi_centers = np.array( [np.mean(np.argwhere(r), axis=0) for r in roi]) self.roi_orig = roi.copy() self.roi = pretty_roi(roi) self.roi_kept = np.ones(len(self.roi_idxs)).astype(bool) self.traces = traces self.images = images # figure setup self.cmap = cmap self.fig = pl.figure() NR, NC = 128, 32 gs = gridspec.GridSpec(nrows=NR, ncols=NC) gs.update(wspace=0.1, hspace=0.1, left=.04, right=.96, top=.98, bottom=.02) # movie axes self.ax_contrast0 = self.fig.add_subplot(gs[0:5, 0:NC // 3]) self.ax_contrast1 = self.fig.add_subplot(gs[5:10, 0:NC // 3]) self.ax_mov = self.fig.add_subplot(gs[10:55, 0:NC // 3]) self.ax_mov.axis('off') self.ax_img = self.fig.add_subplot(gs[55:100, 0:NC // 3]) self.ax_img.axis('off') self.axs_imbuts = [ self.fig.add_subplot(gs[110:128, idx * 2:idx * 2 + 2]) for idx, i in enumerate(self.images) ] # trace axes self.ax_trcs = self.fig.add_subplot(gs[0:64, NC // 2:]) self.ax_trc = self.fig.add_subplot(gs[65:85, NC // 2:]) self.ax_trc.set_xlim([0, len(self.traces)]) self.ax_nav = self.fig.add_subplot(gs[85:90, NC // 2:]) self.ax_nav.set_xlim([0, len(self.traces)]) self.ax_nav.axis('off') self.ax_rm = self.fig.add_subplot(gs[95:110, NC // 2:]) # interactivity self.c0, self.c1 = 0, 100 self.sl_contrast0 = Slider(self.ax_contrast0, 'Low', 0., 255.0, valinit=self.c0, valfmt='%d') self.sl_contrast1 = Slider(self.ax_contrast1, 'Hi', 0., 255.0, valinit=self.c1, valfmt='%d') self.sl_contrast0.on_changed(self.evt_contrast) self.sl_contrast1.on_changed(self.evt_contrast) self.img_buttons = [ Button(ax, k) for k, ax in zip(list(self.images.keys()), self.axs_imbuts) ] self.but_rm = Button(self.ax_rm, 'Remove All ROIs Currently in FOV') # display initial things self.movdata = self.ax_mov.imshow(self.mov[0]) self.movdata.set_animated(True) self.roidata = self.ax_mov.imshow(self.roi, cmap=self.cmap, alpha=0.5, vmin=np.nanmin(self.roi), vmax=np.nanmax(self.roi)) self.trdata, = self.ax_trc.plot(np.zeros(len(self.traces))) self.navdata, = self.ax_nav.plot([-2, -2], [-1, np.max(self.traces)], 'r-') if len(self.images): lab, im = list(self.images.items())[0] self.imgdata = self.ax_img.imshow(im) self.ax_img.set_ylabel(lab) self.plot_current_traces() # callbacks for ib, lab in zip(self.img_buttons, list(self.images.keys())): ib.on_clicked(lambda evt, lab=lab: self.evt_imbut(evt, lab)) self.but_rm.on_clicked(self.remove_roi) self.fig.canvas.mpl_connect('button_press_event', self.evt_click) self.ax_mov.callbacks.connect('xlim_changed', self.evt_zoom) self.ax_mov.callbacks.connect('ylim_changed', self.evt_zoom) # runtime self._idx = -1 self.t0 = time.clock() self.always_draw = [self.movdata, self.roidata, self.navdata] self.blit_clear_axes = [self.ax_mov, self.ax_nav] # parent init animation.TimedAnimation.__init__(self, self.fig, interval=40, blit=True, **kwargs) @property def frame_seq(self): self._idx += 1 if self._idx == len(self.mov): self._idx = 0 self.navdata.set_xdata([self._idx, self._idx]) yield self.mov[self._idx] @frame_seq.setter def frame_seq(self, val): pass def new_frame_seq(self): return self.mov def _init_draw(self): self._draw_frame(self.mov[0]) self._drawn_artists = self.always_draw def _draw_frame(self, d): self.t0 = time.clock() self.movdata.set_data(d) # blit self._drawn_artists = self.always_draw for da in self._drawn_artists: da.set_animated(True) def _blit_clear(self, artists, bg_cache): for ax in self.blit_clear_axes: if ax in bg_cache: self.fig.canvas.restore_region(bg_cache[ax]) def evt_contrast(self, val): self.c0 = self.sl_contrast0.val self.c1 = self.sl_contrast1.val if self.c0 > self.c1: self.c0 = self.c1 - 1 self.sl_contrast0.set_val(self.c0) if self.c1 < self.c0: self.c1 = self.c0 + 1 self.sl_contrast1.set_val(self.c1) self.movdata.set_clim(vmin=self.c0, vmax=self.c1) self.imgdata.set_clim(vmin=self.c0, vmax=self.c1) def evt_imbut(self, evt, lab): self.imgdata.set_data(self.images[lab]) self.ax_img.set_title(lab) def evt_click(self, evt): if not evt.inaxes: return elif evt.inaxes == self.ax_mov: # select roi x, y = int(np.round(evt.xdata)), int(np.round(evt.ydata)) idx = np.ravel_multi_index((y, x), self.roi.shape) inside = np.argwhere([idx in ri for ri in self.roi_idxs]) if len(inside) == 0: return i = inside[0] self.set_current_trace(i) elif evt.inaxes in [self.ax_nav]: x = int(np.round(evt.xdata)) self._idx = x def evt_zoom(self, *args): self.plot_current_traces() def set_current_trace(self, idx): col = self.cmap(np.linspace(0, 1, np.sum(self.roi_kept)))[np.squeeze(idx)] t = self.traces[:, idx] self.trdata.set_ydata(t) self.trdata.set_color(col) self.ax_trc.set_ylim([t.min(), t.max()]) self.ax_trc.set_title('ROI {}'.format(idx)) self.ax_trc.figure.canvas.draw() def get_current_roi(self): croi = np.array([isin(rc, self.ax_mov) for rc in self.roi_centers]) croi[self.roi_kept is False] = False return croi def remove_roi(self, evt): self.current_roi = self.get_current_roi() self.roi_kept[self.current_roi] = False # update if np.sum(self.roi_kept): proi = pretty_roi(self.roi_orig[self.roi_kept]) self.roidata.set_data(proi) self.roidata.set_clim(vmin=np.nanmin(proi), vmax=np.nanmax(proi)) else: self.roidata.remove() def plot_current_traces(self): self.current_roi = self.get_current_roi() if np.sum(self.current_roi) == 0: return for line in self.ax_trcs.get_lines(): line.remove() cols = self.cmap(np.linspace(0, 1, len(self.roi_idxs)))[self.current_roi] lastmax = 0 for t, c in zip(self.traces.T[self.current_roi], cols): self.ax_trcs.plot((t - t.min()) + lastmax, color=c) lastmax = np.max(t) self.ax_trcs.set_ylim([0, lastmax])
class SplitPrintWindow(): def __init__(self, print_manager, combo_prints, hulls_df, print_numb, vid_panel, invert_axes=True): self.root = tk.Tk() self.root.wm_title("Split the Selected Print") self.fig = Figure(figsize=(10, 8), dpi=100) self.canvas = FigureCanvasTkAgg(self.fig, master=self.root) # A tk.DrawingArea. self.canvas.draw() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.root) self.toolbar.update() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.print_manager = print_manager self.combo_prints = combo_prints self.print_numb = print_numb self.first_frame = self.combo_prints.first_frame[print_numb] n_frames = (self.combo_prints.last_frame[print_numb] - self.first_frame) + 1 grid_size = int(np.ceil(np.sqrt(n_frames))) self.axes = [] self.fig.set_size_inches(16, 9) button_axes = self.fig.add_axes([.01, .01, .05, .05]) self.button = Button(button_axes, 'Split') self.button.on_clicked(self.create_new_hulls) these_hulls = hulls_df[hulls_df.print_numb == print_numb] self.collections = {} self.xyes = {} for i in range(0, n_frames): ax = self.fig.add_subplot(grid_size, grid_size, i + 1) self.axes.append(ax) ax.set_axis_off() frame = vid_panel.get_frame(self.first_frame + i) X = self.combo_prints.X[print_numb] Y = self.combo_prints.Y[print_numb] ax.imshow(frame) xes = [] yes = [] for c in (these_hulls.contours[these_hulls.frame == self.first_frame + i].values[0]): #add all to a single list to make one collection xes = xes + list(c[:, 0, 0]) yes = yes + list(c[:, 0, 1]) self.collections[ax] = ax.scatter(xes, yes) self.xyes[ax] = self.collections[ax].get_offsets() #set it to have list of facecolors so that selection works facecolors = self.collections[ax].get_facecolors() npts = len(self.xyes[ax]) facecolors = np.tile(facecolors, npts).reshape(npts, -1) self.collections[ax].set_facecolor(facecolors) if invert_axes: ax.set_xlim(X + 50, X - 50) else: ax.set_xlim(X - 50, X + 50) ax.set_ylim(Y - 50, Y + 50) ax.set_title('Frame ' + str(self.first_frame + i)) self.axes = np.asarray(self.axes) self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) self.canvas.draw() tk.mainloop() def create_new_hulls(self, event): new_hull_points = [] old_hull_points = [] frame = [] if (sys.version_info > (3, 0)): iterab = self.collections.items() else: iterab = self.collections.iteritems() for ax, collection in iterab: #make np array of bools with whether color matches the selection color for each point inds = np.asarray([ True if np.array_equal(i, [.4, .4, .9, 1.0]) else False for i in collection.get_facecolors() ]) #use np bool indexing to get x,y values for selected and unselected new_hull_points.append(self.xyes[ax][inds]) old_hull_points.append(self.xyes[ax][~inds]) frame.append(self.first_frame + np.where(self.axes == ax)[0]) self.print_manager.split_print(new_hull_points, old_hull_points, frame, self.print_numb) self.root.destroy() def callback(self, verts): facecolors = self.collections[self.current_axes].get_facecolors() p = path.Path(verts) ind = p.contains_points(self.xyes[self.current_axes]) for i in range(len(self.xyes[self.current_axes])): if ind[i]: facecolors[i] = [.4, .4, .9, 1.0] else: facecolors[i] = [.4, .4, .2, .5] self.collections[self.current_axes].set_facecolor(facecolors) self.fig.canvas.draw_idle() self.fig.canvas.widgetlock.release(self.lasso) del self.lasso #TODO: troubleshoot widget locks def onpress(self, event): if self.fig.canvas.widgetlock.locked(): return if event.inaxes is None: return self.current_axes = event.inaxes self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) # acquire a lock on the widget drawing self.fig.canvas.widgetlock(self.lasso)
class Animation: """The foundation of all animations. Parameters ---------- blocks : list of animatplot.animations.Block A list of blocks to be animated timeline : Timeline or 1D array, optional If an array is passed in, it will be converted to a Timeline. If not given, a timeline will be created using the length of the first block. fig : matplotlib figure, optional The figure that the animation is to occur on Attributes ---------- animation a matplotlib animation returned from FuncAnimation """ def __init__(self, blocks, timeline=None, fig=None): if timeline is None: self.timeline = Timeline(range(len(blocks[0]))) elif not isinstance(timeline, Timeline): self.timeline = Timeline(timeline) else: self.timeline = timeline _len_time = len(self.timeline) for block in blocks: if len(block) != _len_time: raise ValueError( "All blocks must animate for the same amount of time") self.blocks = blocks self.fig = plt.gcf() if fig is None else fig self._has_slider = False self._pause = False def animate(i): updates = [] for block in self.blocks: updates.append(block._update(self.timeline.index)) if self._has_slider: self.slider.set_val(self.timeline.index) self.timeline._update() return updates self.animation = FuncAnimation(self.fig, animate, frames=self.timeline._len, interval=1000 / self.timeline.fps) def toggle(self, axis=None): """Creates a play/pause button to start/stop the animation Parameters ---------- axis : optional A matplotlib axis to attach the button to. """ if axis is None: adjust_plot = {'bottom': .2} rect = [.78, .03, .1, .07] plt.subplots_adjust(**adjust_plot) self.button_ax = plt.axes(rect) else: self.button_ax = axis self.button = Button(self.button_ax, "Pause") self.button.label2 = self.button_ax.text( 0.5, 0.5, 'Play', verticalalignment='center', horizontalalignment='center', transform=self.button_ax.transAxes) self.button.label2.set_visible(False) def pause(event): if self._pause: self.animation.event_source.start() self.button.label.set_visible(True) self.button.label2.set_visible(False) else: self.animation.event_source.stop() self.button.label.set_visible(False) self.button.label2.set_visible(True) self.fig.canvas.draw() self._pause ^= True self.button.on_clicked(pause) def timeline_slider(self, text='Time', axis=None, valfmt='%1.2f', color=None): """Creates a timeline slider. Parameters ---------- text : str, optional The text to display for the slider. Defaults to 'Time' axis : optional A matplotlib axis to attach the slider to valfmt : str, optional a format specifier used to print the time Defaults to '%1.2f' color : The color of the slider. """ if axis is None: adjust_plot = {'bottom': .2} rect = [.18, .05, .5, .03] plt.subplots_adjust(**adjust_plot) self.slider_ax = plt.axes(rect) else: self.slider_ax = axis if self.timeline.log: valfmt = '$10^{%s}$' % valfmt self.slider = Slider(self.slider_ax, text, 0, self.timeline._len - 1, valinit=0, valfmt=(valfmt + self.timeline.units), valstep=1, color=color) self._has_slider = True def set_time(t): self.timeline.index = int(self.slider.val) self.slider.valtext.set_text(self.slider.valfmt % (self.timeline[self.timeline.index])) if self._pause: for block in self.blocks: block._update(self.timeline.index) self.fig.canvas.draw() self.slider.on_changed(set_time) def controls(self, timeline_slider_args={}, toggle_args={}): """Creates interactive controls for the animation Creates both a play/pause button, and a time slider at once Parameters ---------- timeline_slider_args : Dict, optional A dictionary of arguments to be passed to timeline_slider() toggle_args : Dict, optional A dictionary of argyments to be passed to toggle() """ self.timeline_slider(**timeline_slider_args) self.toggle(**toggle_args) def save_gif(self, filename): """Saves the animation to a gif A convience function. Provided to let the user avoid dealing with writers. Parameters ---------- filename : str the name of the file to be created without the file extension """ self.timeline.index -= 1 # required for proper starting point for save self.animation.save(filename + '.gif', writer=PillowWriter(fps=self.timeline.fps)) def save(self, *args, **kwargs): """Saves an animation A wrapper around :meth:`matplotlib.animation.Animation.save` """ self.timeline.index -= 1 # required for proper starting point for save self.animation.save(*args, **kwargs)
def add_button_to(plt, fn): #print(fn) from matplotlib.widgets import Button ax = plt.axes([0.85, 0.95, 0.15, 0.03]) btn = Button(ax, 'New') btn.on_clicked(fn)
R = 6 T = 0.15 CW = 0.65 / 2.0 + 0.65 / 4.0 L = 0.15 + 0.65 / 2.0 H = 0.03 ButtonQueue.reverse() for Row in range(R): TRow = [] for Col in range(C): A = plt.axes( [L + (CW / float(C)) * Col, T - H * Row, CW / float(C), H]) if len(ButtonQueue) > 0: B = ButtonQueue.pop() if B != "": TRow.append(Button(A, B[0])) TRow[-1].on_clicked(B[1]) TRow[-1].drawon = False else: TRow.append(Button(A, "")) TRow[-1].on_clicked(ButtonClick) TRow[-1].drawon = False else: TRow.append(Button(A, "")) TRow[-1].on_clicked(ButtonClick) TRow[-1].drawon = False ButtonGrid.append(TRow) #PlotType = "FracMaxAnyA0" PlotType = "T99"