Ejemplo n.º 1
0
 def __init__(self, ax):
     self.time_lbl = ax.text(0.02, 0.95, '', transform=ax.transAxes)
     self.power_lbl = ax.text(0.02, 0.90, '', transform=ax.transAxes)
     self.rotation_lbl = ax.text(0.02, 0.85, '', transform=ax.transAxes)
     self.hs_lbl = ax.text(0.02, 0.80, '', transform=ax.transAxes)
     self.vs_lbl = ax.text(0.02, 0.75, '', transform=ax.transAxes)
     self.fuel_lbl = ax.text(0.02, 0.70, '', transform=ax.transAxes)
     # BUTTONS
     # TODO: Reset
     # TODO: run,pause, next/prev frame
     # SLIDERS
     ax_power = plt.axes([0.2, 0.02, 0.5, 0.02])
     ax_rotation = plt.axes([0.2, 0.08, 0.5, 0.02])
     self.slider_power = plt.Slider(ax_power, 'Power', valmin=0, valmax=4, valinit=0, valstep=1)
     self.slider_rotation = plt.Slider(ax_rotation, 'Rotation', valmin=-90, valmax=90, valinit=0, valstep=1)
Ejemplo n.º 2
0
def draw(robots, create_video_path=None):
    fig, ax = plt.subplots()
    size = 0
    for name, arr in robots.items():
        x = [xyz[0] for t, xyz in arr]
        y = [xyz[1] for t, xyz in arr]
        plt.plot(x, y, '-', label=name)
        size = max(size, len(x))
    ax.set_aspect(1.0)
    plt.legend()

    # The function to be called anytime a slider's value changes
    def update(val):
        ax.clear()
        for name, arr in robots.items():
            x = [xyz[0] for t, xyz in arr]
            y = [xyz[1] for t, xyz in arr]
            index = min(int(val), len(x) - 1)
            ax.plot(x[:index + 1], y[:index + 1], '-', label=name)
            ax.scatter([x[index]], [y[index]], s=50)
            ax.annotate(name[0], (x[index], y[index]))
        fig.canvas.draw_idle()

    if create_video_path is not None:
        assert create_video_path.endswith(".mp4"), create_video_path

        writer = None
        fps = 10
        for i in range(size):
            update(i)
            image_stream = io.BytesIO()
            plt.savefig(image_stream, format='png')
            image_stream.seek(0)
            file_bytes = np.asarray(bytearray(image_stream.read()),
                                    dtype=np.uint8)
            img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
            if writer is None:
                height, width = img.shape[:2]
                writer = cv2.VideoWriter(create_video_path,
                                         cv2.VideoWriter_fourcc(*"mp4v"), fps,
                                         (width, height))
            writer.write(img)
        if writer is not None:
            writer.release()
        return  # i.e. no interactive session

    axcolor = 'lightgoldenrodyellow'
    # Make a horizontal slider to control the frequency.
    axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
    slider = plt.Slider(
        ax=axfreq,
        label='time [s]',
        valmin=0.0,
        valmax=size,
        valinit=0.0,
    )

    slider.on_changed(update)

    plt.show()
Ejemplo n.º 3
0
    def _set_up_sliders(self):
        """
        Creates an slider for every parameter.
        """
        i = 0.05
        self._sliders = {}
        for param in self.model.params:
            if not param.fixed:
                axbg = 'lightgoldenrodyellow'
            else:
                axbg = 'red'
            # start-x, start-y, width, height
            ax = self.fig.add_axes((0.162, i, 0.68, 0.03),
                                   facecolor=axbg,
                                   label=param)
            val = param.value
            if not hasattr(param, 'min') or param.min is None:
                minimum = 0
            else:
                minimum = param.min
            if not hasattr(param, 'max') or param.max is None:
                maximum = 2 * val
            else:
                maximum = param.max

            slid = plt.Slider(ax,
                              param,
                              minimum,
                              maximum,
                              valinit=val,
                              valfmt='% 5.4g')
            self._sliders[param] = slid
            slid.on_changed(self._update_plot)
            i += 0.05
def sliderplot(YY, X=None, slidervals=None, *args, **kwargs):
    """
    Shortcut to creating a simple 2D plot with a slider to go through a third dimension
    YY = [nxm]: y axis data (initially plots Y[0,:])
     X = [n] or [nxm]:  x axis data (can be 1D or 2D, either same length or shape as Y)
     slidervals = None or [m]: Values to give in the slider

    E.G.
      sliderplot([1,2,3],[[2,4,6],[8,10,12],[14,16,18],[20,22,24]],slidervals=[3,6,9,12])
    """

    if 'linewidth' and 'lw' not in kwargs.keys():
        kwargs['linewidth'] = 2

    fig = plt.figure(figsize=FIGURE_SIZE, dpi=FIGURE_DPI)

    X = np.asarray(X, dtype=np.float)
    Y = np.asarray(YY, dtype=np.float)
    if slidervals is None:
        slidervals = range(Y.shape[0])
    slidervals = np.asarray(slidervals, dtype=np.float)

    if X.ndim < 2:
        X = np.tile(X, Y.shape[0]).reshape(Y.shape)

    plotline, = plt.plot(X[0, :], Y[0, :], *args, **kwargs)
    plt.axis([X.min(), X.max(), Y.min(), Y.max()])
    plt.subplots_adjust(bottom=0.2)
    ax = plt.gca()

    " Create slider on plot"
    axsldr = plt.axes([0.15, 0.05, 0.65, 0.03], axisbg='lightgoldenrodyellow')

    sldr = plt.Slider(axsldr, '', 0, len(slidervals) - 1)
    txt = axsldr.set_xlabel('{} [{}]'.format(slidervals[0], 0), fontsize=18)

    plt.sca(ax)

    " Slider update function"

    def update(val):
        "Update function for pilatus image"
        pno = int(np.floor(sldr.val))
        plotline.set_xdata(X[pno, :])
        plotline.set_ydata(Y[pno, :])
        txt.set_text('{} [{}]'.format(slidervals[pno], pno))
        plt.draw()
        plt.gcf().canvas.draw()
        # fig1.canvas.draw()

    sldr.on_changed(update)
Ejemplo n.º 5
0
#

# plot the estimated damage for the least damaging orientation
ax1 = fig.add_subplot(221)
ax1.imshow(damage.min(0), interpolation='bicubic')
ax1.set_title('Vascular damage at best orientation')

# plot the interactive GUI
ax2 = plt.subplot(222)
ax2im = ax2.imshow(meanvasdam, 'gray', interpolation='none')

# plot probe
img = plt.imshow(probe[0], extent=[0, 0, 0, 0], alpha=0.5)

# plot dynamic timecourse
# ax3 = fig.add_subplot(223)
# ax3.plot([1,2,3,4,5])

# plot histogram with slider
ax3 = fig.add_subplot(223)
ax3.hist(damage.flatten())
slide = plt.Slider(ax3, "", 0, 10)

# plot luminance
ax4 = fig.add_subplot(224)
ax4.imshow(lumdam.min(0))

