Exemplo n.º 1
0
    def actionfunc(self, damage_type):

        # 损伤SpanSelector对象
        self.span3_red = SpanSelector(self.ax3, self.onselect3, 'vertical', useblit=True,
                                      rectprops=dict(alpha=0.5, facecolor='red'), span_stays=True)
        # 结垢SpanSelector对象
        self.span3_green = SpanSelector(self.ax3, self.onselect3, 'vertical', useblit=True,
                                        rectprops=dict(alpha=0.5, facecolor='green'), span_stays=True)
        # 变形SpanSelector对象
        self.span3_yellow = SpanSelector(self.ax3, self.onselect3, 'vertical', useblit=True,
                                         rectprops=dict(alpha=0.5, facecolor='yellow'), span_stays=True)
        if damage_type == 'Penetration':
            print(damage_type)
            self.damage_Tag = 'Penetration'
            # del self.span3_red
            del self.span3_green
            del self.span3_yellow
        elif damage_type == 'Projection':
            print(damage_type)
            self.damage_Tag = 'Projection'
            del self.span3_red
            # del self.span3_green
            del self.span3_yellow
        elif damage_type == 'Transformation':
            print(damage_type)
            self.damage_Tag = 'Transformation'
            del self.span3_red
            del self.span3_green
Exemplo n.º 2
0
def interactive_plot(data):
    global ax1

    fig, ax1 = plt.subplots(1, figsize=(8, 6))
    #    ax1.set(facecolor='#FFFFCC')

    ax1.plot(data)
    ax1.set_title('Markiere mit der linken Maustaste einen Bereich')
    callback = Index()
    axprev = plt.axes([0.8, 0.01, 0.1, 0.075])
    bclose = Button(axprev, 'Schließen')

    span1 = SpanSelector(ax=ax1,
                         onselect=onselect,
                         direction='horizontal',
                         useblit=True,
                         minspan=2,
                         button=1,
                         rectprops=dict(alpha=0.5, facecolor='red'))

    span2 = SpanSelector(ax=ax1,
                         onselect=offselect,
                         direction='horizontal',
                         useblit=True,
                         minspan=2,
                         button=3,
                         rectprops=dict(alpha=0.5, facecolor='red'))

    bclose.on_clicked(callback.close)

    plt.show()
    del span1, span2
    return coords['min'], coords['max']
Exemplo n.º 3
0
    def __init__(self, data):
        # save reference to data and generate "time" for interpretable X-axis
        self.data = utils.check_physio(data, copy=True)
        fs = 1 if data.fs is None else data.fs
        self.time = np.arange(0, len(data.data) / fs, 1 / fs)

        # we need to create these variables in case someone doesn't "quit"
        # the plot appropriately (i.e., clicks X instead of pressing ctrl+q)
        self.deleted, self.rejected = set(), set()

        # make main plot objects
        self.fig, self.ax = plt.subplots(nrows=1, ncols=1, tight_layout=True)
        self.fig.canvas.mpl_connect('scroll_event', self.on_wheel)
        self.fig.canvas.mpl_connect('key_press_event', self.on_key)

        # two selectors for rejection (left mouse) and deletion (right mouse)
        reject = functools.partial(self.on_remove, reject=True)
        delete = functools.partial(self.on_remove, reject=False)
        self.span1 = SpanSelector(self.ax,
                                  reject,
                                  'horizontal',
                                  button=1,
                                  useblit=True,
                                  rectprops=dict(facecolor='red', alpha=0.3))
        self.span2 = SpanSelector(self.ax,
                                  delete,
                                  'horizontal',
                                  button=3,
                                  useblit=True,
                                  rectprops=dict(facecolor='blue', alpha=0.3))

        self.plot_signals(False)
    def configure_selector(self,frange=False,peaks=False):
        self.peaks_selector = SpanSelector(self.axs[0], self.onselect, 'horizontal', useblit=True,
                                               rectprops=dict(alpha=0.5, facecolor='red'))
        self.peaks_selector.set_active(peaks)

        self.range_selector = SpanSelector(self.axs[0], self.onselect, 'horizontal', useblit=True,
                                     rectprops=dict(alpha=0.5, facecolor='g'))
        self.range_selector.set_active(frange)
