def reset_chart(self): self.track_axes.clear() self.track_figure.patch.set_visible(False) self.track_axes.patch.set_visible(False) self.xdata = [] self.ydata = [] self.idata = [] self.x_min = 0 self.x_max = 1 self.y_max = 1 self.bracket_set = False self.button_hold = False self.plot_zoom = False self.chart_range = None self.selector = None self.max_lock = True self.patch_x = 0 self.patch_x_last = 1 self.patch_width = 1 self.start_edge = 0 self.end_edge = 1 self.acc_plot = self.track_axes.plot([], [], 'o', color='#4575b4')[0] self.rej_plot = self.track_axes.plot([], [], 'o', color='#d73027')[0] self.idx_plot = self.track_axes.plot([], [], 'wo', ms=2)[0] self.bragg_line = self.track_axes.axhline(0, c='#4575b4', ls=':', alpha=0) self.highlight = self.track_axes.axvspan(0.5, 0.5, ls='--', alpha=0, fc='#deebf7', ec='#2171b5') self.track_axes.set_autoscaley_on(True) self.select_span = SpanSelector(ax=self.track_axes, onselect=self.onSelect, direction='horizontal', rectprops=dict(alpha=0.5, ls=':', fc='#deebf7', ec='#2171b5')) self.select_span.set_active(False) self.zoom_span = SpanSelector(ax=self.track_axes, onselect=self.onSelect, direction='horizontal', rectprops=dict(alpha=0.5, ls=':', fc='#ffffd4', ec='#8c2d04')) self.zoom_span.set_active(False)
def create_canvas(self): self.fig = plt.figure() self.canvas = FigureCanvas(self.fig) self.axes = plt.subplot(111) self.axes.set_xlabel("Retention Time") self.axes.set_ylabel("Instensity") self.axes.tick_params(axis='both', labelsize=8) plt.subplots_adjust(bottom=0.25, top=0.90, left=0.08, right=0.9) self.zoom = RectangleSelector(self.axes, self.rectangle_select_callback, drawtype='box', useblit=True, button=[1], minspanx=5, minspany=5, spancoords='pixels') self.span = SpanSelector(self.axes, self.span_select_callback, 'horizontal', minspan=0.002, useblit=True, rectprops=dict(alpha=0.5, facecolor='red'), onmove_callback=None, button=[1]) axbasic = plt.axes([0.59, 0.04, 0.08, 0.075]) axPan = plt.axes([0.7, 0.04, 0.08, 0.075]) axPick = plt.axes([0.81, 0.04, 0.08, 0.075]) self.btnBasic = Button(axbasic, 'Zoom') self.btnPan = Button(axPan, 'Span') self.btnPick = Button(axPick, 'Undo') axtic = plt.axes([0.92, 0.825, 0.06, 0.075]) axext = plt.axes([0.92, 0.725, 0.06, 0.075]) axres = plt.axes([0.92, 0.625, 0.06, 0.075]) self.TICbutton = Button(axtic, 'TIC') self.EXTbutton = Button(axext, 'EXT') self.RESbutton = Button(axres, 'RES') vbox = QVBoxLayout() vbox.addWidget(self.canvas) self.setLayout(vbox) self.btnBasic.on_clicked(self.zoom_mode) self.btnPan.on_clicked(self.span_mode) self.btnPick.on_clicked(self.undo_mode) self.TICbutton.on_clicked(self.slot_tic) self.EXTbutton.on_clicked(self.slot_ext) self.RESbutton.on_clicked(self.slot_res) self.zoom_mode(True) self.redraw() ymino, ymaxo = self.axes.get_ylim() xmino, xmaxo = self.axes.get_xlim() self.oxy = [(xmino, xmaxo), (ymino, ymaxo)]
def __init__(self, data, plot_method=PlotMethod.SCATTER, classes=[], ion=True, **kwargs): self.fig = fig = plt.figure(figsize=(15, 15)) data = data.astype({"class": str}, axis=1) self.classes = np.unique(data["class"].values.tolist() + classes) # Security check if "class" not in data: raise ValueError("You must have a class column in your data") # Create axes data_names = [i for i in data if i != "class"] self.gs = gs = gridspec.GridSpec(len(data_names), 1) self.axes = axes = [fig.add_subplot(i) for i in gs] self.data = data self.axe_zoom = axe_zoom = plt.axes((.15, .03, .84, .05)) self.span_zoom = SpanSelector(axe_zoom, self.select_zoom, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green')) self.spans = [ SpanSelector(axe, self.onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) for axe in axes ] self.radio_axe = rax = plt.axes( (0.005, .1, .1, .03 * len(self.classes))) self.radio = radio = RadioButtons(rax, self.classes) radio.on_clicked(self.clicked_radio) self.current_class_index = 0 self.zoom = np.array( [np.min(data.index.values), np.max(data.index.values)]) self.zoom_ylim = None self.zoom_xlim = None self.zoom_fill = None self.plot_method = plot_method self.kwargs = kwargs self.ion = ion self.plot() self.running = False self.__create_legend()
def __init__(self, routine): super(VolumetricGraphWidget, self).__init__() logging.info("Volumetricgraph Window Started") self.routine = routine self.layout = QVBoxLayout(self) self.setWindowTitle("Graph and Flourescence (+Volumetric)") self.roiindex = 0 self.xmin = 0 self.xmax = 1 self.secondxmin = 0 self.secondxmax = 1 self.secondthreshold = 0.3 self.fig = plt.figure() self.canvas = FigureCanvas(self.fig) self.data = None self.shown = False self.showall = False self.secondchannelUI = 300 self.flags = QLineEdit() self.flagsSave = QPushButton("Save") self.flagsSave.clicked.connect(self.save) self.minimumslider = ValueSelector("Threshold", 0, 100, self.thresholdChanged, ismin=True) self.minimumslider.valueslider.setValue( int(self.routine.settings.threshold * 100)) self.dataCanvas = self.fig.add_subplot(513) self.data2Canvas = self.fig.add_subplot(515) self.pictureCanvas = self.fig.add_subplot(511) self.picture1Canvas = self.fig.add_subplot(512) self.picture2Canvas = self.fig.add_subplot(514) self.span = SpanSelector(self.data2Canvas, self.onsecondselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) self.span2 = SpanSelector(self.dataCanvas, self.onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) self.setUI() self.show()
def __init__(self, sme, segment=0, axes=None, show=True): self.wave = sme.wave self.spec = sme.spec self.mask = sme.mask self.smod = sme.synth self.segment = segment self.nsegments = len(self.wave) self.mode = "line/cont" self.lines = sme.linelist self.vrad = sme.vrad self.vrad = [v if v is not None else 0 for v in self.vrad] self.line_plot = None self.lock = False if axes is None: self.im = plt.subplots()[1] else: self.im = axes self.selector_line = SpanSelector( self.im, self.section_line_callback, direction="horizontal", useblit=True, button=(1, ), ) self.selector_cont = SpanSelector( self.im, self.section_continuum_callback, direction="horizontal", useblit=True, button=(3, ), ) self.im.figure.canvas.mpl_connect("key_press_event", self.key_event) self.im.callbacks.connect("xlim_changed", self.resize_event) ax_next = plt.axes([0.8, 0.025, 0.1, 0.04]) self.button_next = Button(ax_next, "-->") self.button_next.on_clicked(self.next_segment) ax_prev = plt.axes([0.7, 0.025, 0.1, 0.04]) self.button_prev = Button(ax_prev, "<--") self.button_prev.on_clicked(self.previous_segment) self.plot() if show: plt.show()
def __init__(self, ax, **kwargs): onselect = kwargs.pop('onselect', self.dummy) direction = kwargs.pop('direction', 'horizontal') useblit = kwargs.pop('useblit', ax.figure.canvas.supports_blit) SpanSelector.__init__(self, ax, onselect, direction=direction, useblit=useblit, span_stays=False, **kwargs) # The tolerance in points to pick the rectangle sizes self.tolerance = preferences.Plot.pick_tolerance self.on_move_cid = None self._range = None self.step_ax = None self.bounds_check = False self._button_down = False self.snap_size = False self.snap_position = False self.events = Events() self.events.changed = Event(doc=""" Event that triggers when the widget was changed. Arguments: ---------- obj: The widget that changed """, arguments=['obj']) self.events.moved = Event(doc=""" Event that triggers when the widget was moved. Arguments: ---------- obj: The widget that changed """, arguments=['obj']) self.events.resized = Event(doc=""" Event that triggers when the widget was resized. Arguments: ---------- obj: The widget that changed """, arguments=['obj']) self.can_switch = False
def on_mousemove(self, event): if not self.dragging or self.drag_data is None: return ax = self.drag_data[3] if self.span is None: self.dragging = False invtrans = ax.transData.inverted() minspan = 3 * np.abs(invtrans.transform((1, 0)) - invtrans.transform((0, 0)))[0] self.span = SpanSelector(ax, self.on_spanselect, 'horizontal', minspan=minspan) event2 = self.drag_data[4] self.span.press(event2) self.span.onmove(event)
def __init__(self, parent=None): super(Window, self).__init__(parent) #self.setGeometry(300, 100, 800, 600) # distance from sx, from top, length, heigth self.showMaximized() self.figure, ((self.ax1, self.ax2), (self.ax3, self.ax4)) = plt.subplots(2, 2) self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.button = QtGui.QPushButton('Browse') self.button.clicked.connect(self.browse) # set the layout layout = QtGui.QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) layout.addWidget(self.button) self.setLayout(layout) #self.ax = self.figure.add_subplot(111) self.span1 = SpanSelector(self.ax1, self.extremes1, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green')) self.span2 = SpanSelector(self.ax2, self.extremes2, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green')) self.span3 = SpanSelector(self.ax3, self.extremes3, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green')) self.span4 = SpanSelector(self.ax4, self.extremes4, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green'))
def inspectLC(self): # create new window inspwin = tkinter.Tk() inspwin.title("Inspect Lightcurve") # information on selected bad data selectionsFrame = tkinter.Frame(inspwin) buttonsFrame = tkinter.Frame(selectionsFrame) self.inspClose = tkinter.Button(buttonsFrame, text="Save and Close", command=inspwin.destroy) self.inspClose.pack(side='left') self.inspDelete = tkinter.Button(buttonsFrame, text="Delete Selections", command=self.remove_spans) self.inspDelete.pack(side='left') buttonsFrame.pack(side='top', fill=tkinter.X) self.selectlistbox = tkinter.Listbox(selectionsFrame) self.selectlistbox.pack(side='bottom', fill=tkinter.Y) for item in self.lc_spans: self.selectlistbox.insert(tkinter.END, item) self.selectlistbox.bind('<<ListboxSelect>>', self.highlight_span) # plot of the lightcurve (above) and selected region (below) plottingFrame = tkinter.Frame(inspwin) self.baddataLabel = tkinter.Label(plottingFrame, text="Select Bad Data", font=('', 42)) self.baddataLabel.pack(side='top', fill=tkinter.BOTH) self.figInspLC, (self.axInspLC, self.selectedData) = plt.subplots(2, figsize=(12, 6)) self.axInspLC.plot(self.star_lc_all.time.value, self.star_lc_all.flux.value, 'k.') self.axInspLC.plot(self.star_lc.time.value[self.peaks], self.star_lc.flux[self.peaks], 'ob') self.axInspLC.grid() self.line2, = self.selectedData.plot(self.star_lc_all.time.value, self.star_lc_all.flux.value, 'r.') self.selectedData.grid() self.lcInspPlot = FigureCanvasTkAgg(self.figInspLC, plottingFrame) # add a toolbar for plot control toolbar = NavigationToolbar2Tk(self.lcInspPlot, plottingFrame) toolbar.update() self.lcInspPlot.get_tk_widget().pack(side='top', fill=tkinter.BOTH, expand=1) # selection tool for bad data self.spanSel = SpanSelector(self.axInspLC, self.onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red'), span_stays=True) self.lcInspPlot.mpl_connect('key_press_event', self.spanSel) self.lcInspPlot.mpl_connect('close_event', self.handle_close) plottingFrame.pack(side='left') selectionsFrame.pack(side='left')
def addRegion(self, _): self.index += 1 rangeselect.numRanges = self.index coordsList.append(rangeselect.coords.copy()) ax.patches[-1].set_facecolor('green') _ = SpanSelector(ax, rangeselect, 'horizontal', useblit=False, rectprops=dict(alpha=0.3, facecolor='red')) plt.draw()
def add_selector(self, listing): # We will be able to select X-frames and its boundaries # will be stored in the given list """ The SpanSelector is a mouse widget to select a xmin/xmax range and plot the detail view of the selected region in the lower axes """ def onselect(xmin, xmax): # indmin, indmax = np.searchsorted(x, (xmin, xmax)) # indmax = min(len(x)-1, indmax) indmin = xmin indmax = xmax onselect.listing.append([indmin, indmax]) print(onselect.listing) onselect.listing = listing # set useblit True on gtkagg for enhanced performance ax = self.axes span = SpanSelector(ax, onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) self.widget_list.append(span)
def __init__(self, data_list, title="Provide Title"): """ Parameters ---------- data_list: list List of 2-tuples of the form (xdata, ydata) where xdata and ydata are lists corresponding to x and y values to be plotted. xdata and ydata have the same length. title: string Title of plot """ self.data_list = data_list self.fig = plt.figure(figsize=(8, 6)) self.axes = self.fig.add_subplot(211) for data in self.data_list: self.axes.plot(data[0], data[1], '-o') self.axes.set_title(title) self.axes2 = self.fig.add_subplot(212) for data in self.data_list: line, = self.axes2.plot(data[0], data[1], '-o') self.span = SpanSelector(self.axes, self.onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red'))
def draw_plot(self,event): self.figure.clear() self.axes = self.figure.add_subplot(211, axisbg='#FFFFCC') self.axes.clear() self.axes.grid(self.cb_grid.IsChecked()) x = np.arange(0.0, 5.0, 0.01) y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x)) self.axes.plot(x, y, '-') self.axes.set_ylim(-2,2) self.axes.set_title('Press left mouse button and drag to test') self.axes2 = self.figure.add_subplot(212, axisbg='#FFFFCC') self.axes2.clear() self.axes2.grid(self.cb_grid.IsChecked()) line2, = self.axes2.plot(x, y, '-') def onselect(xmin, xmax): indmin, indmax = np.searchsorted(x, (xmin, xmax)) indmax = min(len(x)-1, indmax) thisx = x[indmin:indmax] thisy = y[indmin:indmax] line2.set_data(thisx, thisy) self.axes2.set_xlim(thisx[0], thisx[-1]) self.axes2.set_ylim(thisy.min(), thisy.max()) self.figure.canvas.draw() # set useblit True on gtkagg for enhanced performance self.span = SpanSelector(self.axes, onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red') ) self.figure.canvas.draw()
def add_span_selector(self, name, callback, axes=None, **kwargs): axes = axes if axes else self.axes self.add_element( SpanSelector( axes, lambda min, max: self.__on_selected(name, callback, min, max), **kwargs), name)
def edit_norm(_arg=None): # Only some backends pass in an argument. try: im, = images except ValueError: raise NotImplementedError from None array = im.get_array().ravel() sub_ax = plt.figure().subplots() sub_ax.hist(array, _hist_bins(im), histtype="stepfilled") if isinstance(im.norm, mpl.colors.LogNorm): sub_ax.set(xscale="log") def on_select(vmin, vmax): if vmin == vmax: im.set_clim((array.min(), array.max())) else: im.set_clim((vmin, vmax)) im.figure.canvas.draw() ss = sub_ax.__ss = SpanSelector(sub_ax, on_select, "horizontal", useblit=True, span_stays=True) ss.stay_rect.set(x=im.norm.vmin, width=im.norm.vmax - im.norm.vmin, visible=True) plt.show(block=False)
def plot(self, channel): fig,ax = plt.subplots(nrows=1, ncols=1, figsize=(14,14)) ax[0].loglog(self.fb,self.Pb[channel]) ax[0].set(xlabel="Frequency (Hz)", ylabel="Power (V2/Hz)",); ax[0].set_xlim([1E-1, 1E4]) ax[0].set_ylim([1E-13, 1E-7]) fitplot, = ax[0].loglog(self.fb, self.Pfit[channel]) def onselect(xmin, xmax): #implement condition if range selected is not in fit range indmin, indmax = np.searchsorted(self.fb_fit, (xmin, xmax)) indmax = min(len(self.fb_fit) - 1, indmax) inds = np.arange(indmin, indmax+1, 1) thisx = self.fb_fit[indmin:indmax] thisy = self.Pb_fit[indmin:indmax] ax[0].loglog(thisx, thisy, c='r') fig.canvas.draw_idle() self.fb_fit = np.delete(self.fb_fit, inds) self.Pb_fit = np.delete(self.Pb_fit, inds) self.sorensen_fit() fitplot.set_data(self.fb, self.Pfit[2]) # save #np.savetxt("text.out", np.c_[thisx, thisy]) span = SpanSelector(ax[0], onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) plt.show()
def start_autobaseline(self): # self.toolbar.release(None) self.span = SpanSelector(self.Plot.a, self.autobaseline, 'horizontal') self.span.connect_event('pick_event',self.autobaseline) gcf().canvas.mpl_connect('button_press_event',self.disconnect) return 0
def get_QT_interval(self, fig, ax, ax1, ax2, line2, qt_average_waveform, qt_all_spikes): """ This function allows the user to select the QT interval for a region of data. input: fig(plt.fig) ax, ax1, ax2(plt.fig.subplot) line2(plt.fig.subplot.plot([float])) qt_average_waveform([float]) qt_all_spikes([MCS_Spike]) """ ax.set_title(self.title) ax.plot(qt_average_waveform) for spike in qt_all_spikes: ax1.plot(spike.voltage_data) span = SpanSelector(ax, self.onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) plt.show(block=False) a = raw_input("Press any key... ") qt_start_point = self.indmin qt_end_point = self.indmax return qt_start_point, qt_end_point
def _init_plot(self): self._figure = plt.figure(figsize=(9, 5)) axes = plt.subplot(1, 1, 1) plt.plot(self.wL, self.A, lw=3, color='k') axes.grid(which="both") self._axes = axes plt.xlabel(self.xlabel_str) plt.ylabel('Absorbance') if self._points: x, y = zip(*self._points.items()) self._line, = self._axes.plot(x, y, "r", marker="+", markersize=10, linestyle='None') self._axes.set_xlim(self.x_lim_min, self.x_lim_max) plt.show() def onrangeselect(xmin, xmax): indmin, indmax = np.searchsorted(x, (xmin, xmax)) indmax = min(len(x) - 1, indmax) self.x_lim_min = np.min([xmin, xmax]) self.x_lim_max = np.max([xmin, xmax]) self.set_range(xmin, xmax) self.span = SpanSelector(axes, onrangeselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) plt.show()
def setup_watertxt_plot(self): """ Setup the watertxt plot """ self.clear_watertxt_plot() # set up axes and its properties self.axes = self.figure.add_subplot(111) self.axes.grid(True) # create radio buttons self.axes_radio = self.figure.add_axes( [0.01, 0.02, 0.10, 0.15] ) # [left, bottom, width, height] = fractions of figure width and height self.figure.subplots_adjust(bottom=0.2) self.radio_buttons = RadioButtons(ax=self.axes_radio, labels=("Span On", "Span Off"), active=1, activecolor="r") self.radio_buttons.on_clicked(self.toggle_selector) # create SpanSelector; invisble at first unless activated with toggle selector self.span_selector = SpanSelector(self.axes, self.on_select_axes, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) self.span_selector.visible = False
def PlotContrastHistogram(self): self.summedimhist, self.summedimbins = np.histogram(self.summedim, bins = self.contrastbins) self.contrast_ax.cla() self.contrast_ax.plot(self.summedimbins[:-1], self.summedimhist, color = 'k') self.contrast_ax.set_axis_off() self.contrast_span = SpanSelector(self.contrast_ax, self.ContrastSpan, 'horizontal', span_stays = True, rectprops = dict(alpha = 0.5, facecolor = 'green'))
def plot_zmap(self, zmap): self.zmap = zmap gs = gridspec.GridSpec(5, 1) self.fig = plt.figure(figsize=(8, 6)) self.ax1 = self.fig.add_subplot(gs[:4, :]) self.ax1.imshow(zmap) self.ax1.axes.get_xaxis().set_visible(False) self.ax1.axes.get_yaxis().set_visible(False) self.ax2 = self.fig.add_subplot(gs[4, :]) self.ax2.hist(zmap.flatten(), 100, range=(1, zmap.max()), fc='k', ec='k') self.ax2.axes.get_yaxis().set_visible(False) self.rect = Rectangle((0, 0), 0, self.ax2.get_ylim()[1], alpha=.2, color=(1, 0, 0)) self.ax2.add_patch(self.rect) self.span = SpanSelector(self.ax2, self.on_select, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) plt.show()
def __init__(self, parent=None): super(Tdms_read, self).__init__(parent) self.setupUi(self) self.tdms_data = None self.figure_tdms = plt.figure(5) self.ax_tdms = self.figure_tdms.add_subplot(111) self.figure_tdms.subplots_adjust(left=0.1, right=0.9) self.canvas_tdms = FigureCanvas(self.figure_tdms) self.toolbar_tdms = NavigationToolbar(self.canvas_tdms, self) self.verticalLayout_tdms.addWidget(self.toolbar_tdms) self.verticalLayout_tdms.addWidget(self.canvas_tdms) self.tdms_is_view = False self.axs_tdms = self.ax_tdms.twinx() self.openfile.clicked.connect(self.loadtdms) self.plotdata.clicked.connect(self.plottdms) self.savedata.clicked.connect(self.savetdms) self.tdms_span = SpanSelector(self.axs_tdms, self.tdms_onselect, 'horizontal', useblit=True, button=3, rectprops=dict(alpha=0.3, facecolor='g'))
def start_calc_area(self): self.span = SpanSelector(self.Plot.a, self.calc_area, 'horizontal') self.span.connect_event('pick_event',self.calc_area) gcf().canvas.mpl_connect('button_press_event',self.disconnect) return 0
def __init__(self): QtGui.QMainWindow.__init__(self) self.title = ["Browse file"] slots = [self.browseFile] self.resize(200, 150) self.setWindowTitle('Align') self.segnali = [] self.picchi = [] self.ref = 0 self.fig, self.ax1 = plt.subplots(1, 1) self.shift = [] widget = QtGui.QWidget(self) grid = QtGui.QGridLayout(widget) grid.setVerticalSpacing(2) grid.setHorizontalSpacing(1) Browse_button = QtGui.QPushButton('Browse file', widget) self.connect(Browse_button, QtCore.SIGNAL('clicked()'), self.browseFile) self.span = SpanSelector(self.ax1, self.stp, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green'))
def reset_chart(self): self.track_axes.clear() self.track_figure.patch.set_visible(False) self.track_axes.patch.set_visible(False) self.xdata = np.array([]).astype(np.double) self.ydata = np.array([]).astype(np.double) self.idata = np.array([]).astype(np.double) self.rdata = [] self.x_min = 0 self.x_max = 1 self.y_max = 1 self.bracket_set = False self.button_hold = False self.plot_zoom = False self.chart_range = None self.selector = None self.max_lock = True self.patch_x = 0 self.patch_x_last = 1 self.patch_width = 1 self.start_edge = 0 self.end_edge = 1 self.acc_plot = self.track_axes.plot([], [], "o", color="#4575b4")[0] self.rej_plot = self.track_axes.plot([], [], "o", color="#d73027")[0] self.idx_plot = self.track_axes.plot([], [], "wo", ms=2)[0] self.bragg_line = self.track_axes.axhline(0, c="#4575b4", ls=":", alpha=0) self.highlight = self.track_axes.axvspan(0.5, 0.5, ls="--", alpha=0, fc="#deebf7", ec="#2171b5") self.track_axes.set_autoscaley_on(True) self.zoom_span = SpanSelector( ax=self.track_axes, onselect=self.onSelect, direction="horizontal", rectprops=dict(alpha=0.5, ls=":", fc="#ffffd4", ec="#8c2d04"), ) self.zoom_span.set_active(True) self._update_canvas(canvas=self.track_canvas)
def plotFocusSelect(gui, guybrush, dataset, dataset2): def onselect(xmin, xmax): indmin, indmax = np.searchsorted(x, (xmin, xmax)) indmax = min(len(x) - 1, indmax) thisx = x[indmin:indmax] thisy = y[indmin:indmax] line2.set_data(thisx, thisy) ax2.set_xlim(thisx[0], thisx[-1]) ax2.set_ylim(thisy.min(), thisy.max()) gui.canvas.draw() gui.figure = plt.figure() gui.canvas = FigureCanvas(gui.figure) gui.toolbar = NavigationToolbar(gui.canvas, gui) gui.tabWidget_4.insertTab(0, gui.canvas, "Focus-Plot") x = [] for i in range(len(dataset)): x.append(i) y = np.asarray(dataset) ### PLOTTING #################################################### ax = gui.figure.add_subplot(211) ax.plot(x, y, color="black", lw=0.3, marker="+", label='Original') ax.plot(dataset2, color="grey", lw=1.0, linestyle=":", label='Smoothed Component', marker="p") #ax.plot(dataset2) ax.set_ylabel(guybrush.mst_labels[gui.comboBox_PI.currentIndex()]) ax.set_xlabel("t") ax.legend() ax2 = gui.figure.add_subplot(212) line2, = ax2.plot(x, y, label='Original', color="black", lw=0.3, marker="+") ax2.plot(dataset2, color='grey', label='Smoothed Component', lw=1.0, linestyle=":", marker="p") ax2.set_ylabel(guybrush.mst_labels[gui.comboBox_PI.currentIndex()]) ax2.set_xlabel("t") ax2.legend() # set useblit True on gtkagg for enhanced performance gui.figure.span = SpanSelector(ax, onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.3, facecolor='red'))
def __init__(self, ax, **kwargs): SpanSelector.__init__(self, ax, lambda x, y: x + y, 'horizontal', useblit=False, rectprops=dict(alpha=0.5, facecolor='red'), **kwargs) self.xmin = 0.0 self.xmax = 0.0 self.blocking = m_BlockingMouseInput(ax.get_figure(), mouse_add=1, mouse_pop=2, mouse_stop=3) self.blocking(n=2, timeout=30, show_clicks=False)
def __init__(self, *args, **kwargs): MPLCanvas.__init__(self, *args, **kwargs) #inicijalizacija span selectora self.span = SpanSelector(self.axes, self.nakon_odabira, 'horizontal', useblit=True, rectprops=dict(alpha=0.4, facecolor='tomato'))
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.canvas = MyMplCanvas() self.toolbar = NavigationToolbar(self.canvas, self.canvas) #self.toolbar.hide() self.vbox = QtGui.QVBoxLayout() self.vbox.addWidget(self.canvas) self.vbox.addWidget(self.toolbar) self.setLayout(self.vbox) self.ax1 = self.canvas.axDict['ax1'] ###############ZOOM CONTROLS ################ self.zoomAction = QtGui.QAction("Zoom", self) self.zoomAction.setShortcut("Ctrl+Z") self.addAction(self.zoomAction) QtCore.QObject.connect(self.zoomAction, QtCore.SIGNAL("triggered()"), self.ZoomToggle) self.actionAutoScale = QtGui.QAction("AutoScale", self) #self.MainWindow) self.actionAutoScale.setShortcut("Ctrl+A") self.addAction(self.actionAutoScale) QtCore.QObject.connect(self.actionAutoScale, QtCore.SIGNAL("triggered()"), self.autoscale_plot) self.span = SpanSelector(self.ax1, self.onselect, 'horizontal', minspan=0.01, useblit=True, rectprops=dict(alpha=0.5, facecolor='#C6DEFF')) self.hZoom = False self.span.visible = False self.localYMax = 0 self.canvas.mpl_connect('button_press_event', self.onclick) ###########SAVING FIGURE TO CLIPBOARD########## self.cb = None #will be used for the clipboard self.tempPath = getHomeDir() self.tempPath = os.path.join(self.tempPath, 'tempMPL.png') self.mpl2ClipAction = QtGui.QAction("Save to Clipboard", self) self.mpl2ClipAction.setShortcut("Ctrl+C") self.addAction(self.mpl2ClipAction) QtCore.QObject.connect(self.mpl2ClipAction, QtCore.SIGNAL("triggered()"), self.mpl2Clip) #######SAVING FIGURE DATA############################ self.saveCSVAction = QtGui.QAction("Save to CSV", self) self.saveCSVAction.setShortcut("Ctrl+Alt+S") self.addAction(self.saveCSVAction) QtCore.QObject.connect(self.saveCSVAction, QtCore.SIGNAL("triggered()"), self.save2CSV)
def toggle_span(self): self.spanToggleStatus = not self.spanToggleStatus if self.spanToggleStatus == True: self.span1 = SpanSelector(self.axes1, self.on_select_satni, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) self.span2 = SpanSelector(self.axes2, self.flip_flag, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) else: self.span1 = None self.span2 = None
def span_select(self): self.cursor = Cursor(self.MplWidget.canvas.axes, useblit=False, color='blue', linewidth=1,horizOn=False,vertOn=True) self.span = SpanSelector(self.MplWidget.canvas.axes, self.onselect, 'horizontal', useblit=True, span_stays=True, rectprops=dict(alpha=0.5, facecolor='blue')) self.MplWidget.canvas.axes.grid(color='r', linestyle='-', linewidth=0.1) self.span.active=True self.cursor.active = True
def __init__(self, ax, **kwargs): onselect = kwargs.pop('onselect', self.dummy) direction = kwargs.pop('direction', 'horizontal') useblit = kwargs.pop('useblit', ax.figure.canvas.supports_blit) SpanSelector.__init__(self, ax, onselect, direction=direction, useblit=useblit, span_stays=False, **kwargs) # The tolerance in points to pick the rectangle sizes self.tolerance = 1 self.on_move_cid = None self._range = None self.step_ax = None self.bounds_check = False self.buttonDown = False self.snap_size = False self.snap_position = False self.events = Events() self.events.changed = Event(doc=""" Event that triggers when the widget was changed. Arguments: ---------- obj: The widget that changed """, arguments=['obj']) self.events.moved = Event(doc=""" Event that triggers when the widget was moved. Arguments: ---------- obj: The widget that changed """, arguments=['obj']) self.events.resized = Event(doc=""" Event that triggers when the widget was resized. Arguments: ---------- obj: The widget that changed """, arguments=['obj']) self.can_switch = False
def _add(self): if self.show_debug_msg: print('_add()') if float(matplotlib.__version__[0:3])>=1.4: self.multi_cursor.disconnect() self.multi_cursor = MultiCursor(self.fig.canvas, (self.ax1, self.ax2, self.ax3, self.ax4), useblit=True, horizOn=False, vertOn=True, color='g', lw=1) self.span1.disconnect_events() self.span2.disconnect_events() self.span3.disconnect_events() self.span4.disconnect_events() self.span1 = SpanSelector(self.ax1, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span2 = SpanSelector(self.ax2, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span3 = SpanSelector(self.ax3, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span4 = SpanSelector(self.ax4, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.mode_label['text'] = 'Mode: ADD' self.mode_label['bg'] = 'green' self.fig.canvas.draw()
def __init__(self, *args, **kwargs): SpanSelector.__init__(self, *args, **kwargs)
class DisplayWindow(object): global CdMeOTPRef, MeOTPRef color_list = deque(['b','g','r','c','m','y','k']) current_checker = None def __init__(self, master,ax = None): self.rootref = master self.master = Toplevel() self.checker_frame=Tkinter.Frame(master = self.master)#,yscrollcommand=self.scroll.set) #self.scroll.config(command=self.checker_frame.yview) self.frame = Frame(master = self.master) self.Plot = Figure(figsize=(6,3)) self.channel_list = [] self.array_list = [] self.Plot.a = self.Plot.add_subplot(111) self.Plot.a.set_xlabel('Raman Shift (cm$^{-1}$)') self.Plot.a.set_ylabel('Intensity (a.u.)') self.Plot.a.legend([]) self.Plot.a.get_legend().set_visible(False) self.checker_list = self.Plot.a.lines self.legend_var = IntVar() self.legend_var.set(1) self.legendbox = Checkbutton(self.frame, variable=self.legend_var, command=self.update_legend,text='Legend') # self.legend_label=Label(self.master, bd=1, anchor=W) # self.legend_label.config(text = "Legend") self.statusbar = Label(self.master, bd=1, relief=SUNKEN, anchor=W) self.statusbar.config(text = "Ready") self.canvas = FigureCanvasTkAgg(self.Plot,master = self.frame) self.canvas.show() self.master.protocol("WM_DELETE_WINDOW", self.quitproc) self.master.title(string = "RamanViewer") #self.scroll = Tkinter.Scrollbar(self.frame) #self.scroll.pack(side = Tkinter.RIGHT, fill = Tkinter.BOTH) self.checker_frame=Tkinter.Frame(master = self.master)#,yscrollcommand=self.scroll.set) #self.scroll.config(command=self.checker_frame.yview) self.menubar = Menu(self.master) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="New window", command = lambda: DisplayWindow(self.rootref)) self.filemenu.add_command(label="Open", command = self.DisplaySpectrum) self.filemenu.add_command(label="Save",command = self.SaveSpectrum) self.filemenu.add_command(label="SaveFig",command = self.SaveFigure) self.filemenu.add_command(label="ViewNotebook",command = self.ViewNotebook) self.filemenu.add_command(label="Exit", command = self.quitproc) self.menubar.add_cascade(label="File", menu=self.filemenu) # create more pulldown menus self.editmenu = Menu(self.menubar, tearoff=0) self.editmenu.add_command(label="Smooth", command = self.SmoothSpectrum) self.filemenu.add_command(label="Fitting window", command = lambda:FittingWindow(Toplevel(),ramanspectrum=self.current_checker.spectrum))#, kwargs = {'ramanspectrum':self.current_checker.channel.spec_array}) self.editmenu.add_command(label="Calc Noise", command = self.start_calc_noise) self.editmenu.add_command(label="Calc Area", command = self.start_calc_area) self.editmenu.add_command(label="Basline", command = self.start_autobaseline) self.editmenu.add_command(label="disconnect", command = self.disconnect) self.editmenu.add_command(label='Quick Scan',command = self.open_next_spectrum_in_folder) self.editmenu.add_command(label='Normalize All',command = self.normalizeall) self.editmenu.add_command(label='Zero All',command = self.zeroall) self.editmenu.add_command(label = 'FFT process', command=self.FFT) self.editmenu.add_command(label = 'Remove noise', command = self.removenoise) self.editmenu.add_command(label="Copy") self.editmenu.add_command(label="Paste") self.menubar.add_cascade(label="Edit", menu=self.editmenu) self.correctionmenu = Menu(self.menubar,tearoff=0) self.correctionmenu.add_command(label='SPID633', command = self.SPIDcorrect633) self.correctionmenu.add_command(label='SPID785', command = self.SPIDcorrect785) self.menubar.add_cascade(label = 'Corrections', menu = self.correctionmenu) self.notesmenu =Menu(self.menubar, tearoff=0) self.notesmenu.add_command(label = "Notes", command = self.ViewNotebook) self.notesmenu.add_command(label = "Spectrum Info", command = self.showinfo) self.menubar.add_cascade(label = 'Info', menu = self.notesmenu) self.refsmenu =Menu(self.menubar, tearoff=0) self.refsmenu.add_command(label = "chloroform", command = None) self.refsmenu.add_command(label = "CdMeOTP", command = lambda:self.AddChannel(CdMeOTPRef)) self.refsmenu.add_command(label = "MeOTP", command = lambda:self.AddChannel(MeOTPRef)) self.refsmenu.add_command(label = "ClTP", command = lambda:self.AddChannel(ClTPRef)) self.refsmenu.add_command(label = "BrTP", command = lambda:self.AddChannel(BrTPRef)) self.refsmenu.add_command(label = "FTP", command = lambda:self.AddChannel(FTPRef)) self.refsmenu.add_command(label = "MethylTP", command = lambda:self.AddChannel(MethylTPRef)) self.refsmenu.add_command(label = "CdODPA", command = lambda:self.AddChannel(CdODPARef)) self.refsmenu.add_command(label = "toluene", command = lambda:self.AddChannel(tolueneRef)) self.refsmenu.add_command(label = "CdMethylTP", command = lambda:self.AddChannel(CdMethylTPRef)) self.menubar.add_cascade(label = 'References', menu = self.refsmenu) self.master.config(menu= self.menubar) self.left_click_menu = Menu(self.frame, tearoff=0) self.left_click_menu.add_command(label="open", command = self.DisplaySpectrum) # self.left_click_menu.add_command(label="blue", command=lambda:self.change_color('b')) # self.left_click_menu.add_command(label="black", command=lambda:self.change_color('k')) # self.left_click_menu.add_command(label="yellow", command=lambda:self.change_color('y')) # self.canvas._tkcanvas.bind("<Button-3>", self.popup) self.frame.pack(side = TOP, expand=1, fill=BOTH)#(row = 0, column = 0, padx = 25, pady = 25) self.legendbox.pack(side=BOTTOM) self.statusbar.pack(side = BOTTOM,expand=1,fill=X) self.checker_frame.pack(side=BOTTOM,expand = 1,fill=X)#(row=1,column=0) self.canvas._tkcanvas.pack( expand = 1, fill = BOTH) self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.frame) self.toolbar.update() self.toolbar.pack(side= BOTTOM,expand =True) self.canvas.draw() list_of_display_windows.append(self) if ax is not None: for line in ax.lines: self.Plot.a.add_line(checker(self,line,color = line.get_color())) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] plt.close(ax.get_figure()) return None def popup(self,event): print event.x_root, event.y_root self.left_click_menu.post(event.x_root, event.y_root) def update_legend(self): if self.legend_var.get() == 0: self.Plot.a.get_legend().set_visible(False) else: l = list() for entry in self.checker_list: if True:#entry.get_visible(): l.append(entry.commentbox.get()) self.Plot.a.legend(l) self.Plot.canvas.draw() return 0 def showinfo(self): tkMessageBox.showinfo('Spectrum info',self.current_checker.spectrum.info) return 0 def getcolor(self): self.color_list.rotate(1) return self.color_list[0] def DisplaySpectrum(self): import re options = {} #options['defaultextension'] = '.SPE' options['filetypes'] = [('all files','.*'),('SPE','.spe'),('txt', '.txt'),('csv','.csv')] options['multiple'] = True options['title'] = 'Open Spectrum...' options['parent'] = self.master str_name_list = tkFileDialog.askopenfilenames(**options) if type(str_name_list) == tuple: for name in str_name_list: if 'notes' in name: SFG_Notebook.SFG_NotebookWindow(target_file = name) elif name =='': continue else: newspectrum = RamanSpectrum(name) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor())) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] elif str_name_list == '': return 0 elif type(str_name_list) == list: for name in re.split(' ',str_name_list): newspectrum = RamanSpectrum(name) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor())) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return 0 def SaveSpectrum(self): file_opt = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('all files', '.*')] options['title'] = 'Open Spectrum...' options['initialfile'] = os.path.basename(self.current_checker.name) options['parent'] = self.master if self.current_checker == None: return 0 str_filename = tkFileDialog.asksaveasfilename(**options) if str_filename == '': return 0 else: data = transpose([self.current_checker.get_xdata(),self.current_checker.get_ydata()]) savetxt(str_filename,data,delimiter = ',',comments = '#'+str(self.current_checker.spectrum.info))#SaveSpectrum(self.current_checker.channel.spec_array,str_filename) os.chdir(os.path.dirname(str_filename)) return 0 def ViewNotebook(self): print os.path.dirname(self.current_checker.name) try: SFG_Notebook.SFG_NotebookWindow(target_dir = os.path.dirname(self.current_checker.name)) except IOError: tkSimpleDialog.Message('no file found') return 0 def zeroall(self): for c in self.Plot.a.lines: c.set_ydata(c.get_ydata()-min(c.get_ydata())) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() return 0 def SmoothSpectrum(self): if self.current_checker == None: return 0 newspectrum = smooth(self.current_checker.spectrum) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor(),operations = 'sp = smooth(sp)\n')) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return 0 def SPIDcorrect785(self): if self.current_checker == None: return 0 else: newspectrum = SPIDcorrect785(self.current_checker.spectrum) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor(),operations = 'sp = SPIDcorrect785(sp)\n')) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return 0 def SPIDcorrect633(self): if self.current_checker == None: return 0 else: newspectrum = SPIDcorrect633(self.current_checker.spectrum) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor(),operations = 'sp = SPIDcorrect633(sp)\n')) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return 0 def open_next_spectrum_in_folder(self): self.Plot.canvas.mpl_connect('key_press_event',self.open_next_spectrum) for c in self.checker_list[1:]: self.RemoveSpectrum(self.checker) self.checker_list[0].set_current(0) return 0 def open_next_spectrum(self,event): directory_index = os.listdir(os.path.dirname(os.path.abspath(self.current_checker.channel.spec_array.name))) for x in directory_index: if 'txt' not in x: directory_index.remove(x) directory_index.sort() i=directory_index.index(os.path.basename(self.current_checker.channel.spec_array.name)) if i>len(directory_index)-2: i=-1 if 'txt' not in directory_index[1+1]: i+=1 if event.key == 'right': i+=1 elif event.key == 'left': i-=1 try: newspectrum = RamanSpectrum(directory_index[i]) except: print 'error' print 'i=',i return -1 self.RemoveSpectrum(self.current_checker) self.AddChannel(self.newspectrum) self.checker_list[0].set_current(0) return 0 def normalizeall(self): for check in self.checker_list: data = check.get_ydata() data[:]-=min(data) data/=max(data) check.set_ydata(data) self.Plot.a.relim() self.Plot.a.set_ylim(-0.5,1.5) self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() return 0 def start_calc_noise(self): self.span = SpanSelector(self.Plot.a, self.calc_noise, 'horizontal') self.span.connect_event('pick_event',self.calc_noise) gcf().canvas.mpl_connect('button_press_event',self.disconnect) return 0 def start_calc_area(self): self.span = SpanSelector(self.Plot.a, self.calc_area, 'horizontal') self.span.connect_event('pick_event',self.calc_area) gcf().canvas.mpl_connect('button_press_event',self.disconnect) return 0 def start_autobaseline(self): # self.toolbar.release(None) self.span = SpanSelector(self.Plot.a, self.autobaseline, 'horizontal') self.span.connect_event('pick_event',self.autobaseline) gcf().canvas.mpl_connect('button_press_event',self.disconnect) return 0 def autobaseline(self,start,end): order = int(tkSimpleDialog.askinteger('Fit order', 'Choose the polynomial order.')) if order == None: return 0 if self.current_checker == None: return 0 newspectrum = autobaseline(self.current_checker.spectrum,(start,end),order = order) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor(),operations = 'sp = autobaseline(sp), ('+str(start)+','+str(end)+'), order ='+str(order)+')\n')) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] self.span.disconnect_events() return 0 def calc_noise(self,start,end): try: print "STD =", calc_noise(pandas.Series(self.current_checker.channel.get_ydata(),self.current_checker.channel.get_xdata()),(start,end)) except: print 'error' return 0 def calc_area(self, start,end): try: print "Area =", calc_area(pandas.Series(self.current_checker.channel.get_ydata(),self.current_checker.channel.get_xdata()),(start,end)) except: print 'error' return 0 def disconnect(self): #print event.button#gcf().canvas.mpl_disconnect(self.cid) self.span.disconnect_events() return 0 def removenoise(self): newspectrum = removecorrelatednoise(self.current_checker.spectrum) self.Plot.a.add_line(checker(self,newspectrum,operations = 'sp = removecorrelatednoise(sp)',color=self.getcolor())) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return None def AddChannel(self,spectrum): self.Plot.a.add_line(checker(self,spectrum)) self.Plot.a.lines[-1].set_color(self.getcolor()) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return 0 def RemoveSpectrum(self,checker): self.Plot.a.lines.remove(checker) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.canvas.draw() checker.frame.pack_forget() return 0 def SaveFigure(self): os.chdir('/home/chris/Desktop') self.Plot.savefig('figure.png') f = open('/home/chris/Desktop/figure.py','wb') for line in self.Plot.a.lines: f.write(line.operations) f.close() return 0 def FFT(self): return 0 def quitproc(self): self.master.destroy() list_of_display_windows.remove(self) if len(list_of_display_windows)==0: self.rootref.destroy() return 0
class GaussianTool(FigureTool): def __init__(self, windows=None): super(GaussianTool, self).__init__(windows) self.dragging = False self.drag_data = None self.span = None self._old_plot_comp = {} def get_name(self): return "Gaussian tool" def get_category(self): return 'Spectrum' def get_icon(self): return os.path.dirname(__file__) + '/../images/gaussian.svg' def is_selectable(self): return True def make_cursor(self): return crosshair_cursor() def _wire_wrapper(self, wrapper): if wrapper is None: return m = wrapper.model if m._plot.is_active: self._old_plot_comp[wrapper] = m._plot_components m.enable_plot_components() for c in m: if isinstance(c, GaussTypes): c._model_plot_line.line.set_picker(True) def _unwire_wrapper(self, wrapper): if wrapper is None: return m = wrapper.model if wrapper in self._old_plot_comp: for c in m: if isinstance(c, GaussTypes): c._model_plot_line.line.set_picker(False) if not self._old_plot_comp[wrapper]: m.disable_plot_components() def on_pick(self, event): if event.mouseevent.inaxes is None: return ax = event.mouseevent.inaxes if event.mouseevent.button == 3: window = ax.figure.canvas.parent() mw = window.property('hyperspyUI.ModelWrapper') if mw is not None: for c in mw.model: line = c._model_plot_line.line if event.artist == line and \ isinstance(c, GaussTypes): mw.remove_component(c) def connect_windows(self, windows): super(GaussianTool, self).connect_windows(windows) windows = self._iter_windows(windows) for w in windows: mw = w.property('hyperspyUI.ModelWrapper') self._wire_wrapper(mw) def disconnect_windows(self, windows): super(GaussianTool, self).disconnect_windows(windows) windows = self._iter_windows(windows) for w in windows: mw = w.property('hyperspyUI.ModelWrapper') self._unwire_wrapper(mw) def on_mousedown(self, event): if event.inaxes is None: return ax = event.inaxes f = ax.figure x, y = event.xdata, event.ydata if event.button == 1 and event.dblclick: # Add Gaussian here! window = f.canvas.parent() mw = window.property('hyperspyUI.ModelWrapper') if mw is None: sw = window.property('hyperspyUI.SignalWrapper') mw = sw.make_model() self._wire_wrapper(mw) m = mw.model i = m.axis.value2index(x) h = m.signal()[i] - m()[i] if m.signal.metadata.Signal.binned: h /= m.axis.scale g = GaussianHF(height=h * np.sqrt(2 * np.pi), centre=x) g.height.free = False g.centre.free = False mw.add_component(g) g._model_plot_line.line.set_picker(True) m.fit_component(g, signal_range=None, estimate_parameters=False) g.height.free = True g.centre.free = True else: self.dragging = True self.drag_data = [x, y, event.button, ax, event] def on_spanselect(self, x0, x1): self.span.disconnect_events() self.span = None ax = self.drag_data[3] window = ax.figure.canvas.parent() mw = window.property('hyperspyUI.ModelWrapper') if mw is None: sw = window.property('hyperspyUI.SignalWrapper') mw = sw.make_model() self._wire_wrapper(mw) m = mw.model g = GaussianHF() mw.add_component(g) g._model_plot_line.line.set_picker(True) m.fit_component(g, signal_range=(x0, x1)) i = m.axis.value2index(g.centre.value) g.active = False h = m.signal()[i] - m(onlyactive=True)[i] g.active = True if m.signal.metadata.Signal.binned: h /= m.axis.scale g.height.value = h g.height.free = False g.centre.free = False m.fit_component(g, signal_range=(x0, x1), estimate_parameters=False) g.height.free = True g.centre.free = True if self.drag_data is None: return self.drag_data = None def on_mousemove(self, event): if not self.dragging or self.drag_data is None: return ax = self.drag_data[3] if self.span is None: self.dragging = False invtrans = ax.transData.inverted() minspan = 3 * np.abs(invtrans.transform((1, 0)) - invtrans.transform((0, 0)))[0] self.span = SpanSelector(ax, self.on_spanselect, 'horizontal', minspan=minspan) event2 = self.drag_data[4] self.span.press(event2) self.span.onmove(event)
def __init__(self, filename): self.root = Tk.Tk() self.root.wm_title("EMG-Visualization-Tool") self.root.protocol("WM_DELETE_WINDOW", self._quit) if not filename: filename = askopenfilename() if not filename: sys.exit(0) while not os.path.isfile(filename): showerror("File not found", "Sorry, file '{}' was not found, try again".format(filename)) filename = askopenfilename() if not filename: sys.exit(0) if filename[-19:] == '_usage_autosave.pkl': self.autosave_file = filename print('Input file is an Auto-Save file "{}"'.format(self.autosave_file)) filename = filename[:-19] + '.csv' if not os.path.isfile(filename): showerror('Could not find file "{}" (matching to provided auto-save file "{}")'.format(filename, self.autosave_file)) print('Error: matching file not found (expected "{}")'.format(filename)) print('EXIT') sys.exit(0) else: self.load_autosave_file = True else: self.autosave_file = filename.rsplit(".", 1)[0] + "_usage_autosave.pkl" if os.path.isfile(self.autosave_file): print('Auto-Save file "{}" already exists'.format(self.autosave_file)) if askyesno('Auto-Save file found', 'Auto-Save file "{}" found. Load it instead? ("No" will result in automatical overwriting of the file when auto-saving)'.format(self.autosave_file)): self.load_autosave_file = True self.root.wm_title("EMG-Visualization-Tool: {}".format(filename)) self.dataMgr = DataManager(filename) self.csv_out_file = filename.rsplit(".", 1)[0] + "_usage.csv" while os.path.isfile(self.csv_out_file): print('File "{}" already exists'.format(self.csv_out_file)) if askyesno('Overwrite File?', 'File "{}" already exists. Overwrite?'.format(self.csv_out_file)): print('overwriting "{}"'.format(self.csv_out_file)) break else: new_out_file = asksaveasfilename(initialfile=self.csv_out_file) if new_out_file: self.csv_out_file = new_out_file print('New Output file "{}"'.format(self.csv_out_file)) else: sys.exit(0) print("csv-out-file: {}".format(self.csv_out_file)) self.configFrame = Tk.Frame(self.root, height=500, width=400) Tk.Label(self.configFrame, text="\r\nPlot 1").pack() self.plot1_select = ttk.Combobox(self.configFrame, values=self.dataMgr.plot_columns, state="readonly") self.plot1_select.pack() if '"f"' in self.dataMgr.plot_columns: self.plot1_select.current(self.dataMgr.plot_columns.index('"f"')) else: self.plot1_select.current(0) Tk.Label(self.configFrame, text="Plot 2").pack() self.plot2_select = ttk.Combobox(self.configFrame, values=self.dataMgr.plot_columns, state="readonly") self.plot2_select.pack() if '"rmsd"' in self.dataMgr.plot_columns: self.plot2_select.current(self.dataMgr.plot_columns.index('"rmsd"')) else: self.plot2_select.current(0) Tk.Label(self.configFrame, text="Plot 3").pack() self.plot3_select = ttk.Combobox(self.configFrame, values=self.dataMgr.plot_columns, state="readonly") self.plot3_select.pack() if '"beat"' in self.dataMgr.plot_columns: self.plot3_select.current(self.dataMgr.plot_columns.index('"beat"')) else: self.plot3_select.current(0) Tk.Label(self.configFrame, text="\r\nUsage Plot").pack() self.usage_plots = {} for usg in self.dataMgr.usage_columns: if not usg == '"usage_manual"': chkbx_var = Tk.IntVar() chkbx_var.set(1) usg_check = ttk.Checkbutton(self.configFrame, text=usg, variable=chkbx_var) usg_check.pack() self.usage_plots[usg] = chkbx_var Tk.Label(self.configFrame, text="\r\nLoad/copy \"usage_manual\" from").pack() if self.load_autosave_file: Tk.Label(self.configFrame, text="provided Auto-Save file").pack() else: self.usg_man_select = ttk.Combobox(self.configFrame, values=self.dataMgr.usage_columns, state="readonly") self.usg_man_select.pack() if '"usage_manual"' in self.dataMgr.usage_columns: self.usg_man_select.current(self.dataMgr.usage_columns.index('"usage_manual"')) elif '"usage_total"' in self.dataMgr.usage_columns: self.usg_man_select.current(self.dataMgr.usage_columns.index('"usage_total"')) else: if len(self.dataMgr.usage_columns) > 0: self.usg_man_select.current(0) Tk.Label(self.configFrame, text="\r\nJump Column").pack() if len(self.dataMgr.jump_columns) == 0: self.jmp_select = ttk.Combobox(self.configFrame, values=['--none--'], state="readonly") self.jmp_select.current(0) else: self.jmp_select = ttk.Combobox(self.configFrame, values=self.dataMgr.jump_columns, state="readonly") if '"jump_ibi"' in self.dataMgr.jump_columns: self.jmp_select.current(self.dataMgr.jump_columns.index('"jump_ibi"')) else: self.jmp_select.current(0) self.jmp_select.pack() Tk.Label(self.configFrame, text="").pack() button_continue = Tk.Button(self.configFrame, text='Continue', command=self._CfgContinue) button_continue.pack() Tk.Label(self.configFrame, text="").pack() self.loading_label = Tk.Label(self.configFrame, text="") self.loading_label.pack() self.configFrame.pack() self.visualizerFrame = Tk.Frame(self.root) # Figure with Subplots self.fig = plt.figure(figsize=(17,8), dpi=80, tight_layout=True) gs = gridspec.GridSpec(4,1, height_ratios=[3,2,2,1]) self.ax1 = plt.subplot(gs[0]) self.ax2 = plt.subplot(gs[1], sharex=self.ax1) self.ax3 = plt.subplot(gs[2], sharex=self.ax1) self.ax4 = plt.subplot(gs[3], sharex=self.ax1) canvas = FigureCanvasTkAgg(self.fig, master=self.visualizerFrame) canvas.show() canvas.mpl_connect('key_press_event', self.on_key_event) canvas.mpl_connect('button_press_event', self.on_button_event) # GUI Elements self.mode_label = Tk.Label(self.visualizerFrame, text="Mode: ADD", background="green") self.progress_label = Tk.Label(self.visualizerFrame, text="Page {}/{}".format(self.dataMgr.current_page, self.dataMgr.num_pages)) button_prev = Tk.Button(master=self.visualizerFrame, text='Prev', command=self._prev) button_next = Tk.Button(master=self.visualizerFrame, text='Next', command=self._next) button_zoom_in = Tk.Button(master=self.visualizerFrame, text='Zoom In', command=self._zoom_in) button_zoom_out = Tk.Button(master=self.visualizerFrame, text='Zoom Out', command=self._zoom_out) button_add = Tk.Button(master=self.visualizerFrame, text='Add', command=self._add) button_del = Tk.Button(master=self.visualizerFrame, text='Del', command=self._del) saveFrame = Tk.Frame(self.visualizerFrame) button_autosave = Tk.Button(master=saveFrame, text='Auto-Save', command=self._autosave) button_save = Tk.Button(master=saveFrame, text='Save', command=self._save) button_autosave.grid(column=0, row=0) button_save.grid(column=1, row=0) button_quit = Tk.Button(master=self.visualizerFrame, text='Quit', command=self._quit) # Selection self.multi_cursor = MultiCursor(self.fig.canvas, (self.ax1, self.ax2, self.ax3, self.ax4), useblit=True, horizOn=False, vertOn=True, color='g', lw=1) self.span1 = SpanSelector(self.ax1, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span2 = SpanSelector(self.ax2, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span3 = SpanSelector(self.ax3, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span4 = SpanSelector(self.ax4, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) # GUI Layout button_zoom_in.grid(column=0, row=0) button_zoom_out.grid(column=1, row=0) button_prev.grid(column=3, row=0) self.progress_label.grid(column=4, row=0) button_next.grid(column=5, row=0) canvas.get_tk_widget().grid(column=0, row=1, columnspan=6) canvas._tkcanvas.grid(column=0, row=1, columnspan=6) button_add.grid(column=0, row=2) button_del.grid(column=1, row=2) self.mode_label.grid(column=2, row=2, columnspan=2) saveFrame.grid(column=4, row=2) button_quit.grid(column=5, row=2) Tk.mainloop()
class VisualizerWindow: root = [] dataMgr = [] #graphs fig = [] ax1 = [] ax2 = [] ax3 = [] ax4 = [] ylim_ax1 = [] ylim_ax2 = [] ylim_ax3 = [] #data x = [] usage_manual = [] #debug show_debug_msg = False #autosave (-1 for disable) autosave_period = 30 load_autosave_file = False def __init__(self, filename): self.root = Tk.Tk() self.root.wm_title("EMG-Visualization-Tool") self.root.protocol("WM_DELETE_WINDOW", self._quit) if not filename: filename = askopenfilename() if not filename: sys.exit(0) while not os.path.isfile(filename): showerror("File not found", "Sorry, file '{}' was not found, try again".format(filename)) filename = askopenfilename() if not filename: sys.exit(0) if filename[-19:] == '_usage_autosave.pkl': self.autosave_file = filename print('Input file is an Auto-Save file "{}"'.format(self.autosave_file)) filename = filename[:-19] + '.csv' if not os.path.isfile(filename): showerror('Could not find file "{}" (matching to provided auto-save file "{}")'.format(filename, self.autosave_file)) print('Error: matching file not found (expected "{}")'.format(filename)) print('EXIT') sys.exit(0) else: self.load_autosave_file = True else: self.autosave_file = filename.rsplit(".", 1)[0] + "_usage_autosave.pkl" if os.path.isfile(self.autosave_file): print('Auto-Save file "{}" already exists'.format(self.autosave_file)) if askyesno('Auto-Save file found', 'Auto-Save file "{}" found. Load it instead? ("No" will result in automatical overwriting of the file when auto-saving)'.format(self.autosave_file)): self.load_autosave_file = True self.root.wm_title("EMG-Visualization-Tool: {}".format(filename)) self.dataMgr = DataManager(filename) self.csv_out_file = filename.rsplit(".", 1)[0] + "_usage.csv" while os.path.isfile(self.csv_out_file): print('File "{}" already exists'.format(self.csv_out_file)) if askyesno('Overwrite File?', 'File "{}" already exists. Overwrite?'.format(self.csv_out_file)): print('overwriting "{}"'.format(self.csv_out_file)) break else: new_out_file = asksaveasfilename(initialfile=self.csv_out_file) if new_out_file: self.csv_out_file = new_out_file print('New Output file "{}"'.format(self.csv_out_file)) else: sys.exit(0) print("csv-out-file: {}".format(self.csv_out_file)) self.configFrame = Tk.Frame(self.root, height=500, width=400) Tk.Label(self.configFrame, text="\r\nPlot 1").pack() self.plot1_select = ttk.Combobox(self.configFrame, values=self.dataMgr.plot_columns, state="readonly") self.plot1_select.pack() if '"f"' in self.dataMgr.plot_columns: self.plot1_select.current(self.dataMgr.plot_columns.index('"f"')) else: self.plot1_select.current(0) Tk.Label(self.configFrame, text="Plot 2").pack() self.plot2_select = ttk.Combobox(self.configFrame, values=self.dataMgr.plot_columns, state="readonly") self.plot2_select.pack() if '"rmsd"' in self.dataMgr.plot_columns: self.plot2_select.current(self.dataMgr.plot_columns.index('"rmsd"')) else: self.plot2_select.current(0) Tk.Label(self.configFrame, text="Plot 3").pack() self.plot3_select = ttk.Combobox(self.configFrame, values=self.dataMgr.plot_columns, state="readonly") self.plot3_select.pack() if '"beat"' in self.dataMgr.plot_columns: self.plot3_select.current(self.dataMgr.plot_columns.index('"beat"')) else: self.plot3_select.current(0) Tk.Label(self.configFrame, text="\r\nUsage Plot").pack() self.usage_plots = {} for usg in self.dataMgr.usage_columns: if not usg == '"usage_manual"': chkbx_var = Tk.IntVar() chkbx_var.set(1) usg_check = ttk.Checkbutton(self.configFrame, text=usg, variable=chkbx_var) usg_check.pack() self.usage_plots[usg] = chkbx_var Tk.Label(self.configFrame, text="\r\nLoad/copy \"usage_manual\" from").pack() if self.load_autosave_file: Tk.Label(self.configFrame, text="provided Auto-Save file").pack() else: self.usg_man_select = ttk.Combobox(self.configFrame, values=self.dataMgr.usage_columns, state="readonly") self.usg_man_select.pack() if '"usage_manual"' in self.dataMgr.usage_columns: self.usg_man_select.current(self.dataMgr.usage_columns.index('"usage_manual"')) elif '"usage_total"' in self.dataMgr.usage_columns: self.usg_man_select.current(self.dataMgr.usage_columns.index('"usage_total"')) else: if len(self.dataMgr.usage_columns) > 0: self.usg_man_select.current(0) Tk.Label(self.configFrame, text="\r\nJump Column").pack() if len(self.dataMgr.jump_columns) == 0: self.jmp_select = ttk.Combobox(self.configFrame, values=['--none--'], state="readonly") self.jmp_select.current(0) else: self.jmp_select = ttk.Combobox(self.configFrame, values=self.dataMgr.jump_columns, state="readonly") if '"jump_ibi"' in self.dataMgr.jump_columns: self.jmp_select.current(self.dataMgr.jump_columns.index('"jump_ibi"')) else: self.jmp_select.current(0) self.jmp_select.pack() Tk.Label(self.configFrame, text="").pack() button_continue = Tk.Button(self.configFrame, text='Continue', command=self._CfgContinue) button_continue.pack() Tk.Label(self.configFrame, text="").pack() self.loading_label = Tk.Label(self.configFrame, text="") self.loading_label.pack() self.configFrame.pack() self.visualizerFrame = Tk.Frame(self.root) # Figure with Subplots self.fig = plt.figure(figsize=(17,8), dpi=80, tight_layout=True) gs = gridspec.GridSpec(4,1, height_ratios=[3,2,2,1]) self.ax1 = plt.subplot(gs[0]) self.ax2 = plt.subplot(gs[1], sharex=self.ax1) self.ax3 = plt.subplot(gs[2], sharex=self.ax1) self.ax4 = plt.subplot(gs[3], sharex=self.ax1) canvas = FigureCanvasTkAgg(self.fig, master=self.visualizerFrame) canvas.show() canvas.mpl_connect('key_press_event', self.on_key_event) canvas.mpl_connect('button_press_event', self.on_button_event) # GUI Elements self.mode_label = Tk.Label(self.visualizerFrame, text="Mode: ADD", background="green") self.progress_label = Tk.Label(self.visualizerFrame, text="Page {}/{}".format(self.dataMgr.current_page, self.dataMgr.num_pages)) button_prev = Tk.Button(master=self.visualizerFrame, text='Prev', command=self._prev) button_next = Tk.Button(master=self.visualizerFrame, text='Next', command=self._next) button_zoom_in = Tk.Button(master=self.visualizerFrame, text='Zoom In', command=self._zoom_in) button_zoom_out = Tk.Button(master=self.visualizerFrame, text='Zoom Out', command=self._zoom_out) button_add = Tk.Button(master=self.visualizerFrame, text='Add', command=self._add) button_del = Tk.Button(master=self.visualizerFrame, text='Del', command=self._del) saveFrame = Tk.Frame(self.visualizerFrame) button_autosave = Tk.Button(master=saveFrame, text='Auto-Save', command=self._autosave) button_save = Tk.Button(master=saveFrame, text='Save', command=self._save) button_autosave.grid(column=0, row=0) button_save.grid(column=1, row=0) button_quit = Tk.Button(master=self.visualizerFrame, text='Quit', command=self._quit) # Selection self.multi_cursor = MultiCursor(self.fig.canvas, (self.ax1, self.ax2, self.ax3, self.ax4), useblit=True, horizOn=False, vertOn=True, color='g', lw=1) self.span1 = SpanSelector(self.ax1, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span2 = SpanSelector(self.ax2, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span3 = SpanSelector(self.ax3, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span4 = SpanSelector(self.ax4, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) # GUI Layout button_zoom_in.grid(column=0, row=0) button_zoom_out.grid(column=1, row=0) button_prev.grid(column=3, row=0) self.progress_label.grid(column=4, row=0) button_next.grid(column=5, row=0) canvas.get_tk_widget().grid(column=0, row=1, columnspan=6) canvas._tkcanvas.grid(column=0, row=1, columnspan=6) button_add.grid(column=0, row=2) button_del.grid(column=1, row=2) self.mode_label.grid(column=2, row=2, columnspan=2) saveFrame.grid(column=4, row=2) button_quit.grid(column=5, row=2) Tk.mainloop() def _CfgContinue(self): self.loading_label['text'] = 'loading ...' self.loading_label.update() self.plot_names = [self.plot1_select.get(), self.plot2_select.get(), self.plot3_select.get()] self.plot_cols = [] for pn in self.plot_names: self.plot_cols.append(self.dataMgr.header_columns.index(pn)) self.usage_names = [] self.usage_cols = [] for k,v in self.usage_plots.items(): if v.get() == 1: self.usage_names.append(k) self.usage_cols.append(self.dataMgr.header_columns.index(k)) if self.load_autosave_file: usg_manual_col = -1 else: if self.usg_man_select.get() in self.dataMgr.header_columns: usg_manual_col = self.dataMgr.header_columns.index(self.usg_man_select.get()) else: usg_manual_col = -1 if self.jmp_select.get() in self.dataMgr.jump_columns: jmp_col = self.dataMgr.header_columns.index(self.jmp_select.get()) else: jmp_col = -1 [self.x, self.plot_data, self.usage_data, self.usage_manual, self.jump_positions] = self.dataMgr.readData(self.plot_cols,self.usage_cols,self.loading_label, usg_manual_col, jmp_col) if self.load_autosave_file: infile = open(self.autosave_file, 'rb') self.usage_manual = pickle.load(infile) infile.close() self.configFrame.pack_forget() self.visualizerFrame.pack() print("displaying plots") self.ylim_ax1 = self.calc_ylims(self.plot_data[0]) self.ylim_ax2 = self.calc_ylims(self.plot_data[1]) self.ylim_ax3 = self.calc_ylims(self.plot_data[2]) self.loadPage(1) def HMS(seconds, pos): """Customized x-axis ticks Keyword arguments: seconds -- input in secs pos -- somehow required argument (matplotlib) """ seconds = int(seconds) hours = seconds / 3600 seconds -= 3600 * hours minutes = seconds / 60 seconds -= 60 * minutes if hours == 0: if minutes == 0: return "%ds" % (seconds) return "%dm%02ds" % (minutes, seconds) return "%dh%02dm" % (hours, minutes) def calc_ylims(self, data): [cnt, edge] = np.histogram(data, 25) s = len(data) thres = 0.975*s i = 0 j = len(cnt)-1 while True: if cnt[i] < cnt[j]: if s-cnt[i] < thres: break else: s -= cnt[i] i += 1 else: if s-cnt[j] < thres: break else: s -= cnt[j] j -= 1 return [min(0, edge[i]), max(1, edge[j+1])] def plotPage(self): index_low = self.dataMgr.low_Idx() index_high = self.dataMgr.high_Idx() if self.show_debug_msg: print("index_low: {} | index_high: {}".format(index_low, index_high)) self.ax1.clear() self.ax1.xaxis.set_major_formatter(plt.FuncFormatter(self.HMS)) self.ax1.plot(self.x[index_low:index_high], np.array(self.plot_data[0][index_low:index_high])) self.ax1.set_ylim(self.ylim_ax1) self.ax1.set_title(self.plot_names[0]) self.ax2.clear() self.ax2.plot(self.x[index_low:index_high], self.plot_data[1][index_low:index_high]) self.ax2.set_ylim(self.ylim_ax2) self.ax2.set_title(self.plot_names[1]) self.ax3.clear() self.ax3.plot(self.x[index_low:index_high], self.plot_data[2][index_low:index_high]) self.ax3.set_ylim(self.ylim_ax3) self.ax3.set_title(self.plot_names[2]) self.plotUsages() self.fig.canvas.draw() def plotUsages(self): index_low = self.dataMgr.low_Idx() index_high = self.dataMgr.high_Idx() self.ax4.clear() self.ax4.set_ylim(0,len(self.usage_names)+2) self.ax4.set_yticks([], minor=False) colors = ['#483D8B', '#228B22', '#B22222', '#8A2BE2', '#808000', '#FF4500', '#DA70D6', '#FFA500'] self.ax4.fill_between(self.x[index_low:index_high], 0, (len(self.usage_names)+2)*np.array(self.usage_manual[index_low:index_high]), facecolor='#7fbf7f', edgecolor='None') self.ax4.plot(self.jump_positions, [len(self.usage_names)+1]*len(self.jump_positions), 'r*') for u in range(0,len(self.usage_data)): self.ax4.fill_between(self.x[index_low:index_high], u, u+np.array(self.usage_data[u][index_low:index_high]), facecolor=colors[u], edgecolor='None') patches = [mpatches.Patch(color='green', alpha=0.5, label='usage_manual')] for i in range(0,len(self.usage_names)): patches.append(mpatches.Patch(color=colors[i], label=self.usage_names[i])) plt.legend(bbox_to_anchor=(0., 1.0, 1., .102), loc=3, ncol=5, mode="expand", borderaxespad=0., handles=patches) self.ax1.set_xlim(self.dataMgr.low_Xlimit(),self.dataMgr.high_Xlimit()) def onselectAdd(self, xmin, xmax): minIdx = max(0, round(xmin*500)) maxIdx = min(self.dataMgr.file_length-1, round(xmax*500)) if self.show_debug_msg: print("ADD: xmin: {} | xmax: {}".format(xmin, xmax)) print("ADD: minIdx: {} | maxIdx: {}".format(minIdx, maxIdx)) self.usage_manual[minIdx:maxIdx] = 1 self.plotUsages() self.fig.canvas.draw() def onselectDel(self, xmin, xmax): minIdx = max(0, round(xmin*500)) maxIdx = min(self.dataMgr.file_length-1, round(xmax*500)) if self.show_debug_msg: print("DEL: xmin: {} | xmax: {}".format(xmin, xmax)) print("DEL: minIdx: {} | maxIdx: {}".format(minIdx, maxIdx)) self.usage_manual[minIdx:maxIdx] = 0 self.plotUsages() self.fig.canvas.draw() def onselectZoom(self, xmin, xmax): if self.show_debug_msg: print("ZOOM: xmin: {} | xmax: {}".format(xmin, xmax)) self.plotUsages() self.ax1.set_xlim(xmin,xmax) self.fig.canvas.draw() def on_key_event(self, event): if self.show_debug_msg: print('you pressed %s'%event.key) if event.key == 'a': self._prev() elif event.key == 'd': self._next() elif event.key == 'w': self._add() elif event.key == 's': self._del() elif event.key == 'q': self._zoom_in() elif event.key == 'e': self._zoom_out() elif event.key == 'r': self._save() elif event.key == 'f': self._autosave() elif event.key == 'x': self._prevJump() elif event.key == 'c': self._nextJump() elif event.key == 'left': self._prev() elif event.key == 'right': self._next() elif event.key == 'up': self._add() elif event.key == 'down': self._del() def on_button_event(self, event): if self.show_debug_msg: print('you clicked %s'%event.button) if event.button == 3: #right mouse button self._zoom_out() elif event.button == 2: #middle mouse button (scroll wheel) self._zoom_in() def _quit(self): self.root.quit() # stops mainloop self.root.destroy() # this is necessary on Windows to prevent # Fatal Python Error: PyEval_RestoreThread: NULL tstate def _prev(self): if self.show_debug_msg: print('_prev()') if self.dataMgr.current_page > 1: self.loadPage(self.dataMgr.current_page-1) def _next(self): if self.show_debug_msg: print('next()') if self.dataMgr.current_page < self.dataMgr.num_pages: self.loadPage(self.dataMgr.current_page+1) def _prevJump(self): if self.show_debug_msg: print('_prevJump()') if self.dataMgr.current_page > 1: for p in reversed(self.jump_positions): num = self.dataMgr.getPageNumByX(p) if num < self.dataMgr.current_page: self.loadPage(num) break def _nextJump(self): if self.show_debug_msg: print('nextJump()') if self.dataMgr.current_page < self.dataMgr.num_pages: for p in self.jump_positions: num = self.dataMgr.getPageNumByX(p) if num > self.dataMgr.current_page: self.loadPage(num) break def loadPage(self, page_num): if self.autosave_period > -1 and page_num % self.autosave_period == 0: if self.show_debug_msg: print('autosaving on page {}'.format(page_num)) self._autosave() self.dataMgr.current_page = min(max(1, page_num), self.dataMgr.num_pages) if self.show_debug_msg: print('loadPage(): {}'.format(self.dataMgr.current_page)) self.plotPage() self.progress_label["text"] ="Page {}/{}".format(self.dataMgr.current_page, self.dataMgr.num_pages) def _add(self): if self.show_debug_msg: print('_add()') if float(matplotlib.__version__[0:3])>=1.4: self.multi_cursor.disconnect() self.multi_cursor = MultiCursor(self.fig.canvas, (self.ax1, self.ax2, self.ax3, self.ax4), useblit=True, horizOn=False, vertOn=True, color='g', lw=1) self.span1.disconnect_events() self.span2.disconnect_events() self.span3.disconnect_events() self.span4.disconnect_events() self.span1 = SpanSelector(self.ax1, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span2 = SpanSelector(self.ax2, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span3 = SpanSelector(self.ax3, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.span4 = SpanSelector(self.ax4, self.onselectAdd, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='green') ) self.mode_label['text'] = 'Mode: ADD' self.mode_label['bg'] = 'green' self.fig.canvas.draw() def _del(self): if self.show_debug_msg: print('_del()') if float(matplotlib.__version__[0:3])>=1.4: self.multi_cursor.disconnect() self.multi_cursor = MultiCursor(self.fig.canvas, (self.ax1, self.ax2, self.ax3, self.ax4), useblit=True, horizOn=False, vertOn=True, color='r', lw=1) self.span1.disconnect_events() self.span1.disconnect_events() self.span2.disconnect_events() self.span3.disconnect_events() self.span4.disconnect_events() self.span1 = SpanSelector(self.ax1, self.onselectDel, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red') ) self.span2 = SpanSelector(self.ax2, self.onselectDel, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red') ) self.span3 = SpanSelector(self.ax3, self.onselectDel, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red') ) self.span4 = SpanSelector(self.ax4, self.onselectDel, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red') ) self.mode_label['text'] = 'Mode: DEL' self.mode_label['bg'] = 'red' self.fig.canvas.draw() def _zoom_in(self): if self.show_debug_msg: print('_zoom_in()') if float(matplotlib.__version__[0:3])>=1.4: self.multi_cursor.disconnect() self.multi_cursor = MultiCursor(self.fig.canvas, (self.ax1, self.ax2, self.ax3, self.ax4), useblit=True, horizOn=False, vertOn=True, color='b', lw=1) self.span1.disconnect_events() self.span1.disconnect_events() self.span2.disconnect_events() self.span3.disconnect_events() self.span4.disconnect_events() self.span1 = SpanSelector(self.ax1, self.onselectZoom, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='blue') ) self.span2 = SpanSelector(self.ax2, self.onselectZoom, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='blue') ) self.span3 = SpanSelector(self.ax3, self.onselectZoom, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='blue') ) self.span4 = SpanSelector(self.ax4, self.onselectZoom, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='blue') ) self.mode_label['text'] = 'Mode: ZOOM' self.mode_label['bg'] = 'blue' self.fig.canvas.draw() def _zoom_out(self): if self.show_debug_msg: print('_zoom_out()') self.plotUsages() self.fig.canvas.draw() def _save(self): if self.show_debug_msg: print('_save()') savetxt = plt.text(20, 20, 'saving...', fontsize=46, color='r', weight='bold', ha='center', va='top') self.fig.canvas.draw() self.dataMgr.writeCSV(self.csv_out_file, self.usage_manual) savetxt.remove() self.fig.canvas.draw() if os.path.isfile(self.autosave_file): archive_filename = self.autosave_file.rsplit(".", 1)[0] + "_old.pkl" print('renaming autosave file from "{}" to "{}"'.format(self.autosave_file, archive_filename)) if os.path.isfile(archive_filename): os.unlink(archive_filename) os.rename(self.autosave_file, archive_filename) def _autosave(self): if self.show_debug_msg: print('_autosave()') savetxt = plt.text(20, 20, 'autosaving...', fontsize=46, color='r', weight='bold', ha='center', va='top') self.fig.canvas.draw() self.dataMgr.writeAutoSave(self.autosave_file, self.usage_manual) savetxt.remove() self.fig.canvas.draw()
legend2.get_frame().set_alpha(0.5) legend2.draggable(state=True) # show text of mean, max, min values on graph; use matplotlib.patch.Patch properies and bbox text2 = 'mean = %.2f\nmax = %.2f\nmin = %.2f' % (parameter['mean'], parameter['max'], parameter['min']) patch_properties = {'boxstyle': 'round', 'facecolor': 'wheat', 'alpha': 0.5 } ax2_text = ax2.text(0.05, 0.95, text2, transform = ax2.transAxes, fontsize = 14, verticalalignment = 'top', horizontalalignment = 'left', bbox = patch_properties) # make a splan selector and have it turned off initially until user # presses 'q' or 'a' on the key board via toggle_selector span = SpanSelector(ax1, onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) span.visible = False # connect span with the toggle selector in order to toggle span selector on and off span.connect_event('key_press_event', toggle_selector) # make sure that the layout of the subplots do not overlap plt.tight_layout() plt.show() except IOError as error: print 'cannot read file' + error.filename print error.message except IndexError as error: print 'Cannot read file! Bad file!'