plt.draw()
plt.show()
plt.ioff()
Ejemplo n.º 6
0
def select_epochs(folder, overWrite=False):
    # Find test set with most uniform covering of speed and environment variable.
    # provides then a little manual tool to change the size of the window
    # and its position.

    if not os.path.exists(folder + 'nnBehavior.mat'):
        raise ValueError('this file does not exist :' + folder +
                         'nnBehavior.mat')
    with tables.open_file(folder + 'nnBehavior.mat', "a") as f:
        children = [c.name for c in f.list_nodes("/behavior")]
        if overWrite == False and "trainEpochs" in children and "testEpochs" in children:
            return

        # Get info from the file
        speedMask = f.root.behavior.speedMask[:]
        positions = f.root.behavior.positions
        positions = np.swapaxes(positions[:, :], 1, 0)
        speeds = f.root.behavior.speed
        positionTime = f.root.behavior.position_time
        positionTime = np.swapaxes(positionTime[:, :], 1, 0)
        speeds = np.swapaxes(speeds[:, :], 1, 0)
        if speeds.shape[0] == positionTime.shape[0] - 1:
            speeds = np.append(speeds,
                               speeds[-1]).reshape(positionTime.shape[0],
                                                   speeds.shape[1])
        #We extract session names:
        sessionNames = [
            "".join([chr(c) for c in l[0][:, 0]])
            for l in f.root.behavior.SessionNames[:, 0]
        ]
        if sessionNames[0] != 'Recording':
            IsMultiSessions = True
            sessionNames = [
                "".join([chr(c) for c in l[0][:, 0]])
                for l in f.root.behavior.SessionNames[:, 0]
            ]
            sessionStart = f.root.behavior.SessionStart[:, :][:, 0]
            sessionStop = f.root.behavior.SessionStop[:, :][:, 0]
        else:
            IsMultiSessions = False

        sessionValue = np.zeros(speedMask.shape[0])
        if IsMultiSessions:
            for k in range(len(sessionNames)):
                sessionValue[ep.inEpochs(
                    positionTime[:, 0], [sessionStart[k], sessionStop[k]])] = k

        # Select the representative behavior without sleeps to show
        epochToShow = []
        if IsMultiSessions:
            sleep_list = [
                re.search('sleep', sessionNames[x], re.IGNORECASE)
                for x in range(len(sessionNames))
            ]
            id_sleep = [
                x for x in range(len(sleep_list)) if sleep_list[x] != None
            ]
            if id_sleep:
                all_id = set(range(len(sessionNames)))
                id_toshow = list(
                    all_id.difference(id_sleep))  # all except sleeps
                for id in id_toshow:
                    epochToShow.extend([sessionStart[id], sessionStop[id]])
        else:
            epochToShow.extend([
                positionTime[0, 0], positionTime[-1, 0]
            ])  # if no sleeps, or session names, or hab take everything
        maskToShow = ep.inEpochsMask(positionTime[:, 0], epochToShow)
        behToShow = positions[maskToShow, :]
        timeToShow = positionTime[maskToShow, 0]
        sessionValue_toshow = sessionValue[maskToShow]
        if IsMultiSessions:
            SessionNames_toshow = [sessionNames[i] for i in id_toshow]

        ### Get times of show
        if IsMultiSessions:
            if id_sleep[0] == 0:  # if sleep goes first get the end of it
                ids = np.where(sessionValue == id_sleep[0])[0]
                st = positionTime[ids[-1] + 1]
                for i in id_sleep[1:]:
                    ids = np.where(sessionValue == i)[0]
                    st = np.append(
                        st, (positionTime[ids[0]], positionTime[ids[-1]]))
                if st[-1] != positionTime[-1]:
                    st = np.append(st, positionTime[-1])
                else:
                    st = st[:-1]
            else:  # if it starts with maze
                st = positionTime[0]
                for i in id_sleep:
                    ids = np.where(sessionValue == i)[0]
                    st = np.append(
                        st, (positionTime[ids[0]], positionTime[ids[-1]]))
                if st[-1] != positionTime[-1]:
                    st = np.append(st, positionTime[-1])
                else:
                    st = st[:-1]
            assert (st.shape[0] % 2 == 0)
            showtimes = tuple(zip(st[::2], st[1::2]))

        # Default train and test sets
        sizeTest = timeToShow.shape[0] // 10
        testSetId = timeToShow.shape[0] - timeToShow.shape[0] // 10
        bestTestSet = 0
        useLossPredTrainSet = True
        lossPredSetId = 0
        sizelossPredSet = timeToShow.shape[0] // 10
        SetData = {
            'sizeTest': sizeTest,
            'testsetId': testSetId,
            'bestTestSet': bestTestSet,
            'useLossPredTrainSet': useLossPredTrainSet,
            'lossPredSetId': lossPredSetId,
            'sizelossPredSet': sizelossPredSet
        }

        #### Next we provide a tool to manually change the bestTest set position
        # as well as its size:

        # Cut the cmap to avoid black colors
        min_val, max_val = 0.3, 1.0
        n = 20
        cmap = plt.get_cmap("nipy_spectral")
        colors = cmap(np.linspace(min_val, max_val, n))
        cmSessValue = mplt.colors.LinearSegmentedColormap.from_list(
            "mycmap", colors)
        colorSess = cmSessValue(
            np.arange(len(sessionNames)) / (len(sessionNames)))
        keptSession = np.zeros(len(colorSess)) + 1  # a mask for the session
        if IsMultiSessions:
            keptSession[id_sleep] = 0

        fig = plt.figure()
        gs = plt.GridSpec(positions.shape[1] + 5,
                          max(len(colorSess), 2),
                          figure=fig)
        if IsMultiSessions:
            ax = [
                fig.add_subplot(gs[id, :]) for id in range(positions.shape[1])
            ]  #ax for feature display
            ax[0].get_shared_x_axes().join(ax[0], ax[1])
            # ax = [brokenaxes(xlims=showtimes, subplot_spec=gs[id,:]) for id in range(positions.shape[1])] #ax for feature display
        else:
            ax = [
                fig.add_subplot(gs[id, :]) for id in range(positions.shape[1])
            ]  #ax for feature display
            ax[0].get_shared_x_axes().join(ax[0], ax[1])
        ax += [fig.add_subplot(gs[-5, id]) for id in range(len(sessionNames))]
        ax += [
            fig.add_subplot(gs[-4,
                               max(len(colorSess) -
                                   3, 1):max(len(colorSess), 2)])
        ]
        ax += [
            fig.add_subplot(gs[-4, 0:max(len(colorSess) - 4, 1)]),
            fig.add_subplot(gs[-3, :])
        ]  #loss pred training set slider
        ax += [fig.add_subplot(gs[-2, :]),
               fig.add_subplot(gs[-1, :])]  #test set.

        if IsMultiSessions:
            trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs(
                timeToShow,
                SetData,
                keptSession,
                starts=sessionStart,
                stops=sessionStop)
        else:
            trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs(
                timeToShow, SetData, keptSession)

        ls = []
        for dim in range(positions.shape[1]):
            l1 = ax[dim].scatter(
                timeToShow[ep.inEpochs(timeToShow, trainEpoch)[0]],
                behToShow[ep.inEpochs(timeToShow, trainEpoch)[0], dim],
                c="red",
                s=0.5)
            l2 = ax[dim].scatter(
                timeToShow[ep.inEpochs(timeToShow, testEpochs)[0]],
                behToShow[ep.inEpochs(timeToShow, testEpochs)[0], dim],
                c="black",
                s=0.5)
            if SetData['useLossPredTrainSet']:
                l3 = ax[dim].scatter(
                    timeToShow[ep.inEpochs(timeToShow, lossPredSetEpochs)[0]],
                    behToShow[ep.inEpochs(timeToShow, lossPredSetEpochs)[0],
                              dim],
                    c="orange",
                    s=0.5)
            else:
                l3 = ax[dim].scatter(timeToShow[0],
                                     behToShow[0, dim],
                                     c='orange',
                                     s=0.5)
            ls.append([l1, l2, l3])

            # display the sessions positions at the bottom:
            if IsMultiSessions:
                for idk, k in enumerate(id_toshow):
                    if len(np.where(np.equal(sessionValue_toshow, k))[0]) > 0:
                        ax[id].hlines(np.min(behToShow[
                            np.logical_not(np.isnan(behToShow[:, dim])),
                            dim]) - np.std(behToShow[
                                np.logical_not(np.isnan(behToShow[:, dim])),
                                dim]),
                                      xmin=timeToShow[np.min(
                                          np.where(
                                              np.equal(sessionValue_toshow,
                                                       k)))],
                                      xmax=timeToShow[np.max(
                                          np.where(
                                              np.equal(sessionValue_toshow,
                                                       k)))],
                                      color=colorSess[idk],
                                      linewidth=3.0)

        #TODO add histograms here...
        slider = plt.Slider(ax[-2],
                            'test starting index',
                            0,
                            behToShow.shape[0] - SetData['sizeTest'],
                            valinit=SetData['testsetId'],
                            valstep=1)
        sliderSize = plt.Slider(ax[-1],
                                'test size',
                                0,
                                behToShow.shape[0],
                                valinit=SetData['sizeTest'],
                                valstep=1)
        if SetData['useLossPredTrainSet']:
            buttLossPred = plt.Button(ax[-5], "lossPred", color="orange")
        else:
            buttLossPred = plt.Button(ax[-5], "lossPred", color="white")
        sliderLossPredTrain = plt.Slider(
            ax[-4],
            "loss network training \n set starting index",
            0,
            behToShow.shape[0],
            valinit=0,
            valstep=1)
        sliderLossPredTrainSize = plt.Slider(ax[-3],
                                             "loss network training set size",
                                             0,
                                             behToShow.shape[0],
                                             valinit=SetData['sizeTest'],
                                             valstep=1)

        # Next we add buttons to select the sessions we would like to keep:
        butts = [
            plt.Button(ax[len(ax) - k - 6],
                       sessionNames[k],
                       color=colorSess[k]) for k in range(len(colorSess))
        ]
        if IsMultiSessions:
            for id in id_sleep:
                ax[len(ax) - id - 6].set_axis_off()

        def update(val):
            SetData['testsetId'] = slider.val
            SetData['sizeTest'] = sliderSize.val
            SetData['lossPredSetId'] = sliderLossPredTrain.val
            SetData['sizelossPredSet'] = sliderLossPredTrainSize.val

            if IsMultiSessions:
                trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs(
                    timeToShow,
                    SetData,
                    keptSession,
                    starts=sessionStart,
                    stops=sessionStop)
            else:
                trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs(
                    timeToShow, SetData, keptSession)

            for dim in range(len(ls)):
                l1, l2, l3 = ls[dim]
                if isinstance(l1, list):
                    for iaxis in range(len(l1)):
                        l1[iaxis].set_offsets(
                            np.transpose(
                                np.stack([
                                    timeToShow[ep.inEpochs(
                                        timeToShow, trainEpoch)[0]],
                                    behToShow[
                                        ep.inEpochs(timeToShow, trainEpoch)[0],
                                        dim]
                                ])))
                        l2[iaxis].set_offsets(
                            np.transpose(
                                np.stack([
                                    timeToShow[ep.inEpochs(
                                        timeToShow, testEpochs)[0]],
                                    behToShow[
                                        ep.inEpochs(timeToShow, testEpochs)[0],
                                        dim]
                                ])))
                        if SetData['useLossPredTrainSet']:
                            try:
                                ls[dim][2][iaxis].remove()
                                # l3[iaxis].remove()
                            except:
                                pass
                        else:
                            try:
                                ls[dim][2][iaxis].remove()
                                # l3[iaxis].remove()
                            except:
                                pass
                    if SetData['useLossPredTrainSet']:
                        ls[dim][2] = ax[dim].scatter(
                            timeToShow[ep.inEpochs(timeToShow,
                                                   lossPredSetEpochs)[0]],
                            behToShow[
                                ep.inEpochs(timeToShow, lossPredSetEpochs)[0],
                                dim],
                            c="orange",
                            s=0.5)
                else:
                    l1.set_offsets(
                        np.transpose(
                            np.stack([
                                timeToShow[ep.inEpochs(timeToShow,
                                                       trainEpoch)[0]],
                                behToShow[
                                    ep.inEpochs(timeToShow, trainEpoch)[0],
                                    dim]
                            ])))
                    l2.set_offsets(
                        np.transpose(
                            np.stack([
                                timeToShow[ep.inEpochs(timeToShow,
                                                       testEpochs)[0]],
                                behToShow[
                                    ep.inEpochs(timeToShow, testEpochs)[0],
                                    dim]
                            ])))
                    if SetData['useLossPredTrainSet']:
                        try:
                            ls[dim][2].remove()
                        except:
                            pass
                        ls[dim][2] = ax[dim].scatter(
                            timeToShow[ep.inEpochs(timeToShow,
                                                   lossPredSetEpochs)[0]],
                            behToShow[
                                ep.inEpochs(timeToShow, lossPredSetEpochs)[0],
                                dim],
                            c="orange",
                            s=0.5)
                    else:
                        try:
                            l3.remove()
                        except:
                            pass
            fig.canvas.draw_idle()

        slider.on_changed(update)
        sliderSize.on_changed(update)
        sliderLossPredTrain.on_changed(update)
        sliderLossPredTrainSize.on_changed(update)

        def buttUpdate(id):
            def buttUpdate(val):
                if keptSession[id]:
                    butts[id].color = [0, 0, 0, 0]
                    keptSession[id] = 0
                else:
                    keptSession[id] = 1
                    butts[id].color = colorSess[id]
                update(0)

            return buttUpdate

        [b.on_clicked(buttUpdate(id)) for id, b in enumerate(butts)]

        def buttUpdateLossPred(val):
            if SetData['useLossPredTrainSet']:
                buttLossPred.color = [0, 0, 0, 0]
                SetData['useLossPredTrainSet'] = False
            else:
                SetData['useLossPredTrainSet'] = True
                buttLossPred.color = "orange"
            update(0)
            return SetData['useLossPredTrainSet']

        buttLossPred.on_clicked(buttUpdateLossPred)

        suptitle_str = 'Please choose train and test sets. You can include validation set'
        plt.suptitle(suptitle_str, fontsize=22)
        plt.get_current_fig_manager().window.showMaximized()
        plt.show()

        testSetId = slider.val
        sizeTest = sliderSize.val

        lossPredSetId = sliderLossPredTrain.val
        sizelossPredSet = sliderLossPredTrainSize.val

        if IsMultiSessions:
            trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs(
                timeToShow,
                SetData,
                keptSession,
                starts=sessionStart,
                stops=sessionStop)
        else:
            trainEpoch, testEpochs, lossPredSetEpochs = ep.get_epochs(
                timeToShow, SetData, keptSession)

        if "testEpochs" in children:
            f.remove_node("/behavior", "testEpochs")
        f.create_array("/behavior", "testEpochs", testEpochs)
        if "trainEpochs" in children:
            f.remove_node("/behavior", "trainEpochs")
        f.create_array("/behavior", "trainEpochs", trainEpoch)

        if "keptSession" in children:
            f.remove_node("/behavior", "keptSession")
        f.create_array("/behavior", "keptSession", keptSession)

        if "lossPredSetEpochs" in children:
            f.remove_node("/behavior", "lossPredSetEpochs")
        if SetData['useLossPredTrainSet']:
            f.create_array("/behavior", "lossPredSetEpochs", lossPredSetEpochs)
        else:
            f.create_array("/behavior", "lossPredSetEpochs", [])

        f.flush()  #effectively write down the modification we just made

        fig, ax = plt.subplots()
        trainMask = ep.inEpochsMask(positionTime, trainEpoch)[:, 0]
        testMask = ep.inEpochsMask(positionTime, testEpochs)[:, 0]
        ax.scatter(positionTime[trainMask], positions[trainMask, 0], c="red")
        ax.scatter(positionTime[testMask], positions[testMask, 0], c="black")
        if SetData['useLossPredTrainSet']:
            lossPredMask = ep.inEpochsMask(positionTime, lossPredSetEpochs)[:,
                                                                            0]
            ax.scatter(positionTime[lossPredMask],
                       positions[lossPredMask, 0],
                       c="orange")
        fig.show()