Exemplo n.º 5
0
def convert_iq_and_plot_from_mem(in_file, number):
    """ remove GNSS data from the IQ file and plot it from memory. """

    global TRIM_PROC, fig, a_x, span, span2
    # Remove GNSS data from the IQ file
    old_f = open(in_file, 'rb')
    old_size = os.path.getsize(in_file)
    data_size = 2048 * ((old_size - 36) // 2074)
    new_f = BytesIO()
    new_f.write(old_f.read(36))
    new_f.write(b'data')
    new_f.write(struct.pack('<i', data_size))
    for i in range(62, old_size, 2074):
        old_f.seek(i)
        new_f.write(old_f.read(2048))
    old_f.close()
    new_f.seek(0, 0)
    data = np.frombuffer(new_f.getvalue(), dtype='int16')
    data = data[0::2] + 1j * data[1::2]
    # Plot the IQ w/o GNSS data
    plt.rcParams['toolbar'] = 'None'
    fig, a_x = plt.subplots()
    plt.specgram(data,
                 NFFT=1024,
                 Fs=12000,
                 window=lambda data: data * np.hanning(len(data)),
                 noverlap=512,
                 vmin=10,
                 vmax=200,
                 cmap=COLORMAP)
    plt.xlabel("Time (s)")
    ticks = FuncFormatter(lambda x, pos: FREQUENCY + (x // 1e3))
    a_x.yaxis.set_major_formatter(ticks)
    a_x.set_ybound(-6000.0, 6000.0)
    if TRIM_PROC == 1:
        plt.title(in_file.rsplit("_", 2)[1] + " - [" + str(number) + "/" +
                  str(TOTAL_FILES) + "]",
                  fontsize=10)
        span = SpanSelector(a_x,
                            onselect,
                            'horizontal',
                            useblit=True,
                            rectprops=dict(alpha=0.4, facecolor='red'))
        span2 = SpanSelector(a_x,
                             onselect2,
                             'horizontal',
                             useblit=True,
                             rectprops=dict(alpha=0.4, facecolor='green'))
        fig.canvas.mpl_connect('motion_notify_event', on_mouse_move)
        fig.canvas.mpl_connect('button_press_event', on_mouse_click)
    else:
        plt.gcf().set_facecolor("yellow")
        fig.canvas.mpl_connect('button_press_event', on_press)
        plt.title(in_file.rsplit("_", 2)[1] + " - [" + str(number) + "/" +
                  str(TOTAL_FILES) + "]" + " - [trimmed IQ preview]",
                  fontsize=10)
        TRIM_PROC = 1
    plt.show()
Exemplo n.º 6
0
    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 __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()
Exemplo n.º 8
0
    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()
Exemplo n.º 9
0
    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, 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'))
Exemplo n.º 11
0
    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()
Exemplo n.º 12
0
    def create_canvas(self):
        self.fig = plt.figure()
        self.canvas = FigureCanvas(self.fig)
        self.axes = plt.subplot(111)
        self.axes.set_xlabel("Scans")
        self.axes.set_ylabel("Instensity")
        self.axes.set_title("Least Square Fitting(2D)", fontsize=9)
        self.axes.tick_params(axis='both', labelsize=8)
        plt.subplots_adjust(bottom=0.22, top=0.90, left=0.08, right=0.9)

        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])

        axspan = plt.axes([0.09, 0.04, 0.08, 0.075])
        axundo = plt.axes([0.2, 0.04, 0.08, 0.075])
        axstar = plt.axes([0.31, 0.04, 0.08, 0.075])
        self.btnspan = Button(axspan, 'span')
        self.btnundo = Button(axundo, 'undo')
        self.btnstar = Button(axstar, 'start')

        self.btnspan.on_clicked(self.span_mode)
        self.btnundo.on_clicked(self.undo_mode)
        self.btnstar.on_clicked(self.star_mode)

        self.span.set_active(True)
        self.redraw()
        ymino, ymaxo = self.axes.get_ylim()
        xmino, xmaxo = self.axes.get_xlim()
        self.oxy = [(xmino, xmaxo), (ymino, ymaxo)]
Exemplo n.º 13
0
    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'))
Exemplo n.º 15
0
    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()
Exemplo n.º 16
0
    def _setup_ui(self):
        # Add a side menu for specifying the wavelength of the selected line
        panel = QtWidgets.QWidget()

        label = QtWidgets.QLabel("Enter wavelength [Å]:", panel)
        help_label = QtWidgets.QLabel("Enter a wavelength value, zoom in, then select the region "
                                      "containing the emission line at the specified wavelength.",
                                      panel)
        help_label.setStyleSheet("font-style: italic;")
        self._ui['textbox'] = QtWidgets.QLineEdit(parent=panel)

        panel.layout = QtWidgets.QGridLayout(panel)
        panel.layout.addWidget(label, 0, 0, 1, 1)
        panel.layout.addWidget(self._ui['textbox'], 0, 1, 1, 1)
        panel.layout.addWidget(help_label, 1, 0, 1, 2, Qt.AlignCenter)

        main_window = self.fig.canvas.manager.window
        dock = QtWidgets.QDockWidget("Enter wavelength:", main_window)
        main_window.addDockWidget(Qt.BottomDockWidgetArea, dock)
        dock.setWidget(panel)

        # A 1D span selector to highlight a given line
        span = SpanSelector(self.ax, self._on_select, 'horizontal', useblit=True,
                            rectprops=dict(alpha=0.5, facecolor='red'))
        span.set_active(False)

        def enable_span():
            tb = self.fig.canvas.manager.toolbar

            if span.active:
                span.set_active(False)
            else:
                span.set_active(True)

            if tb._active == 'PAN':
                tb.pan()
                tb._actions['pan'].setChecked(False)

            if tb._active == 'ZOOM':
                tb.zoom()
                tb._actions['zoom'].setChecked(False)

        span_control = QtWidgets.QPushButton('λ')
        span_control.setCheckable(True)
        span_control.clicked.connect(enable_span)
        span_control.setStyleSheet("color: #de2d26; font-weight: bold;")
        self.fig.canvas.manager.toolbar.addWidget(span_control)

        # setup auto-identify button
        if self.line_list is not None:
            autoid_control = QtWidgets.QPushButton('auto-identify')
            autoid_control.clicked.connect(self.auto_identify)
            self.fig.canvas.manager.toolbar.addWidget(autoid_control)

        # add a button for "done"
        done_control = QtWidgets.QPushButton('done')
        done_control.clicked.connect(self._finish)
        self.fig.canvas.manager.toolbar.addWidget(done_control)

        plt.show()
Exemplo n.º 17
0
 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)