Ejemplo n.º 7
0
def speed_filter(folder, overWrite=False):
    ## A simple tool to set up a threshold on the speed value
    # The speed threshold is then implemented through a speed_mask:
    # a boolean array indicating for each index (i.e measured feature time step)
    # if it is above threshold or not.

    # Parameters
    window_len = 14  #changed following Dima's advice

    with tables.open_file(folder + 'nnBehavior.mat', "a") as f:

        children = [c.name for c in f.list_nodes("/behavior")]
        if "speedMask" in children:
            print("speedMask already created")
            if overWrite:
                f.remove_node("/behavior", "speedMask")
            else:
                return

        # Prepare data
        positions = f.root.behavior.positions
        speed = f.root.behavior.speed
        positionTime = f.root.behavior.position_time
        sessionNames = [
            "".join([chr(c) for c in l[0][:, 0]])
            for l in f.root.behavior.SessionNames[:, 0]
        ]
        if sessionNames[0] != 'Recording':
            IsMultiSessions = True
            sessionStart = f.root.behavior.SessionStart[:, :][:, 0]
            sessionStop = f.root.behavior.SessionStop[:, :][:, 0]
        else:
            IsMultiSessions = False

        positions = np.swapaxes(positions[:, :], 1, 0)
        speed = np.swapaxes(speed[:, :], 1, 0)
        posTime = np.swapaxes(positionTime[:, :], 1, 0)
        if speed.shape[0] == posTime.shape[0] - 1:
            speed = np.append(speed, speed[-1])
        speed = np.reshape(speed, [speed.shape[0], 1])
        # Make sure all variables stay in the time limits
        tmin = 0
        tmax = posTime[-1]
        myposTime = posTime[((posTime >= tmin) * (posTime <= tmax))[:, 0]]
        myspeed = speed[((posTime >= tmin) * (posTime <= tmax))[:, 0]]

        # Select the representative behavior to show
        epochToShow = []
        if IsMultiSessions:
            hab_list = [
                re.search('hab', sessionNames[x], re.IGNORECASE)
                for x in range(len(sessionNames))
            ]
            id_hab = [x for x in range(len(hab_list)) if hab_list[x] != None]
            sleep_list = [
                re.search('sleep', sessionNames[x], re.IGNORECASE)
                for x in range(len(sessionNames))
            ]
            id_sleep = [
                x for x in range(len(sleep_list)) if sleep_list[x] != None
            ]
            if id_hab:
                for id in id_hab:
                    epochToShow.extend([sessionStart[id], sessionStop[id]])
            elif id_sleep:
                id_toshow = list(range(id_sleep[0] + 1,
                                       id_sleep[1]))  # in between two sleeps
                for id in id_toshow:
                    epochToShow.extend([sessionStart[id], sessionStop[id]])
        else:
            epochToShow.extend([
                myposTime[0, 0], myposTime[-1, 0]
            ])  # if no sleeps, or session names, or hab take everything
        maskToShow = ep.inEpochsMask(myposTime[:, 0], epochToShow)
        behToShow = positions[maskToShow, :]
        timeToShow = myposTime[maskToShow, 0]

        # Smooth speed
        s = np.r_[myspeed[window_len - 1:0:-1], myspeed,
                  myspeed[-2:-window_len - 1:-1]]
        w = eval('np.' + "hamming" + '(window_len)')
        myspeed2 = np.convolve(w / w.sum(), s[:, 0],
                               mode='valid')[(window_len // 2 -
                                              1):-(window_len // 2)]

        speedToshowSm = myspeed2[maskToShow]
        speedThreshold = np.mean(
            np.log(speedToshowSm[speedToshowSm >= 0] + 10**(-8)))
        speedFilter = speedToshowSm > np.exp(speedThreshold)

        # Figure
        fig = plt.figure(figsize=(7, 15))
        fig.suptitle("Speed threshold selection",
                     fontsize=18,
                     fontweight='bold')
        # Coordinates over time
        ax0 = fig.add_subplot(6, 2, (1, 2))
        l1, = ax0.plot(timeToShow[speedFilter],
                       behToShow[speedFilter, 0],
                       c="red")
        l2, = ax0.plot(timeToShow[speedFilter],
                       behToShow[speedFilter, 1],
                       c="orange")
        l3 = ax0.scatter(timeToShow[speedFilter],
                         np.zeros(timeToShow[speedFilter].shape[0]) - 4,
                         c="black",
                         s=0.2)
        ax0.set_ylabel("environmental \n variable")
        # Speed over time
        ax1 = fig.add_subplot(6, 2, (3, 4), sharex=ax0)
        l4, = ax1.plot(timeToShow[speedFilter],
                       speedToshowSm[speedFilter],
                       c="purple")  # smoothed
        ax1.set_ylabel("speed")
        ax1.set_xlabel("Time (s)")
        # Speed histogram
        ax2 = fig.add_subplot(6, 2, 7)
        speed_log = np.log(speedToshowSm[np.not_equal(speedToshowSm, 0)] +
                           10**(-8))
        ax2.hist(speed_log, histtype="step", bins=200, color="blue")
        ax2.set_yticks([])
        l5 = ax2.axvline(speedThreshold, color="black")
        ax2.set_xlabel("log speed")
        ax2.set_xlim(np.percentile(speed_log[~np.isnan(speed_log)], 0.3),
                     np.max(speed_log[~np.isnan(speed_log)]))
        ax3 = fig.add_subplot(6, 2, 8)
        speed_plot = speedToshowSm[np.not_equal(speedToshowSm, 0)]
        ax3.hist(speed_plot, histtype="step", bins=200, color="blue")
        ax3.set_yticks([])
        l6 = ax3.axvline(np.exp(speedThreshold), color="black")
        ax3.set_xlabel("raw speed")
        ax3.set_xlim(0, np.percentile(speed_plot[~np.isnan(speed_plot)], 98))
        ax4 = fig.add_subplot(6, 2, (11, 12))
        slider = plt.Slider(
            ax4,
            ' ',
            np.min(np.log(speedToshowSm[speedToshowSm >= 0] + 10**(-8))),
            np.max(np.log(speedToshowSm[speedToshowSm >= 0] + 10**(-8))),
            valinit=speedThreshold,
            valstep=0.01)
        ax4.set_ylabel("speed Threshold")
        ax = [ax0, ax1, ax2, ax3, ax4]

        def update(val):
            speedThreshold = val
            speedFilter = speedToshowSm > np.exp(speedThreshold)
            l1.set_ydata(behToShow[speedFilter, 0])
            l2.set_ydata(behToShow[speedFilter, 1])
            l1.set_xdata(timeToShow[speedFilter])
            l2.set_xdata(timeToShow[speedFilter])
            l3.set_offsets(
                np.transpose(
                    np.stack([
                        timeToShow[speedFilter],
                        np.zeros(timeToShow[speedFilter].shape[0]) - 4
                    ])))
            l4.set_ydata(speedToshowSm[speedFilter])
            l4.set_xdata(timeToShow[speedFilter])
            l5.set_xdata(val)
            l6.set_xdata(np.exp(val))
            fig.canvas.draw_idle()

        slider.on_changed(update)
        plt.show()
        # Final value
        speedFilter = myspeed2 > np.exp(
            slider.val)  # Apply the value to the whole dataset

        f.create_array("/behavior", "speedMask", speedFilter)
        f.flush()
        f.close()
        # Change the way you save
        df = pd.DataFrame([np.exp(slider.val)])
        df.to_csv(folder +
                  "speedFilterValue.csv")  #save the speed filter value
Ejemplo n.º 8
0
    def __init__(self, doneCallback, skipCallback, dumpCallback, exitCallback, prevCallback, background, MAX_PROMINENCE=6.0, FALSE_MAXIMUM_ROW_DISTANCE = 30):

        self.MAX_PROMINENCE = MAX_PROMINENCE
        self.FALSE_MAXIMUM_ROW_DISTANCE = FALSE_MAXIMUM_ROW_DISTANCE

        self.doneCallback = doneCallback
        self.skipCallback = skipCallback
        self.dumpCallback = dumpCallback
        self.exitCallback = exitCallback
        self.prevCallback = prevCallback

        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)

        self.background = background

        self.ax.set_xlabel("Time")
        self.ax.set_ylabel("Voltage")

        self.titleColor = 'black'

        self.ax.name = 'main'

        self.fig.subplots_adjust(bottom=0.27, top=0.92, left=0.08, right=0.94)

        # Define an axes area and draw a slider in it
        min_prom_slider_ax = self.fig.add_axes([0.25, 0.17, 0.65, 0.03])
        self.min_prom_slider = plt.Slider(min_prom_slider_ax, 'Min. Prom.', 0.0, MAX_PROMINENCE, valinit=MAX_PROMINENCE)

        # Draw another slider
        max_prom_slider_ax = self.fig.add_axes([0.25, 0.12, 0.65, 0.03])
        self.max_prom_slider = plt.Slider(max_prom_slider_ax, 'Max. Prom.', 0.0, MAX_PROMINENCE, valinit=MAX_PROMINENCE)

        self.min_prom_slider.on_changed(self.updateProminence)
        self.max_prom_slider.on_changed(self.updateProminence)

        self.doneButtonTitle = 'Done'

        doneButtonAxes = plt.axes([0.80, 0.05, 0.1, 0.045])
        self.doneButton = plt.Button(doneButtonAxes, self.doneButtonTitle)
        self.doneButton.on_clicked(self.done)

        resetBtn = plt.axes([0.69, 0.05, 0.1, 0.045])
        self.resetButton = plt.Button(resetBtn, 'Auto')
        self.resetButton.on_clicked(self.reset)

        skipButtonAxes = plt.axes([0.58, 0.05, 0.1, 0.045])
        self.skipButton = plt.Button(skipButtonAxes, 'Skip')
        self.skipButton.on_clicked(self.skip)

        dumpButtonAxes = plt.axes([0.47, 0.05, 0.1, 0.045])
        self.dumpButton = plt.Button(dumpButtonAxes, 'Dump')
        self.dumpButton.on_clicked(self.dump)

        clearButtonAxes = plt.axes([0.36, 0.05, 0.1, 0.045])
        self.clearButton = plt.Button(clearButtonAxes, 'Clear')
        self.clearButton.on_clicked(self.clear)

        prevButtonAxes = plt.axes([0.25, 0.05, 0.1, 0.045])
        self.prevButton = plt.Button(prevButtonAxes, 'Prev')
        self.prevButton.on_clicked(self.prev)

        exitButtonAxes = plt.axes([0.14, 0.05, 0.1, 0.045])
        self.exitButton = plt.Button(exitButtonAxes, 'Exit')
        self.exitButton.on_clicked(self.exit)

        self.fig.canvas.mpl_connect('button_press_event', self.onclick)
Ejemplo n.º 9
0
ax.set_zlim3d(0, 1.5 * max_q)
ax.set_xlabel('x', fontsize=22)
ax.set_ylabel('z', fontsize=22)
ax.set_zlabel('y', fontsize=22)

# Detector
axdet = plt.axes([0.6, 0.1, 0.4, 0.8])
plt.sca(axdet)
pl_im = plt.imshow(detector_image)
pl_im.set_clim(0, 1)

axsldr1 = plt.axes([0.1, 0.4, 0.35, 0.06], facecolor='lightgoldenrodyellow')
axsldr2 = plt.axes([0.1, 0.3, 0.35, 0.06], facecolor='lightgoldenrodyellow')
axsldr3 = plt.axes([0.1, 0.2, 0.35, 0.06], facecolor='lightgoldenrodyellow')
axsldr4 = plt.axes([0.1, 0.1, 0.35, 0.06], facecolor='lightgoldenrodyellow')
sldr1 = plt.Slider(axsldr1, 'phi', -180, 180, valinit=0, valfmt='%5.2f')
sldr2 = plt.Slider(axsldr2, 'chi', -98, 98, valinit=90, valfmt='%5.2f')
sldr3 = plt.Slider(axsldr3, 'eta', -40, 220, valinit=0, valfmt='%5.2f')
sldr4 = plt.Slider(axsldr4,
                   'delta',
                   0,
                   160,
                   valinit=detector_del,
                   valfmt='%5.2f')


def update_all(val):
    "Update function for pilatus image"

    phi, chi, eta, delta = sldr1.val, sldr2.val, sldr3.val, sldr4.val
def sliderplot2D(ZZZ, XX=None, YY=None, slidervals=None, *args, **kwargs):
    """
    Shortcut to creating an image plot with a slider to go through a third dimension
    ZZZ = [nxmxo]: z axis data
     XX = [nxm] or [n]:  x axis data
     YY = [nxm] or [m]: y axis data
     slidervals = None or [o]: Values to give in the slider

    if XX and/or YY have a single dimension, the 2D values are generated via meshgrid

    E.G.
      sliderplot([1,2,3],[[2,4,6],[8,10,12],[14,16,18],[20,22,24]],slidervals=[3,6,9,12])
    """

    if 'linewidth' and 'lw' not in kwargs.keys():
        kwargs['linewidth'] = 2

    fig = plt.figure(figsize=FIGURE_SIZE, dpi=FIGURE_DPI)

    ZZZ = np.asarray(ZZZ, dtype=np.float)

    if slidervals is None:
        slidervals = range(ZZZ.shape[2])
    slidervals = np.asarray(slidervals, dtype=np.float)

    if XX is None:
        XX = range(ZZZ.shape[1])
    if YY is None:
        YY = range(ZZZ.shape[0])
    XX = np.asarray(XX, dtype=np.float)
    YY = np.asarray(YY, dtype=np.float)
    if XX.ndim < 2:
        XX, YY = np.meshgrid(XX, YY)

    p = plt.pcolormesh(XX, YY, ZZZ[:, :, 0])
    # p.set_clim(cax)

    plt.subplots_adjust(bottom=0.2)
    ax = plt.gca()
    ax.set_aspect('equal')
    ax.autoscale(tight=True)

    " Create slider on plot"
    axsldr = plt.axes([0.15, 0.05, 0.65, 0.03], axisbg='lightgoldenrodyellow')

    sldr = plt.Slider(axsldr, '', 0, len(slidervals) - 1)
    txt = axsldr.set_xlabel('{} [{}]'.format(slidervals[0], 0), fontsize=18)

    plt.sca(ax)

    " Slider update function"

    def update(val):
        "Update function for pilatus image"
        pno = int(np.round(sldr.val))
        p.set_array(ZZZ[:-1, :-1, pno].ravel())
        txt.set_text('{} [{}]'.format(slidervals[pno], pno))
        plt.draw()
        plt.gcf().canvas.draw()
        # fig1.canvas.draw()

    sldr.on_changed(update)
Ejemplo n.º 11
0
fig.canvas.mpl_connect('button_press_event', onClick)

anim = animation.FuncAnimation(fig,
                               animate,
                               init_func=init,
                               frames=360,
                               interval=20,
                               blit=True,
                               repeat=True)

###############################################################################

############################## Put sliders

axslider_inc = plt.axes([0.1, 0.92, 0.25, 0.03])
s_inc = plt.Slider(axslider_inc, 'Inc ', 0, 90, valfmt='%0d', valinit=90)
s_inc.on_changed(update)

axslider_node = plt.axes([0.65, 0.92, 0.25, 0.03])
s_node = plt.Slider(axslider_node,
                    'Node Angle',
                    -90,
                    90,
                    valfmt='%0d',
                    valinit=0)
s_node.on_changed(update)

axslider_a = plt.axes([0.1, 0.06, 0.5, 0.03])
s_a = plt.Slider(axslider_a, 'a ', 0.1, 10.0, valfmt='%0.1f', valinit=1.0)
s_a.on_changed(update)
Ejemplo n.º 12
0
# --- Sliders Start ---
'''
Some Interface stuff.
Also here it would be great to have some
automatic function which does this...
instead of writing each line,
something which detects what parameters are to be used and then
auto finds space and creates a slider for it.
'''
fig3 = plt.figure(3)
fig3.clear()
axcolor = 'lightgoldenrodyellow'
axATT = plt.axes([0.25, 0.90, 0.50, 0.02], axisbg=axcolor)
sATT = plt.Slider(axATT,
                  'Attenuation dBm',
                  -90,
                  -20.0,
                  valinit=-51.44,
                  valfmt='%1.5f')
axPHI = plt.axes([0.25, 0.87, 0.50, 0.02], axisbg=axcolor)
sPHI = plt.Slider(axPHI, 'Phase offset', -np.pi, np.pi, valinit=0)
axXSC = plt.axes([0.25, 0.84, 0.50, 0.02], axisbg=axcolor)
sXSC = plt.Slider(axXSC, 'x-scale', 0.9, 1.1, valinit=1.04187, valfmt='%1.5f')
axXPOS = plt.axes([0.25, 0.81, 0.50, 0.02], axisbg=axcolor)
sXPOS = plt.Slider(axXPOS,
                   'x-pos',
                   -0.5,
                   0.5,
                   valinit=-0.49125,
                   valfmt='%1.5f')
axWb = plt.axes([0.25, 0.49, 0.50, 0.02], axisbg=axcolor)
sWb = plt.Slider(axWb, 'WireBond Ind. pH', 0, 2000, valinit=1200.0)
Ejemplo n.º 13
0
plt.ylabel('$м^3$')

fig2 = plt.figure(2)
ax2 = fig2.add_subplot(1, 1, 1)
p2, = ax2.plot(weeks, y)
plt.title('Витрати води')
plt.xlabel('номер неділі від 2019 року')
plt.ylabel('$м^3/c$')

plt.subplots_adjust(bottom=0.25)

axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
height_slider = plt.Slider(
    ax=axfreq,
    label='Висота греблі (м)',
    valmin=1,
    valmax=100,
    valstep=1,
    valinit=H,
)

fig3 = plt.figure(3)
ax3 = fig3.add_subplot(1, 1, 1)
p3, = ax3.plot(weeks, e(H))
plt.title('Кількість виробленої энергії від 2019 року')
plt.xlabel('номер неділі від 2019 року')
plt.ylabel('(кВт/час)')

fig4 = plt.figure(4)
ax4 = fig4.add_subplot(1, 1, 1)
p4, = ax4.plot(weeks, de(H))
plt.title('Кількість виробленої энергії у неділю')
Ejemplo n.º 14
0
    def image_slider(self,
                     index=None,
                     axis=0,
                     clim=None,
                     cmap=None,
                     colorbar=False,
                     **kwargs):
        """
        Plot image in matplotlib figure with a slider (if available)
        :param index: int, image index, 0-length of scan, if None, use centre index
        :param axis: int, axis to index (0-2)
        :param clim: [min, max] colormap cut-offs (None for auto)
        :param cmap: str colormap name (None for auto)
        :param colorbar: False/ True add colorbar to plot
        :param kwargs: additinoal arguments for plot_detector_image
        :return: axes object
        """
        if index is None:
            index = self.vol.shape[axis] // 2

        # Create figure
        show = False
        if 'axes' not in kwargs:
            show = True
            axes = create_axes(subplot=111)
            kwargs['axes'] = axes
        axes = self.image(index, axis, clim, cmap, colorbar, **kwargs)

        # pcolormesh object
        pcolor = axes.collections[0]

        # Move axes for slider
        bbox = axes.get_position()
        left, bottom, width, height = bbox.x0, bbox.y0, bbox.width, bbox.height
        change_in_height = height * 0.1
        new_position = [
            left, bottom + 2 * change_in_height, width,
            height - 2 * change_in_height
        ]
        new_axes_position = [left, bottom, width, change_in_height]

        axes.set_position(new_position, 'original')
        new_axes = axes.figure.add_axes(new_axes_position)

        sldr = plt.Slider(new_axes,
                          'Volume',
                          0,
                          self.vol.shape[axis],
                          valinit=index,
                          valfmt='%0.0f')

        def update(val):
            """Update function for pilatus image"""
            imgno = int(round(sldr.val))
            if axis == 1:
                im = self.vol[:, imgno, :]
            elif axis == 2:
                im = self.vol[:, :, imgno]
            else:
                im = self.vol[imgno]
            pcolor.set_array(im.flatten())
            plt.draw()
            # fig.canvas.draw()

        sldr.on_changed(update)

        if show:
            plt.show()
        return axes
Ejemplo n.º 15
0
def imshow(data, title=None, isrgb=True, vmin=0, vmax=None,
           cmap=None, miniswhite=False, interpolation='bilinear',
           dpi=96, figure=None, subplot=111, show_hist = False, 
           auto_scale = False, **kwargs):
    """Plot n-dimensional images using matplotlib.pyplot.

    Return figure, subplot and plot axis.
    Requires pyplot already imported ``from matplotlib import pyplot``.

    Arguments
    ---------

    isrgb : bool
        If True, data will be displayed as RGB(A) images if possible.

    miniswhite : bool
        If True, gray scale palette will be inverted.

    title : str
        Window and subplot title

    figure : a matplotlib.figure.Figure instance (optional)

    subplot : int
        A matplotlib.pyplot.subplot axis

    Other arguments are same as for matplotlib.pyplot.imshow.

    """
    data = data.squeeze()
    dims = len(data.shape)
    if dims < 2 or dims>3:
        raise ValueError("not an image")
    if dims == 2:
        data = numpy.array([data], data.dtype)
        dims = len(data.shape)

    if (isrgb and data.shape[-3] in (3, 4)):
        data = numpy.swapaxes(data, -3, -2)
        data = numpy.swapaxes(data, -2, -1)
    elif (not isrgb and data.shape[-1] in (3, 4)):
        data = numpy.swapaxes(data, -3, -1)
        data = numpy.swapaxes(data, -2, -1)
    isrgb = isrgb and data.shape[-1] in (3, 4)
    dims -= 3 if isrgb else 2

    datamax = data.max()
    datamin = data.min()
    if datamin < 0:
        vmin = datamin
    if data.dtype in (numpy.int8, numpy.int16, numpy.int32,
                      numpy.uint8, numpy.uint16, numpy.uint32):
        for bits in (8, 10, 12, 14, 16, 20, 24, 32):
            if datamax < 2**bits:
                datamax = 2**bits
                break
        if isrgb and data.dtype != numpy.uint8:
            data *= (255.0 / datamax) # better use digitize()
            data = data.astype('B')
    elif isrgb:
        data /= datamax

    if not isrgb and vmax is None:
        vmax = data.max()

    datamax = data.max()

    import matplotlib.pyplot as pyplot

    if figure is None:
        pyplot.rc('font', family='sans-serif', weight='normal', size=8)
        figure = pyplot.figure(dpi=dpi, figsize=(10.3, 6.3), frameon=True,
                               facecolor='1.0', edgecolor='w')
        try:
            figure.canvas.manager.window.title(title)
        except Exception:
            pass
        pyplot.subplots_adjust(bottom=0.03*(dims+2), top=0.925,
                               left=0.1, right=0.95, hspace=0.05, wspace=0.0)
    subplot = pyplot.subplot(subplot)

    if title:
        pyplot.title(title, size=11)

    if cmap is None:
        cmap = pyplot.cm.binary if miniswhite else pyplot.cm.gray

    current = list((0, ) * dims)
    current[0] = data.shape[0]//2
    image = pyplot.imshow(data[tuple(current)].squeeze(),
                          vmin=vmin, vmax=vmax, cmap=cmap,
                          interpolation=interpolation, **kwargs)
    p = image.axes.get_position ()

    cbar = None
    if not isrgb:
        cbar = pyplot.colorbar()
        tick_values = []
        from ..utils import tostr

    if dims:
        current_axis = [0]
        sliders = [pyplot.Slider(
            pyplot.axes([0.125, 0.03*(axis+1), 0.725, 0.025]),
            'Dimension %i' % axis, 0, data.shape[axis]-1, 0, #facecolor='0.5',
            valfmt='%%.0f of %i' % data.shape[axis]) for axis in range(dims)]
        for slider in sliders:
            slider.drawon = False

        if show_hist:
            hist = pyplot.axes([0.03,p.y0, 2*(p.x0-0.03), p.height])
            hist_args = dict(bins = show_hist, orientation='horizontal')
            h = hist.hist(data[tuple(current)].ravel(), **hist_args)
            hist.set_xlim(0,h[0][1:].max())

        def set_image(current, sliders=sliders, data=data, cbar=cbar, tick_values=tick_values):
            """Change image and redraw canvas."""
            d = data[tuple(current)].squeeze()
            mx = d.max()
            if auto_scale and mx:
                scale = datamax/mx
                if cbar is not None:
                    if not tick_values:
                        ticks = cbar.ax.get_yticklabels()
                        tick_values[:] = [float(t.get_text()) for t in ticks]
                    cbar.ax.set_yticklabels(map(tostr, [t/scale for t in tick_values]))
                d *= scale

            image.set_data(d)
            if show_hist:
                p = image.axes.get_position()
                hist.cla()
                h = hist.hist(data[tuple(current)].ravel(), **hist_args)
                hist.set_xlim(0,h[0][1:].max())
            for ctrl, index in zip(sliders, current):
                ctrl.eventson = False
                ctrl.set_val(index)
                ctrl.eventson = True
            figure.canvas.draw()

        def on_changed(index, axis, data=data, image=image, figure=figure,
                       current=current):
            """Callback for slider change event."""
            print current, axis
            index = int(round(index))
            current_axis[0] = axis
            if index == current[axis]:
                return
            if index >= data.shape[axis]:
                index = 0
            elif index < 0:
                index = data.shape[axis] - 1
            current[axis] = index
            set_image(current)

        def on_keypressed(event, data=data, current=current):
            """Callback for key press event."""
            key = event.key
            axis = current_axis[0]
            print current, axis
            if str(key) in '0123456789':
                on_changed(int(key), axis)
            elif key == 'right':
                on_changed(current[axis] + 1, axis)
            elif key == 'left':
                try:
                    on_changed(current[axis] - 1, axis)
                except IndexError, msg:
                    print axis, len (current), `str(msg)`
            elif key == 'up':
                current_axis[0] = 0 if axis == len(data.shape)-1 else axis + 1
            elif key == 'down':
                current_axis[0] = len(data.shape)-1 if axis == 0 else axis - 1
            elif key == 'end':
                on_changed(data.shape[axis] - 1, axis)
            elif key == 'home':
                on_changed(0, axis)
            elif key == 'm':
                on_changed(data.shape[axis]//2, axis)
            elif key == 'q':
                sys.exit(0)
Ejemplo n.º 16
0
    def __init__(self, index, dm):
        self.current_index = index
        self.dm = dm
        self.raw_data = dm.raw_data
        self.p_max_locs = dm.p_max_locs
        self.saecg_p = dm.saecg_wrapper['saecg_p']
        self.fs = dm.fs
        self.mode = 1  # view mode for beat viewer

        self.fig, self.ax = plt.subplots(
            nrows=5,
            ncols=1,
            gridspec_kw={'height_ratios': [1, 1, 0.1, 0.1, 1]})
        self.fig.tight_layout()  # Configure the layout of UI elements

        self.axprev = plt.axes([0.7, 0.01, 0.08, 0.03])
        self.axnext = plt.axes([0.81, 0.01, 0.08, 0.03])
        self.axanalyze = plt.axes([0.05, 0.01, 0.08, 0.03])
        self.axmode = plt.axes([0.15, 0.01, 0.08, 0.03])
        self.axpremature = plt.axes([0.25, 0.01, 0.1, 0.03])

        self.bnext = Button(self.axnext, 'Next')
        self.bnext.on_clicked(lambda x: self.next_button_pushed(x))

        self.bprev = Button(self.axprev, 'Previous')
        self.bprev.on_clicked(lambda x: self.prev_button_pushed(x))

        self.banalyze = Button(self.axanalyze, 'Analyze')
        self.banalyze.on_clicked(lambda x: self.analyze_button_pushed(x))

        self.bmode = Button(self.axmode, 'Mode')
        self.bmode.on_clicked(lambda x: self.mode_button_pushed(x))

        self.bpremature = Button(self.axpremature, 'Premature Beat Analysis')
        self.bpremature.on_clicked(lambda x: self.premature_button_pushed(x))

        plt.axes(self.ax[0])
        self.ax[0].set_title('Raw Data')
        plt.plot(np.true_divide(range(len(self.raw_data)), self.fs),
                 self.raw_data)
        plt.scatter(np.true_divide(self.dm.heartpy_params['wd']['peaklist'],
                                   self.fs),
                    self.raw_data[self.dm.heartpy_params['wd']['peaklist']],
                    c='g')

        plt.axes(self.ax[1])
        title_string = 'Signal Averaged P Wave'
        self.ax[1].set_title(title_string)
        plt.plot(np.true_divide(range(len(self.saecg_p)), self.fs),
                 self.saecg_p)

        # Make the slider for left edge
        plt.axes(self.ax[2])
        self.slider_start = plt.Slider(self.ax[2],
                                       'Start',
                                       0,
                                       len(self.saecg_p) / self.fs,
                                       valinit=0.1 * len(self.saecg_p) /
                                       self.fs,
                                       color='blue')
        self.slider_start.on_changed(lambda x: self.slider_updated(x))
        # Make the slider for right edge
        plt.axes(self.ax[3])
        self.slider_end = plt.Slider(self.ax[3],
                                     'End',
                                     0,
                                     len(self.saecg_p) / self.fs,
                                     valinit=0.9 * len(self.saecg_p) / self.fs,
                                     color='blue')
        self.slider_end.on_changed(lambda x: self.slider_updated(x))

        plt.axes(self.ax[1])
        self.ax[1].vlines(
            self.slider_start.val,
            self.saecg_p[int(self.slider_start.val * self.fs)] - 0.02,
            self.saecg_p[int(self.slider_start.val * self.fs)] + 0.02,
            color='red')
        self.ax[1].vlines(
            self.slider_end.val,
            self.saecg_p[int(self.slider_end.val * self.fs)] - 0.02,
            self.saecg_p[int(self.slider_end.val * self.fs)] + 0.02,
            color='red')

        plt.axes(self.ax[4])
        self.ax[4].clear()
        title_string = 'Beat %d out of %d beats' % (
            self.get_current_index() + 1, len(dm.beat_wrapper['beats']))
        self.ax[4].set_title(title_string)

        plt.plot(
            np.true_divide(
                range(len(self.dm.beat_wrapper['beats'][self.current_index])),
                self.fs), self.dm.beat_wrapper['beats'][self.current_index])

        plt.plot(self.p_max_locs[self.get_current_index()] / self.fs,
                 self.dm.beat_wrapper['beats'][self.get_current_index()][round(
                     self.p_max_locs[self.get_current_index()])],
                 marker='x')

        plt.plot(
            self.dm.xcorr_params['max_loc'][self.get_current_index()] /
            self.fs, self.dm.beat_wrapper['beats'][self.current_index]
            [self.dm.xcorr_params['max_loc'][self.get_current_index()]], 'o')

        mng = plt.get_current_fig_manager()
        mng.window.state("zoomed")
        plt.show()
Ejemplo n.º 17
0
def dynamic_plot(investor_history, ibov_var, print_ops, max_num_ops=7):
    """ Dynamically plots, over time, the performance of IBOVESPA and on investor.

    :param investor_history: performance history of the investor.
    :param ibov_var: price history of IBOVESPA.
    :param print_ops: if True, the investor's decisions (buy and sell operations) will be plot.
    :param max_num_ops: max number of operations to display on the screen at a time.
    """
    # init
    plt.ion()
    figure, ax = plt.subplots()
    lines_ibov, = ax.plot([], [], "g", linewidth=3, alpha=0.6)
    lines_inv, = ax.plot([], [], "r", linewidth=3, alpha=0.6)

    BASE_PAUSE_TIME = 1
    pause_time = BASE_PAUSE_TIME

    ax.set_autoscaley_on(True)
    ax.set_xlim(0, len(ibov_var))
    ax.grid()

    plt.legend(['IBOV', "Investor"], loc='upper left')
    plt.xlabel("Time (days)")
    plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%.1f%%'))
    figure.subplots_adjust(left=0.25, bottom=0.25)

    # speed slider
    spd_slider_ax = figure.add_axes([0.42, 0.07, 0.3, 0.05],
                                    facecolor='lightgoldenrodyellow')
    spd_slider = plt.Slider(spd_slider_ax,
                            'Speed',
                            0.2,
                            20,
                            valinit=BASE_PAUSE_TIME)

    def spd_slider_on_changed(val):
        nonlocal pause_time
        pause_time = BASE_PAUSE_TIME / val

    spd_slider.on_changed(spd_slider_on_changed)

    # plot
    xdata = []
    ydata_inv = []
    ydata_ibov = []

    pc_ann_inv = pc_ann_ibov = None
    op_points = []
    op_annotations = []

    for x in range(len(ibov_var)):
        # set data
        xdata.append(x)
        ydata_inv.append(investor_history[0][x])
        ydata_ibov.append(ibov_var[x])

        lines_inv.set_xdata(xdata)
        lines_inv.set_ydata(ydata_inv)

        lines_ibov.set_xdata(xdata)
        lines_ibov.set_ydata(ydata_ibov)

        # rescale
        ax.relim()
        ax.autoscale_view()

        # percentage annotation
        if pc_ann_ibov is not None:
            pc_ann_ibov.remove()
        pc_ann_ibov = ax.annotate('%0.2f%%' % ydata_ibov[-1],
                                  xy=(1, ydata_ibov[-1]),
                                  xytext=(8, 0),
                                  color=lines_ibov.get_color(),
                                  xycoords=('axes fraction', 'data'),
                                  textcoords='offset points',
                                  weight="bold")

        if pc_ann_inv is not None:
            pc_ann_inv.remove()
        pc_ann_inv = ax.annotate('%0.2f%%' % ydata_inv[-1],
                                 xy=(1, ydata_inv[-1]),
                                 xytext=(8, 0),
                                 color=lines_inv.get_color(),
                                 xycoords=('axes fraction', 'data'),
                                 textcoords='offset points',
                                 weight="bold")

        # op annotation
        if print_ops and investor_history[1][x][1] != 0:
            color = "g" if investor_history[1][x][0] == "BUY" else "r"
            p, = ax.plot([xdata[-1]], [ydata_inv[-1]],
                         marker='o',
                         markersize=5,
                         color=color)
            op_points.append(p)
            op_annotations.append(
                ax.annotate("%d" % investor_history[1][x][1],
                            xy=(xdata[-1], ydata_inv[-1]),
                            xytext=(xdata[-1] - 0.25, ydata_inv[-1] - 0.25),
                            color=color,
                            weight="bold",
                            fontsize=8,
                            arrowprops={"arrowstyle": "->"}))

            if len(op_annotations) > max_num_ops:
                op_points.pop(0).remove()
                op_annotations.pop(0).remove()  # remove the oldest annotation

        # draw and delay
        plt.pause(pause_time)

    plt.ioff()
    plt.show()
Ejemplo n.º 18
0
                   v_speed=0,
                   fuel=500,
                   rotation=0,
                   power=0)
dt = 1. / 40

fig, ax = plt.subplots()
ax.set_position([0.1, 0.2, 0.8, 0.7])
ship_position, = ax.plot(ship.x, ship.y, 'bo', ms=6)

# SLIDERS
ax_power = plt.axes([0.2, 0.02, 0.5, 0.02])
ax_rotation = plt.axes([0.2, 0.08, 0.5, 0.02])
slider_power = plt.Slider(ax_power,
                          'Power',
                          valmin=0,
                          valmax=4,
                          valinit=0,
                          valstep=1)
slider_rotation = plt.Slider(ax_rotation,
                             'Rotation',
                             valmin=-90,
                             valmax=90,
                             valinit=0,
                             valstep=1)
slider_power.on_changed(update_power)
slider_rotation.on_changed(update_rotation)

#  TEXTS
time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)
power_text = ax.text(0.02, 0.90, '', transform=ax.transAxes)
rotation_text = ax.text(0.02, 0.85, '', transform=ax.transAxes)
Ejemplo n.º 19
0
mpl.xlim(Idler_Motion_Pts.x_lim)
mpl.ylim(Idler_Motion_Pts.y_lim)
mpl.xlabel('x')
mpl.ylabel('y')

mpl.grid()
mpl.gca().set_aspect('equal', adjustable='box')

## Plot constant tValues along f(t, thetaSpace)

# Color
axcolor = 'lightgoldenrodyellow'
ax_θ_O = mpl.axes([0.25, 0.1, 0.5, 0.05], facecolor=axcolor)

sliθ_O = mpl.Slider(ax_θ_O, 'θ_O (Rotation Around P_0)', Omega_O.linspace[0],
                    Omega_O.linspace[-1])
sliθ_O.set_val(C_motion_all_t.Vars['omega_O'].val)


def update(val):
    C_motion_all_t.Vars['omega_O'].val = val
    C_motion_all_t.coord_gen()

    handle_plot.set_xdata(C_motion_all_t.x[-1])
    handle_plot.set_ydata(C_motion_all_t.y[-1])
    fig.canvas.draw_idle()


sliθ_O.on_changed(update)

mpl.show()
room.plot(ax)

# Detector
axdet = plt.axes([0.6, 0.1, 0.4, 0.8])
room.plot_detector(axdet)
axdet.axis('image')

axsldr1 = plt.axes([0.1, 0.45, 0.35, 0.06], facecolor='lightgoldenrodyellow')
axsldr2 = plt.axes([0.1, 0.37, 0.35, 0.06], facecolor='lightgoldenrodyellow')
axsldr3 = plt.axes([0.1, 0.29, 0.35, 0.06], facecolor='lightgoldenrodyellow')
axsldr4 = plt.axes([0.1, 0.21, 0.35, 0.06], facecolor='lightgoldenrodyellow')
axsldr5 = plt.axes([0.1, 0.13, 0.35, 0.06], facecolor='lightgoldenrodyellow')
axsldr6 = plt.axes([0.1, 0.05, 0.35, 0.06], facecolor='lightgoldenrodyellow')
sldr1 = plt.Slider(axsldr1,
                   'phi',
                   -180,
                   180,
                   valinit=diffractometer.phi,
                   valfmt='%5.2f')