Exemplo n.º 18
0
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)
Exemplo n.º 19
0
        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)
Exemplo n.º 20
0
    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'))
Exemplo n.º 21
0
 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()
Exemplo n.º 22
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 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()
Exemplo n.º 24
0
    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')
Exemplo n.º 25
0
    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()
Exemplo n.º 26
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
Exemplo n.º 27
0
    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'))
Exemplo n.º 28
0
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'))
Exemplo n.º 29
0
    def __init__(self, master, path, toolitems):
        logging.basicConfig(filename='event_log.log', level=logging.INFO)
        FIGSIZE = (8, 3)
        self.window_id = next(self.id_generator)
        self.master = master
        self.toolitems = toolitems

        self.master.protocol("WM_DELETE_WINDOW", self.master.quit)
        master.title("BrainWave Visualization")
        master.state('zoomed')
        master.protocol("WM_DELETE_WINDOW", self.root_close)

        self.initialize_annotation_display()

        self.initialize_graph_display(FIGSIZE)

        self.project_path = path
        self.json_path = self.project_path + "annotations.json"
        try:
            self.data, self.timestamps, self.annotations = data.open_project(
                path)
            if self.annotations != []:
                if self.annotations[0] == -1:
                    messagebox.showerror("Error: ", self.annotations[1])
                    self.annotations = []
            self.draw_graph(self.data, self.timestamps, self.annotations)
            for id in self.annotations:
                id = id.id
                self.index_to_ids.append(id)
            for a in self.annotations:
                self.listb.insert(tkinter.END, a.title)
        except Exception as e:
            logging.error('Error during opening initial project')
            logging.error(e)
            messagebox.showerror("Error:", e)

        # put the plot with navbar on the tkinter window
        self.main_canvas.mpl_connect('button_release_event', self.butrelease)

        # add span selector to the axes but set it defaultly to not visible,
        # only activate it when the button annotate is pressed
        self.span = SpanSelector(self.main_graph_ax,
                                 self.onselect,
                                 'horizontal',
                                 useblit=True,
                                 rectprops=dict(alpha=0.5, facecolor='red'),
                                 span_stays=True)
        self.span.set_visible(False)

        # create buttons for interaction
        self.annotate_button = Button(master, command=self.annotate)

        self.export_button = Button(master, command=self.export)

        self.close_button = Button(master, command=master.quit)

        # variables for storing min and max of the current span selection
        self.span_min = None
        self.span_max = None
Exemplo n.º 30
0
 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'))