sldr2 = plt.Slider(axsldr2,
                   'chi',
                   -98,
                   98,
                   valinit=diffractometer.chi,
                   valfmt='%5.2f')
sldr3 = plt.Slider(axsldr3,
                   'eta',
                   -20,
                   200,
                   valinit=diffractometer.eta,
                   valfmt='%5.2f')
sldr4 = plt.Slider(axsldr4,
Ejemplo n.º 21
0
inp = autoencoder.get_layer(index=-1-middle).input_shape[1:]
inp = Input(shape=(inp[0], inp[1], 1))
x = autoencoder.get_layer(index=-1-middle)(inp)
for i in range(1, middle+1):
    x = autoencoder.get_layer(index=-1-(middle-i))(x)

decode = Model(inp, x)

def update(val):
    vals = []
    """"for s in slider:
        vals.append(s.val)"""
    for i in range(decode.get_input_shape_at(0)[1]):
        vals.append([])
        for i2 in range(decode.get_input_shape_at(0)[2]):
            vals[-1].append([slider[i*decode.get_input_shape_at(0)[2]+i2].val])
    plt.subplot(211)
    image = decode.predict(np.array([vals]))
    plt.imshow(image.reshape(img_height, img_width))


axcolor = 'lightgoldenrodyellow'
slider = []
"""for i in range(int(img_height/2**LAYER_COUNT)):"""
for i in range(decode.get_input_shape_at(0)[2]*decode.get_input_shape_at(0)[1]):
    ax = plt.axes([0.25, (decode.get_input_shape_at(0)[2]*decode.get_input_shape_at(0)[1]-i)*0.1, 0.65, 0.03], facecolor=axcolor)
    slider.append(plt.Slider(ax, 'input'+str(i), 0, 30))
    slider[-1].on_changed(update)

update(0)
plt.show()
Ejemplo n.º 22
0
    maxval = xdata.max()
else:
    maxval = ydata.max()
ax.set_xlim(minval, maxval)
ax.set_ylim(minval, maxval)

spacing = np.linspace(0.1, 0.05, 2)
thickness = 0.02

ax_a = plt.axes([0.3, spacing[0], 0.5, thickness], facecolor='white')
ax_b = plt.axes([0.3, spacing[1], 0.5, thickness], facecolor='white')

sldr_a = plt.Slider(ax_a,
                    'Rotation Rate',
                    s1 - 0.01,
                    s1 + 0.01,
                    valinit=s1,
                    valfmt='%0.5f',
                    color='gray')
sldr_b = plt.Slider(ax_b,
                    'Speed Factor',
                    s2 - 2,
                    s2 + 2,
                    valinit=s2,
                    valfmt='%0.5f',
                    color='gray')


def update(val):
    s1 = sldr_a.val
    s2 = sldr_b.val
Ejemplo n.º 23
0
import numpy as np
from matplotlib import pyplot, animation
from mpl_toolkits.mplot3d import Axes3D  #Enables 3D functionality
from time import sleep
from mechlib import geometry as g

#Objects
p1 = g.Vector3()
p2 = g.Vector3(1, 1, 1)
graphables = [g.Origin(origin=p1), g.Origin(origin=p2), g.Line(p1, p2)]

#SETUP
fig = pyplot.figure(figsize=plt.figaspect(2.))  #The graphical figure
fig.suptitle('3D Lin-Alg Rotations')
ax = fig.add_subplot(2, 1, 1, projection='3d')  #The graphing subplot

setAxesRange(ax3D, 4)

#Drawing
for o in graphables:
    o.draw(ax)

ax = fig.add_subplot(2, 1, 2)  #The slider subplot
s = pyplot.Slider(axSlider, "Theta", 0, 360, 0)  #The slider

fig.show()

#SHOW
#while True:
#    graphables[0].rotate('z', np.radians(s.val))
#    fig.canvas.draw()
Ejemplo n.º 24
0
def interactive_3d_plot(vid_path,
                        triangulated_csv_path,
                        skeleton_path=None,
                        figure_size=(9, 5),
                        marker_size=5,
                        skeleton_thickness=1):
    """Makes an interactive 3D plot with video and a slider to control the frame number.

    Arguments:
        vid_path {str} -- location of the video to observe.
        triangulated_csv_path {str} -- location of csv with triangulated points corresponding to the
            video given in vid_path.
    """
    global FIG, FIGNUM, AXS, SLIDER

    # Import the triangulated CSV
    with open(triangulated_csv_path, 'r') as f:
        triagreader = csv.reader(f)
        l = next(triagreader)
        bodyparts = []
        for i, bp in enumerate(l):
            if (i - 1) % 3 == 0:
                bodyparts.append(bp)
        num_bodyparts = len(bodyparts)
        next(triagreader)
        triangulated_points = []
        for row in triagreader:
            triangulated_points.append([[] for _ in range(3)])
            for ibp in range(num_bodyparts):
                triangulated_points[-1][0].append(float(row[1 + ibp * 3]))
                triangulated_points[-1][1].append(float(row[2 + ibp * 3]))
                triangulated_points[-1][2].append(float(row[3 + ibp * 3]))
    triangulated_points = np.array(triangulated_points)

    # Get the video
    video = cv2.VideoCapture(vid_path)
    num_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))

    if skeleton_path is not None:
        with open(skeleton_path, 'r') as yaml_file:
            dic = yaml.safe_load(yaml_file)
            bp_list = dic['bodyparts']
            bp_connections = dic['skeleton']
        skeleton = True
    else:
        skeleton = False

    # Check the number of frames vs number of rows in csv
    if num_frames != np.shape(triangulated_points)[0]:
        raise Warning(
            'Number of frames in video and rows in CSV are not equal. Check that the paths'
            + ' given are correct.')

    # Initalize the plots
    cmap = matplotlib.cm.get_cmap('jet')
    color_idx = np.linspace(0, 1, num_bodyparts)
    bp_cmap = cmap(color_idx)
    # Limits in space of the markers + 10%
    margin = 1.3
    pcntl = 2
    x_range = (np.nanpercentile(triangulated_points[:, 0, :], pcntl) * margin,
               np.nanpercentile(triangulated_points[:, 0, :], 100 - pcntl) *
               margin)
    y_range = (np.nanpercentile(triangulated_points[:, 1, :], pcntl) * margin,
               np.nanpercentile(triangulated_points[:, 1, :], 100 - pcntl) *
               margin)
    z_range = (np.nanpercentile(triangulated_points[:, 2, :], pcntl) * margin,
               np.nanpercentile(triangulated_points[:, 2, :], 100 - pcntl) *
               margin)

    FIG = mpl_pp.figure(figsize=figure_size)
    FIGNUM = mpl_pp.gcf().number
    AXS = []
    AXS.append(FIG.add_subplot(1, 2, 1))
    AXS.append(FIG.add_subplot(1, 2, 2, projection='3d'))
    AXS[1].view_init(elev=90, azim=90)

    def update(iframe):
        iframe = int(iframe)
        mpl_pp.figure(FIGNUM)
        video.set(cv2.CAP_PROP_POS_FRAMES, iframe)  # Set the frame to get
        fe, frame = video.read()  # Read the frame
        if fe:
            frame_rgb = frame[..., ::-1].copy()

            AXS[0].cla()
            AXS[0].imshow(frame_rgb)

            AXS[1].cla()
            AXS[1].set_xlim(x_range)
            AXS[1].set_ylim(y_range)
            AXS[1].set_zlim(z_range)

            # Underlying skeleton
            if skeleton:
                for bpc in bp_connections:
                    ibp1 = bp_list.index(bpc[0])
                    ibp2 = bp_list.index(bpc[1])

                    t_point1 = triangulated_points[iframe, :, ibp1]
                    t_point2 = triangulated_points[iframe, :, ibp2]

                    if any(np.isnan(t_point1)) or any(np.isnan(t_point1)):
                        continue
                    AXS[1].plot([t_point1[0], t_point2[0]],
                                [t_point1[1], t_point2[1]],
                                [t_point1[2], t_point2[2]],
                                color='k',
                                linewidth=skeleton_thickness)

            # Bodypart markers
            for ibp in range(np.size(triangulated_points, 2)):
                # Markers
                AXS[1].scatter(triangulated_points[iframe, 0, ibp],
                               triangulated_points[iframe, 1, ibp],
                               triangulated_points[iframe, 2, ibp],
                               color=bp_cmap[ibp, :],
                               s=marker_size)

    def arrow_key_image_control(event):
        if event.key == 'left' and SLIDER.val > 0:
            SLIDER.set_val(SLIDER.val - 1)
        elif event.key == 'right' and SLIDER.val < num_frames - 1:
            SLIDER.set_val(SLIDER.val + 1)
        else:
            pass

    update(0)

    axcolor = 'lightgoldenrodyellow'
    ax_ind = mpl_pp.axes([0.15, 0.1, 0.65, 0.03], facecolor=axcolor)
    SLIDER = mpl_pp.Slider(ax_ind,
                           'Frame',
                           0,
                           num_frames - 1,
                           valinit=0,
                           valstep=1,
                           valfmt='%u')
    SLIDER.on_changed(update)

    cid = FIG.canvas.mpl_connect('key_press_event', arrow_key_image_control)

    mpl_pp.show()