Esempio n. 1
0
    def slider(self):

        from matplotlib.widgets import Slider, Button, RadioButtons

        # Image configuration and first call
        #fig = plt.figure(figsize=(38, 5))
        fig, ax = plt.subplots()
        fig.subplots_adjust(bottom=0.15)

        def data(x0, y0, t0, t1):
            image = td(self.array, x0=int(x0), y0=int(y0), theta0=int(t0), theta1=int(t1), \
             radius=self.radius, savfile=self.sav, path=self.path, rad0=int(self.rad0), images = self.images)
            im = image.tdplot(plot=False, colorbar=False)
            return im

        im = data(self.x0, self.y0, self.theta0, self.theta1)
        image = ax.imshow(im,
                          cmap='Greys_r',
                          interpolation='spline36',
                          origin='lower')

        #plt.axes.Axes.set_xscale(1, 'linear')

        # Remove actual image to not be shown
        plt.show(block=False)
        plt.pause(0.0001)
        plt.close('all')

        # Set up sliders
        axt1 = plt.axes([0.1, 0.06, 0.34, 0.04], facecolor='lightcyan')
        axt0 = plt.axes([0.1, 0.01, 0.34, 0.04], facecolor='pink')
        axy0 = plt.axes([0.55, 0.06, 0.35, 0.04], facecolor='lightcyan')
        axx0 = plt.axes([0.55, 0.01, 0.35, 0.04], facecolor='pink')
        axrd = plt.axes([0.1, 0.85, 0.34, 0.04])

        slider_ra = Slider(axrd, "radio", 0, 20, valinit=self.rad0)
        slider_t1 = Slider(axt1,
                           r'$\theta _1(^\circ)$',
                           0,
                           359,
                           valinit=self.theta1)
        slider_t0 = Slider(axt0,
                           r'$\theta _0(^\circ)$',
                           0,
                           359,
                           valinit=self.theta0)
        slider_x0 = Slider(axy0, r'x', 0, 400, valinit=self.x0)
        slider_y0 = Slider(axx0, r'y', 0, 400, valinit=self.y0)

        plt.axes([0.25, 0.25, 0.6, 0.6])

        # Update the image
        def update(val):
            theta0 = slider_t0.val
            theta1 = slider_t1.val
            x0 = slider_x0.val
            y0 = slider_y0.val
            r0 = slider_ra.val
            image.set_data(data(int(x0), int(y0), int(theta0), int(theta1)))
            fig.canvas.draw()
            #ax.clear()
            plt.draw()

        # Change sliders
        slider_t0.on_changed(update)
        slider_t1.on_changed(update)
        slider_x0.on_changed(update)
        slider_y0.on_changed(update)
        slider_ra.on_changed(update)

        plt.show()
Esempio n. 2
0
    return sumy


s = Four(M, T, t)  # Initial plot
l, = plt.plot(t, s, lw=1, color='red')
plt.axis([0, pi, -4.0, 4.0])  # minx, maxx, miny, maxy

xlabel('Time')
ylabel('Signal')
title('Fourier Synthesis of Sawtooth function')
grid(True)

# Slider
axcolor = 'w'
axnumwaves = plt.axes([0.15, 0.1, 0.75, 0.03], axisbg=axcolor)
snumwaves = Slider(axnumwaves, '# Waves', 1, 20, valinit=T)
# Previous: value of the slider (float) assigned to snumwaves


def hzfunc():
    hzdict = Four(int(numwaves), T, t)
    ydata = hzdict
    l.set_ydata(ydata)
    plt.draw()


hzfunc()


def update(val):  # Update slider
    global numwaves
Esempio n. 3
0
fft_plot = axs[0, 1].imshow(np.zeros((gs['x'], gs['z'])).T, origin='lower')
axs[0, 1].set_title('DFT')

ang_dist_th_plot, = axs[0, 0].plot([], [])
ang_dist_plot, = axs[0, 0].plot([], [], '.')
axs[0, 0].set_title('angular distribution')

quiv = axs[1, 1].quiver(v_X,
                        v_Z,
                        np.ones((gs['x'], gs['z'])),
                        np.ones((gs['x'], gs['z'])),
                        scale=None)

axslice = plt.axes([0.25, 0.1, 0.5, 0.03], facecolor='lightgoldenrodyellow')
sslice = Slider(axslice, 'Slice', 0, 1, valinit=0, dragging=False)

for ax in axs.flatten():
    ax.set_aspect(1)


def update_title(i, timestep):
    axs[1, 0].set_title('Slice: {}/{}, time: {}'.format(
        i,
        len(ds.index) - 1, timestep * sim_settings['simulation']['timestep']))


def psi(x, kappa):
    return np.exp(kappa * np.sin(x)) / np.abs(special.iv(0, kappa)) / 2 / np.pi

Esempio n. 4
0
bm = ax.bar(binsm[:-1], histm, width=barwidth, color='salmon')

ax.set_title('Assumed 1 degree of symmetry ', y=0.9, loc='right', fontdict=sty)
ax.set_xlabel(r'$\pm$ |cos($\theta$)|')
ax.set_ylabel(r'1/N dN/d(cos($\theta$))', labelpad=-1)

# Add two sliders for tweaking the parameters

# Define an axes area and draw sliders:
a0_slider_ax = fig.add_axes([0.1, 0.12, 0.65, 0.01],
                            clip_on=False,
                            facecolor=axis_color)
a0_slider = Slider(a0_slider_ax,
                   'a0',
                   0.,
                   1,
                   edgecolor='white',
                   facecolor=bar_color,
                   valinit=a0)

a1_slider_ax = fig.add_axes([0.1, 0.10, 0.65, 0.01], facecolor=axis_color)
a1_slider = Slider(a1_slider_ax,
                   'a1',
                   -0.3,
                   0.3,
                   edgecolor='white',
                   facecolor=bar_color,
                   valinit=a1)

a2_slider_ax = fig.add_axes([0.1, 0.08, 0.65, 0.01], facecolor=axis_color)
a2_slider = Slider(a2_slider_ax,
Esempio n. 5
0
from matplotlib.widgets import Slider, Button, RadioButtons

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
s = a0 * np.sin(2 * np.pi * f0 * t)
l, = plt.plot(t, s, lw=2, color='red')
plt.axis([0, 1, -10, 10])

axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)

sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)


def update(val):
    amp = samp.val
    freq = sfreq.val
    l.set_ydata(amp * np.sin(2 * np.pi * freq * t))
    fig.canvas.draw_idle()


sfreq.on_changed(update)
samp.on_changed(update)

resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
Esempio n. 6
0
plt.suptitle(basename + ', imageindex = ' + str(imageindex_init))

imgplot.norm = colors.LogNorm(1, normlz.max())
cbar = fig.colorbar(imgplot, ax=ax1)

db = [245, 118]
ax1.plot(db[0] * np.ones(194), np.arange(0, 194), 'k:')
ax1.plot(np.arange(0, 486), db[1] * np.ones(486), 'k:')

#slider_ax = plt.axes([0, 0.05, 0.8, 0.05])
slider_ax = plt.axes([0.1, 0.02, 0.8, 0.05])

img_slider = Slider(
    slider_ax,  # the axes object containing the slider
    'imageindex:',  # the name of the slider parameter
    imageindex_min,  # minimal value of the parameter
    imageindex_max,  # maximal value of the parameter
    valinit=imageindex_init,  # initial value of the parameter
    valstep=1.0)


def update(imageindex):
    #sin_plot.set_ydata(np.sin(a*x)) # set new y-coordinates of the plotted points
    #fig.canvas.draw_idle()          # redraw the plot
    ax = imgplot
    strimageindex = '%(#)04i' % \
    {"#": imageindex}
    filenameraw = folderraw + '/b_mehta_' + basename + '_' + strimageindex + '.raw'
    f1 = open(filenameraw, "r")
    raw = np.fromfile(f1, dtype=np.uint32)
    img = raw.reshape(195, 487)
Esempio n. 7
0
axButton = plt.axes([0.83, 0.15, 0.06, 0.06])  # xloc,yloc,width,heights
btn = Button(axButton, ' ADD ')

axButton1 = plt.axes([0.83, 0.05, 0.08, 0.06])  # xloc,yloc,width,heights
btn1 = Button(axButton1, ' Save Data ', hovercolor='r')

# button on click callback function
btn.on_clicked(setValue)
btn1.on_clicked(setData)

# Sliders declaration
axSlider1 = plt.axes([0.1, 0.21, 0.55, 0.02])  # xloc,yloc,width,height
slider1 = Slider(axSlider1,
                 'Vgb',
                 valmin=-0.01,
                 valmax=2,
                 valinit=Vgb,
                 valfmt='Vgb is ' + '%1.2f' + ' V',
                 color="blue")

axSlider2 = plt.axes([0.1, 0.17, 0.55, 0.02])  # xloc,yloc,width,height
slider2 = Slider(ax=axSlider2,
                 label='Tox',
                 valmin=1,
                 valmax=8,
                 valinit=tox * 10**(9),
                 valfmt='tox is ' + '%1.2f' + ' nm',
                 color="green")

axSlider3 = plt.axes([0.1, 0.13, 0.55, 0.02])  # xloc,yloc,width,height
slider3 = Slider(axSlider3,
Esempio n. 8
0
def plot_result(img_array, ret_img_array):
    std = float(cp.std(ret_img_array))
    gamma = [0.5]
    v_max = [8 * std]
    frac = ret_img_array.shape[0] / 128
    thumbnail_shape = [int(each / frac) for each in ret_img_array.shape]
    thumbnail = np.array(
        Image.fromarray(ret_img_array).resize(thumbnail_shape,
                                              Image.ANTIALIAS))
    # first select proper vmax and gamma
    fig = plt.figure()
    ima = plt.axes((0.1, 0.20, 0.8, 0.7))
    ima.set_title("Please select proper Vmax and Gamma for result")
    ima.imshow(thumbnail,
               cmap="gray",
               norm=colors.PowerNorm(gamma=gamma[0]),
               vmin=0,
               vmax=v_max[0])
    # plot slider
    om1 = plt.axes((0.25, 0.05, 0.65, 0.03))
    om2 = plt.axes((0.25, 0.10, 0.65, 0.03))
    som1 = Slider(om1,
                  r"$max value$",
                  0,
                  16 * std,
                  valinit=v_max[0],
                  dragging=True)  # generate the first slider
    som2 = Slider(om2, r"$Gamma$", 0, 4.0, valinit=gamma[0],
                  dragging=True)  # generate the second slider

    # define update function for slides
    def update(val):
        s1 = som1.val
        s2 = som2.val
        v_max[0] = s1
        gamma[0] = s2
        ima.imshow(thumbnail,
                   cmap="gray",
                   norm=colors.PowerNorm(gamma=gamma[0]),
                   vmin=0,
                   vmax=v_max[0])
        fig.canvas.draw_idle()

    # bind update function to slides
    som1.on_changed(update)
    som2.on_changed(update)
    plt.show()
    del thumbnail

    # then print the final compared images
    fig, (ax1, ax2) = plt.subplots(1, 2)
    # plot original image sequence
    ax1.set_title("Original image sequence")
    ims = []
    for frame in img_array[:200]:
        im = ax1.imshow(frame, cmap="gray", animated=True)
        ims.append([im])
    ani = animation.ArtistAnimation(fig,
                                    ims,
                                    interval=50,
                                    blit=True,
                                    repeat_delay=0)
    # animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=0)
    # plot result
    ax2.imshow(ret_img_array,
               cmap="gray",
               norm=colors.PowerNorm(gamma=gamma[0]),
               vmin=0,
               vmax=v_max[0])
    ax2.set_title("srrf image")

    plt.show()
Esempio n. 9
0
main_wa_mode = plt.axes(main_wp_mode, facecolor='lightgoldenrodyellow')
main_w_mode = RadioButtons(main_wa_mode, ('Inspect', 'DirectAdd', 'DirectRemoval'))
for label in main_w_mode.labels: label.set_fontsize(fs[0])
main_w_mode.on_clicked(main_mode_change)

# Main window: Set flags
main_wp_flags = [main_wp_mode[0]+main_wp_mode[2]+0.05, main_wp_mode[1], main_wp_mode[2], main_wp_mode[3]]
main_wa_flags = plt.axes(main_wp_flags, facecolor='lightgoldenrodyellow')
main_w_flag = CheckButtons(main_wa_flags, ['Completed', 'Interesting', 'Problematic'], [False,False,False])
for label in main_w_flag.labels: label.set_fontsize(fs[0])
main_w_flag.on_clicked(main_flag_change)

# Main window: Signal Cap slider
main_wp_sigcap = [main_wp_flags[0]+main_wp_flags[2]+0.05, main_wp_flags[1]+0.05, 0.13, 0.015]
main_wa_sigcap = plt.axes(main_wp_sigcap)
main_w_sigcap = Slider(main_wa_sigcap, 'Signal intensity cap', 0,3000, valinit=signalcap, dragging=False, valfmt='%.0f')
main_w_sigcap.label.set_position((1.1,1.5))
main_w_sigcap.on_changed(update_sigcap)

# Main window: Delete all
main_wp_delall = [main_wp_flags[0]+main_wp_flags[2]+0.05, main_wp_flags[1], 0.16, 0.035]
main_wa_delall = plt.axes(main_wp_delall, facecolor='lightgoldenrodyellow')
main_w_delall = Button(main_wa_delall, 'Remove all metastases')
main_w_delall.on_clicked(remove_all_metastases)

# Main window: Save&Close
main_wp_snc = [main_wp_delall[0]+main_wp_delall[2]+0.05, main_wp_delall[1], 0.12, 0.08]
main_wa_snc = plt.axes(main_wp_snc, facecolor='lightgoldenrodyellow')
main_w_snc = Button(main_wa_snc, 'Save & Close')
main_w_snc.on_clicked(main_saveandclose)
Esempio n. 10
0
def PlotGraph(xlist, ylist, scord, ecord, mode):
    global Slist
    global Holelist
    global Poslist

    Slist = np.array([])
    Holelist = np.array([])
    Poslist = np.array([])

    Slist = Smoothener(ylist[scord:ecord], 15, 400)
    Holelist, Poslist = HoleFinder(Slist, xlist)

    fig = plt.figure()
    ax = fig.subplots()
    plt.subplots_adjust(bottom=0.25)
    p, = ax.plot(xlist, Slist, linewidth=0.5)
    StepSlide = plt.axes([0.15, 0.15, 0.65, 0.03])
    StepFactor = Slider(StepSlide,
                        "Step size",
                        valmin=2,
                        valmax=50,
                        valinit=15,
                        valstep=1)
    ThresholdSlide = plt.axes([0.15, 0.1, 0.65, 0.03])
    ThresholdFactor = Slider(ThresholdSlide,
                             "Threshold",
                             valmin=10,
                             valmax=3000,
                             valinit=400,
                             valstep=5)

    ax_confirm = plt.axes([0.875, 0.125, 0.1, 0.03])
    ConfirmButton = Button(ax_confirm, "Confirm")
    if mode: ax.set_yscale('log')

    def update(val):
        global Slist
        global Holelist
        global Poslist
        currentStep = StepFactor.val
        currentThreshold = ThresholdFactor.val
        Slist = Smoothener(ylist[scord:ecord], currentStep, currentThreshold)
        Holelist, Poslist = HoleFinder(Slist, xlist)
        p.set_ydata(Slist)
        fig.canvas.draw()

    def closee(val):
        plt.close()

    StepFactor.on_changed(update)
    ThresholdFactor.on_changed(update)
    ConfirmButton.on_clicked(closee)

    def quit_figure(event):
        if event.key == 'q':
            plt.close(event.canvas.figure)

    cid = plt.gcf().canvas.mpl_connect('key_press_event', quit_figure)

    plt.show()

    plt.close()

    return Holelist, Poslist, Slist
Esempio n. 11
0
if __name__ == "__main__":
    stop = False
    val_min = -60
    val_max = 10
    fig = plt.figure(figsize=(5, 5))
    ax = fig.add_subplot(1, 1, 1)
    plt.subplots_adjust(bottom=0.35)
    axnext = plt.axes([0.8, 0.05, 0.1, 0.075])
    bnext = Button(axnext, 'Stop')
    bnext.on_clicked(stop_func)
    left, bottom, width, height = 0.15, 0.05, 0.5, 0.1
    slider_ax_min = plt.axes([left, bottom, width, height])
    slider_min = Slider(slider_ax_min,
                        'Min',
                        valmin=-60,
                        valmax=10,
                        valstep=1,
                        valinit=-60)
    slider_min.on_changed(update_min)
    slider_ax_max = plt.axes([left, bottom + 0.15, width, height])
    slider_max = Slider(slider_ax_max,
                        'Max',
                        valmin=-60,
                        valmax=10,
                        valstep=1,
                        valinit=10)
    slider_max.on_changed(update_max)
    ax.set_title("Working")
    t = Thread(target=monitor)
    t.start()
    plt.show()
Esempio n. 12
0
t_axis = plt.axes([0.25, 0.38, 0.65, 0.03], axisbg=axcolor)

axalpha = plt.axes([0.25, 0.32, 0.65, 0.03], axisbg=axcolor)
axbeta = plt.axes([0.25, 0.29, 0.65, 0.03], axisbg=axcolor)
axk = plt.axes([0.25, 0.26, 0.65, 0.03], axisbg=axcolor)

yaxalpha = plt.axes([0.25, 0.20, 0.65, 0.03], axisbg=axcolor)
yaxbeta = plt.axes([0.25, 0.17, 0.65, 0.03], axisbg=axcolor)
yaxk = plt.axes([0.25, 0.14, 0.65, 0.03], axisbg=axcolor)

zaxalpha = plt.axes([0.25, 0.08, 0.65, 0.03], axisbg=axcolor)
zaxbeta = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
zaxk = plt.axes([0.25, 0.02, 0.65, 0.03], axisbg=axcolor)

timeSlider = Slider(t_axis, "$t$", 10, 500, valinit=n, valfmt='%1d')

betaSlider = Slider(axbeta, "$\\beta_x$", 0, 2, valinit=xbeta0, valfmt='%1.3f')
alphaSlider = Slider(axalpha,
                     "$\\alpha_x$",
                     0,
                     0.5,
                     valinit=xalpha0,
                     valfmt='%1.3f')
kSlider = Slider(axk, "$k_x$", 0, 5, valinit=kx, valfmt='%1.3f')

y_betaSlider = Slider(yaxbeta,
                      "$\\beta_y$",
                      0,
                      2,
                      valinit=ybeta0,
Esempio n. 13
0
_, inner, outer = make_track()

ax.scatter(inner[:, 0], inner[:, 1], s=1)
ax.scatter(outer[:, 0], outer[:, 1], s=1)

ax.set_aspect('equal', adjustable='box')

axcolor = 'lightgoldenrodyellow'
a_sigma = plt.axes([0.25, 0.25, 0.65, 0.03], facecolor=axcolor)
a_gauss = plt.axes([0.25, 0.20, 0.65, 0.03], facecolor=axcolor)
a_density = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
a_bump = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
a_u = plt.axes([0.25, 0.05, 0.65, 0.03], facecolor=axcolor)
a_v = plt.axes([0.25, 0.0, 0.65, 0.03], facecolor=axcolor)

sigma_slider = Slider(a_sigma, 'Sigma', 0.1, 2.0, valinit=0.6, valstep=0.01)
track_slider = Slider(a_gauss, 'Track width', 0.5, 5, valinit=1, valstep=0.1)
density_slider = Slider(a_density,
                        'Density',
                        0.01,
                        0.3,
                        valinit=0.05,
                        valstep=0.01)
bump_slider = Slider(a_bump, 'Scale', 1.0, 40.0, valinit=20, valstep=0.1)

ellispse_u_slider = Slider(a_u,
                           'Stretch horizontally',
                           1.0,
                           100,
                           valinit=40,
                           valstep=0.5)
Esempio n. 14
0
def view_patches_bar(Yr, A, C, b, f, d1, d2, YrA=None, img=None):
    """view spatial and temporal components interactively

     Parameters:
     -----------
     Yr:    np.ndarray
            movie in format pixels (d) x frames (T)

     A:     sparse matrix
                matrix of spatial components (d x K)

     C:     np.ndarray
                matrix of temporal components (K x T)

     b:     np.ndarray
                spatial background (vector of length d)

     f:     np.ndarray
                temporal background (vector of length T)

     d1,d2: np.ndarray
                frame dimensions

     YrA:   np.ndarray
                 ROI filtered residual as it is given from update_temporal_components
                 If not given, then it is computed (K x T)

     img:   np.ndarray
                background image for contour plotting. Default is the image of all spatial components (d1 x d2)

    Returns:
    --------
    array of bools
        For each component, to keep it or to reject it

    """
    print("Press arrows left or right to navigate through components.")
    print("Press 'r' to remove a component, and 'k' to reverse a removal.")

    pl.ion()
    if 'csc_matrix' not in str(type(A)):
        A = csc_matrix(A)
    if 'array' not in str(type(b)):
        b = b.toarray()

    nr, T = C.shape
    keep = np.ones(nr, dtype=bool)
    nb = f.shape[0]
    nA2 = np.sqrt(np.array(A.power(2).sum(axis=0))).squeeze()

    if YrA is None:
        Y_r = spdiags(old_div(1, nA2), 0, nr, nr) * (A.T.dot(Yr) -
                                                     (A.T.dot(b)).dot(f) -
                                                     (A.dot(A)).dot(C)) + C
    else:
        Y_r = YrA + C

    if img is None:
        img = np.reshape(np.array(A.mean(axis=1)), (d1, d2), order='F')

    fig = pl.figure(figsize=(10, 10))

    axcomp = pl.axes([0.05, 0.05, 0.9, 0.03])

    ax1 = pl.axes([0.05, 0.55, 0.4, 0.4])
    ax3 = pl.axes([0.55, 0.55, 0.4, 0.4])
    ax2 = pl.axes([0.05, 0.1, 0.9, 0.4])

    s_comp = Slider(axcomp, 'Component', 0, nr + nb - 1, valinit=0)
    vmax = np.percentile(img, 98)

    def update(val):
        i = np.int(np.round(s_comp.val))
        print(('Component:' + str(i)))

        if i < nr:

            ax1.cla()
            imgtmp = np.reshape(A[:, i].toarray(), (d1, d2), order='F')
            ax1.imshow(imgtmp, interpolation='None', cmap=pl.cm.gray)
            if keep[i]:
                ax1.set_title('Spatial component ' + str(i + 1))
            else:
                ax1.set_title('Spatial component (Rejected) ' + str(i + 1))
            ax1.axis('off')

            ax2.cla()
            ax2.plot(np.arange(T), Y_r[i], 'c', linewidth=3)
            ax2.plot(np.arange(T), C[i], 'r', linewidth=2)
            if keep[i]:
                ax2.set_title('Temporal component ' + str(i + 1))
            else:
                ax2.set_title('Temporal component (Rejected)' + str(i + 1))
            ax2.legend(labels=['Filtered raw data', 'Inferred trace'])

            ax3.cla()
            ax3.imshow(img, interpolation='None', cmap=pl.cm.gray, vmax=vmax)
            imgtmp2 = imgtmp.copy()
            imgtmp2[imgtmp2 == 0] = np.nan
            ax3.imshow(imgtmp2,
                       interpolation='None',
                       alpha=0.5,
                       cmap=pl.cm.hot)
            ax3.axis('off')
        else:
            ax1.cla()
            bkgrnd = np.reshape(b[:, i - nr], (d1, d2), order='F')
            ax1.imshow(bkgrnd, interpolation='None')
            ax1.set_title('Spatial background ' + str(i + 1 - nr))
            ax1.axis('off')

            ax2.cla()
            ax2.plot(np.arange(T), np.squeeze(np.array(f[i - nr, :])))
            ax2.set_title('Temporal background ' + str(i + 1 - nr))

    def arrow_key_image_control(event):

        if event.key == 'left':
            new_val = np.round(s_comp.val - 1)
            if new_val < 0:
                new_val = 0
            s_comp.set_val(new_val)

        elif event.key == 'right':
            new_val = np.round(s_comp.val + 1)
            if new_val > nr + nb:
                new_val = nr + nb
            s_comp.set_val(new_val)

        elif event.key == 'k':
            '''This will set it so that the component is kept.'''
            keep[s_comp.val] = True
            s_comp.set_val(s_comp.val)

        elif event.key == 'r':
            '''This will set it so that the component is removed.'''
            keep[s_comp.val] = False
            s_comp.set_val(s_comp.val)

        else:
            pass

    s_comp.on_changed(update)
    s_comp.set_val(0)
    fig.canvas.mpl_connect('key_release_event', arrow_key_image_control)
    pl.show()
    return keep
        break

####################
# VISUALIZER W/ SCROLLBAR
plt.figure(2)
ax = pylab.subplot(111)
pylab.subplots_adjust(left=0.25, bottom=0.25)

frame = 0
l = pylab.imshow(data[frame, :, :], cmap='gray')
for i in range(np.size(pts, 0)):
    pylab.scatter(pts[i, 0], pts[i, 1], s=1, c='red', marker='o')

axcolor = 'lightgoldenrodyellow'
axframe = pylab.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
sframe = Slider(axframe, 'Frame', 0, frameCount, valinit=0)


def update(val):
    frame = int(sframe.val)
    l.set_data(data[frame, :, :])


sframe.on_changed(update)

pylab.show()

# convert the grayscale image to binary image
gray_image = data[50, :, :]
# resize frame
gray_image = cv2.resize(gray_image, None, fx=scaleFac, fy=scaleFac)
_imageIndex = 0
_imageTotal = len(_images)

_img = cv2.imread(_images[_imageIndex], cv2.IMREAD_UNCHANGED)
_img = cv2.cvtColor(_img, cv2.COLOR_BGR2GRAY)

_sliderInitVal = 10
_percentThreshold = _sliderInitVal
_threshold = _percentThreshold / 100 * 255

_fig = plt.figure("Binary Image with Adaptive Gaussian Thresholding")
_gs = GridSpec(15, 2)
_fig1 = plt.subplot(_gs[0:13, 0])
_fig1.set_title("Original")
_fig1ShowIt = plt.imshow(_img, cmap="gray")

_imgBin = cv2.adaptiveThreshold(_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                cv2.THRESH_BINARY, 7, _threshold)
_fig2 = plt.subplot(_gs[0:13, 1])
_fig2.set_title("Binary")
_fig2ShowIt = plt.imshow(_imgBin, cmap="gray")

_sliderAx = _fig.add_axes([0.2, 0.1, 0.4, 0.05])
_slider = Slider(_sliderAx, "Threshold (%)", 0, 20, valinit=_sliderInitVal)
_sliderCid = _slider.on_changed(_changeThreshold)
_ChangeAx = _fig.add_axes([0.7, 0.1, 0.1, 0.05])
_changeButton = Button(_ChangeAx, "Change Image")
_changeButtonCid = _changeButton.on_clicked(_changeImage)

plt.show()
Esempio n. 17
0
#部件显示位置及颜色
axcolor = 'lightgoldenrodyellow'
reset_ax = plt.axes(
    [reset_x, widgets_start, reset_width, widgets_hight * 2 + widgets_space])
freq_ax = plt.axes([left_space, widgets_start, slider_width, widgets_hight],
                   facecolor=axcolor)
amp_ax = plt.axes([left_space, widgets_start * 3, slider_width, widgets_hight],
                  facecolor=axcolor)
radio_ax = plt.axes([
    reset_x - reset_width, widgets_start, reset_width,
    widgets_hight * 2 + widgets_space
],
                    facecolor=axcolor)

#部件定义
sfreq = Slider(freq_ax, 'Freq', 0.1, 30.0, valinit=f0)
samp = Slider(amp_ax, 'Amp', 0.1, 10.0, valinit=a0)
radio = RadioButtons(radio_ax, ('red', 'blue', 'green'), active=1)
button = Button(reset_ax, 'Reset', color=axcolor, hovercolor='0.975')

#定期更新图像例子
count = 0
x = np.linspace(-3, 3)
#ax.plot(x, x ** 2)

ax.set_title('click on point to plot time series')
line, = ax.plot(x, x**2, 'o', picker=5)  # 5 points tolerance


#滑块参数变化事件处理函数
def update(val):
Esempio n. 18
0
ani = animation.FuncAnimation(fig, animate, interval=1)

#fig = plt.figure("slider")
#fig = plt.subplot(1, 2, 2)
#ax = fig.add_subplot(1, 2, 2)#, projection='3d')
#plt.subplots_adjust(left=0.5)
R1 = plt.axes([0.55, 0.1, 0.4, 0.05])
P1 = plt.axes([0.55, 0.2, 0.4, 0.05])
Y1 = plt.axes([0.55, 0.3, 0.4, 0.05])
R2 = plt.axes([0.55, 0.4, 0.4, 0.05])
P2 = plt.axes([0.55, 0.5, 0.4, 0.05])
Y2 = plt.axes([0.55, 0.6, 0.4, 0.05])
R3 = plt.axes([0.55, 0.7, 0.4, 0.05])
P3 = plt.axes([0.55, 0.8, 0.4, 0.05])
Y3 = plt.axes([0.55, 0.9, 0.4, 0.05])
roll1_silder = Slider(R1, 'roll_1', 0.0, 2.0 * np.pi, valinit=0, valstep=0.1)
pitch1_silder = Slider(P1, 'pitch_1', 0.0, 2.0 * np.pi, valinit=0, valstep=0.1)
yaw1_silder = Slider(Y1, 'yaw_1', 0.0, 2.0 * np.pi, valinit=0, valstep=0.1)
roll2_silder = Slider(R2, 'roll_2', 0.0, 2.0 * np.pi, valinit=0, valstep=0.1)
pitch2_silder = Slider(P2, 'pitch_2', 0.0, 2.0 * np.pi, valinit=0, valstep=0.1)
yaw2_silder = Slider(Y2, 'yaw_2', 0.0, 2.0 * np.pi, valinit=0, valstep=0.1)
roll3_silder = Slider(R3, 'roll_3', 0.0, 2.0 * np.pi, valinit=0, valstep=0.1)
pitch3_silder = Slider(P3, 'pitch_3', 0.0, 2.0 * np.pi, valinit=0, valstep=0.1)
yaw3_silder = Slider(Y3, 'yaw_3', 0.0, 2.0 * np.pi, valinit=0, valstep=0.1)


def update_slider(i):
    global Robot
    roll1 = roll1_silder.val
    pitch1 = pitch1_silder.val
    yaw1 = yaw1_silder.val
Esempio n. 19
0
    v_data = [np.sin(k * x - i) for x in x_data]
    ru, rv = rota(x_data, v_data, angle2, s2y)
    c2.set_data(ru, rv)

    s1.set_ydata(s1y)
    s2.set_ydata(s2y)


animation = FuncAnimation(f,
                          frame,
                          frames=np.linspace(0, 2 * np.pi, 20),
                          interval=100)

axX = plt.axes([0.2, 0.01, 0.6, 0.02])
sX = Slider(axX, "$X$", -50, 50)
axlamb = plt.axes([0.2, 0.04, 0.6, 0.02])
slamb = Slider(axlamb, r"$\lambda$", 2, 10)
axa = plt.axes([0.2, 0.07, 0.6, 0.02])
sa = Slider(axa, r"$a$", 0, 30)


def maj(_):
    global X
    global lamb
    global a
    X, lamb, a = sX.val, slamb.val, sa.val


sX.on_changed(maj)
slamb.on_changed(maj)
Esempio n. 20
0
def create_slider(districts_file, population_file, households_file,
                  persons_file, transmission_log):
    """
    Create plot with interactive slider.
    """
    #######################################
    # Gather information about districts. #
    #######################################

    districts = {}
    districts[0] = (0, 0, 0)

    latitudes = []
    longitudes = []

    with open(districts_file, 'r') as district_file:
        reader = csv.DictReader(district_file, delimiter=';')
        for row in reader:
            d_id = int(row['id'])
            x = float(row['latitude'].replace(",", "."))
            y = float(row['longitude'].replace(",", "."))
            pop_size = int(row['pop_size'])

            # Don't add districts with incorrect location data
            if abs(x) < 90 and abs(y) < 180:
                latitudes.append(x)
                longitudes.append(y)
                districts[d_id] = (x, y, pop_size)

    # Use Smopy to get map image for the given region (calculated from min/max latitudes/longitudes in districts file)
    region_map = smopy.Map(
        (min(latitudes), min(longitudes), max(latitudes), max(longitudes)),
        z=9)

    ##################################################################
    # Gather information about persons and households in simulation. #
    ##################################################################

    # Check how long each person stays ill (= infectious) when infected.
    person_infectiousness = {}
    with open(persons_file, 'r') as person_file:
        reader = csv.DictReader(person_file, delimiter=';')
        for row in reader:
            person_infectiousness[int(row['id'])] = row['end_infectiousness']

    # For each person, fetch the household ID
    person_households = []
    with open(population_file, 'r') as pop_file:
        reader = csv.DictReader(pop_file, delimiter=";")
        for row in reader:
            person_households.append(int(float(row['household_id'])))

    # For each household, fetch the district it belongs to.
    households = {}
    with open(households_file, 'r') as hh_file:
        reader = csv.DictReader(hh_file, delimiter=';')
        for row in reader:
            hh_id = int(row['id'])
            d_id = int(row['district_id'])
            households[hh_id] = d_id

    ########################################
    # Gather information about infections. #
    ########################################

    prepare_csv_transmissions(transmission_log, "infections.csv")

    infections = {}
    with open('./infections.csv', 'r') as infections_file:
        reader = csv.DictReader(infections_file, delimiter=",")
        for row in reader:
            person_id = int(row['person_id'])
            if (person_id < len(person_infectiousness) + 1):
                hh_id = person_households[person_id]
                district = households[hh_id]
                start_infected = int(row['begin_infection'])
                end_infected = start_infected + int(
                    person_infectiousness[person_id])

                for day in range(start_infected, end_infected + 1):
                    if day in infections:
                        # add extra infection
                        if district in infections[day]:
                            infections[day][district] += 1
                        else:
                            infections[day][district] = 1
                    else:
                        # add first infection
                        infections[day] = {}
                        infections[day][district] = 1

    ##################
    # Create figure. #
    ##################

    fig, ax = plt.subplots()
    fig.canvas.set_window_title("Evolution of disease spread")

    plt.subplots_adjust(bottom=0.25)

    # Legend for circles sizes (representing district population sizes).
    l1 = plt.scatter([], [], s=4, facecolors='none', edgecolors='black')
    l2 = plt.scatter([], [], s=16, facecolors='none', edgecolors='black')
    l3 = plt.scatter([], [], s=64, facecolors='none', edgecolors='black')
    l4 = plt.scatter([], [], s=256, facecolors='none', edgecolors='black')
    l5 = plt.scatter([], [], s=1024, facecolors='none', edgecolors='black')

    labels = ["< 224", "< 327", "< 525", "< 5000", "> 5000"]

    leg = plt.legend([l1, l2, l3, l4, l5],
                     labels,
                     ncol=5,
                     frameon=False,
                     fontsize=10,
                     handlelength=2,
                     loc=8,
                     bbox_to_anchor=[0.5, -0.15],
                     handletextpad=1,
                     title='District sizes',
                     scatterpoints=1)
    leg.get_title().set_position((0, -35))

    # Scatterplot to represent districts + fraction of infected per district.
    region_map.show_mpl(ax)
    l = plt.scatter([], [], alpha=0.5)
    l.axes.get_xaxis().set_ticks([])
    l.axes.get_yaxis().set_ticks([])

    axcolor = 'lightgoldenrodyellow'
    ax_day = plt.axes([0.12, 0.1, 0.79, 0.03], axisbg=axcolor)
    sday = Slider(ax_day, 'Day', 0.1, 100.0, valinit=1, valfmt='%0.0f')

    plt.subplots_adjust(bottom=0.15)

    # Legend for colors (representing fraction of infected in district).
    data_range = [0, 100]
    m = cm.ScalarMappable(cmap=cm.autumn_r)
    m.set_array(data_range)
    c = plt.colorbar(m, ax=ax, shrink=0.5, orientation="horizontal")
    c.set_label("Fraction of district infected")

    ###############################
    # Update function for slider. #
    ###############################

    def update(val):
        """
        Update the plot according to the value of the slider.
        """
        day = int(round(sday.val))

        xs = []
        ys = []
        offsets = []
        sizes = []
        colors = []

        if (day in infections):
            day_infections = infections[day]

            for key, value in districts.iteritems():
                x, y = region_map.to_pixels((value[0], value[1]))
                district_size = value[2]
                circle_size = 0

                if (district_size <= 224):
                    circle_size = 4
                elif (district_size <= 327):
                    circle_size = 16
                elif (district_size <= 525):
                    circle_size = 64
                elif (district_size <= 5000):
                    circle_size = 256
                else:
                    circle_size = 1024

                if key in day_infections:
                    num_infections = day_infections[key]
                    xs.append(x)
                    ys.append(y)
                    offsets.append([x, y])
                    sizes.append(circle_size)
                    colors.append(
                        [1, 1 - (float(num_infections) / district_size), 0])

        l.set_offsets(offsets)
        l.set_sizes(sizes)
        l.set_facecolors(np.array(colors))
        fig.canvas.draw_idle()

    # Execute update() when value of slider changes
    sday.on_changed(update)
    plt.show()
l, = plt.plot(x1, y1, lw=2, color='red')
lm, = plt.plot(x, y, lw=1, color='green')
plt.axis([A - w / 2, B + w / 2, (C + H / 2), (D - H / 2)])

axcolor = 'lightgoldenrodyellow'

ax0x = plt.axes([0.05, 0.90, 0.25, 0.03], facecolor=axcolor)
ax0y = plt.axes([0.05, 0.86, 0.25, 0.03], facecolor=axcolor)
ax1x = plt.axes([0.65, 0.90, 0.25, 0.03], facecolor=axcolor)
ax1y = plt.axes([0.65, 0.86, 0.25, 0.03], facecolor=axcolor)
ax2x = plt.axes([0.65, 0.18, 0.25, 0.03], facecolor=axcolor)
ax2y = plt.axes([0.65, 0.14, 0.25, 0.03], facecolor=axcolor)
ax3x = plt.axes([0.05, 0.18, 0.25, 0.03], facecolor=axcolor)
ax3y = plt.axes([0.05, 0.14, 0.25, 0.03], facecolor=axcolor)

s0x = Slider(ax0x, 'q0x', -2000, 2000, valinit=q0x)
s0y = Slider(ax0y, 'q0y', -2000, 2000, valinit=q0y)
s1x = Slider(ax1x, 'q1x', -2000, 2000, valinit=q1x)
s1y = Slider(ax1y, 'q1y', -2000, 2000, valinit=q1y)
s2x = Slider(ax2x, 'q2x', -2000, 2000, valinit=q2x)
s2y = Slider(ax2y, 'q2y', -2000, 2000, valinit=q2y)
s3x = Slider(ax3x, 'q3x', -2000, 2000, valinit=q3x)
s3y = Slider(ax3y, 'q3y', -2000, 2000, valinit=q3y)


def update(val):

    global m00
    global m01
    global m02
    global m10
Esempio n. 22
0
def poissonimg(val):
    global img
    λ = 2**(val - 8.0)
    imp = clip(poisson(img * λ) / λ, 0, 0xff).astype(int)
    DIH(imp, f'{val}EV')


def scotophotopic(label):
    global img, fig, mb, slEV
    img = cvtColor(imread(mb), RGB if label == 'RGB' else GRAY)
    DIH(img)
    slEV.reset()
    fig.canvas.draw_idle()  # Forces image refresh


# GUI elements
fig, _ = subplots()
subplots_adjust(left=.25, bottom=.25)

axEV, axc = axes([.25, .1, .65, .03]), axes([.025, .5, .15, .15])
slEV = Slider(axEV, 'EV', 0.0, 16.0, valinit=8.0, valstep=1.0)
radio = RadioButtons(axc, ('RGB', 'B&W'), active=0)
slEV.on_changed(poissonimg)
radio.on_clicked(scotophotopic)

# Image re/de-generation
mb = 'MB{}.png'.format(choice('ABCD'))
img = cvtColor(imread(mb), RGB)

poissonimg(8)
show()
Esempio n. 23
0
                    right=0.92,
                    hspace=0.5,
                    wspace=0.5)

fig1, ax4 = plt.subplots(figsize=(8, 5))
fig1.subplots_adjust(top=0.9, bottom=0.3, left=0.1, right=0.9)


def update(val):
    ax4.clear()
    ax4.grid(True)
    ax4.axhline(y=0, color='k')
    ax4.set_title(titles[4])
    ax4.set_ylim(-10, 10)
    ax4.set_xlabel('Time')
    ax4.set_ylabel('Amplitude')
    ax4.plot(x, y_[int(val)])


update(0)

ax_period = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor='lightgoldenrodyellow')
s_period = Slider(ax_period,
                  'Change harmonic',
                  0,
                  len(y_) - 1,
                  valinit=0,
                  valstep=1)
s_period.on_changed(update)

plt.show()
gs = gridspec.GridSpec(2, 2, height_ratios=[1, 10])
ax1 = plt.subplot(gs[0, :])  # top
ax2 = plt.subplot(gs[1, 0])  # left
ax3 = plt.subplot(gs[1, 1])  # right
axes = np.array([ax1, ax2, ax3])

fig = plt.subplots_adjust(top=0.95, left=0.07, bottom=0.2, right=1.0)

ax_slider_reference = plt.axes([0.25, 0.10, 0.6,
                                0.03])  # left, bottom, width, height
ax_slider_current = plt.axes([0.25, 0.05, 0.6,
                              0.03])  # left, bottom, width, height

slider_reference_frame = Slider(ax_slider_reference,
                                'Reference Frame',
                                0,
                                numFrames - 1,
                                valfmt='%0.0f',
                                valinit=reference_frameID)
slider_current_frame = Slider(ax_slider_current,
                              'Current Frame',
                              0,
                              numFrames - 1,
                              valfmt='%0.0f',
                              valinit=current_frameID)

slider_reference_frame.on_changed(update_frame)
slider_current_frame.on_changed(update_frame)

update_frame(42)

plt.show()
Esempio n. 25
0
def show_image_stack_multi_view(data,
                                interpolation="none",
                                axis_names=["Axis 0", "Axis 1", "Axis 2"],
                                **kwargs):
    """
    Display a stack of images

    """
    import matplotlib.pyplot as plt
    from matplotlib.widgets import Slider, Button, RadioButtons

    # check dim
    assert data.ndim == 3

    # generate figure
    fig = plt.figure()
    ax1 = plt.subplot(131)
    ax2 = plt.subplot(132)
    ax3 = plt.subplot(133)
    fig.subplots_adjust(left=0.25, bottom=0.25)

    # select first image
    s1 = [slice(0, 1), slice(None), slice(None)]
    s2 = [slice(None), slice(0, 1), slice(None)]
    s3 = [slice(None), slice(None), slice(0, 1)]
    im1 = data[s1].squeeze()
    im2 = data[s2].squeeze()
    im3 = data[s3].squeeze().transpose()

    ax1.set_ylabel(axis_names[1])
    ax1.set_xlabel(axis_names[2])

    ax2.set_ylabel(axis_names[0])
    ax2.set_xlabel(axis_names[2])

    ax3.set_ylabel(axis_names[1])
    ax3.set_xlabel(axis_names[0])

    # display image
    l = [None] * 3
    l[0] = ax1.imshow(im1, interpolation=interpolation, **kwargs)
    l[1] = ax2.imshow(im2, interpolation=interpolation, **kwargs)
    l[2] = ax3.imshow(im3, interpolation=interpolation, **kwargs)

    # define slider
    ax4 = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg="lightgoldenrodyellow")
    ax5 = fig.add_axes([0.25, 0.06, 0.65, 0.03], axisbg="lightgoldenrodyellow")
    ax6 = fig.add_axes([0.25, 0.02, 0.65, 0.03], axisbg="lightgoldenrodyellow")

    slider1 = Slider(ax4,
                     "%s index" % axis_names[0],
                     0,
                     data.shape[0] - 1,
                     valinit=0,
                     valfmt="%i")
    slider2 = Slider(ax5,
                     "%s index" % axis_names[1],
                     0,
                     data.shape[1] - 1,
                     valinit=0,
                     valfmt="%i")
    slider3 = Slider(ax6,
                     "%s index" % axis_names[2],
                     0,
                     data.shape[2] - 1,
                     valinit=0,
                     valfmt="%i")

    class Update:
        def __init__(self, axis):
            self.axis = axis

        def __call__(self, val):
            ind = int(val)
            s = [
                slice(ind, ind + 1) if i == self.axis else slice(None)
                for i in xrange(3)
            ]
            im = data[s].squeeze()
            if self.axis == 2:
                im = im.transpose()
            l[self.axis].set_data(im)
            fig.canvas.draw()

    slider1.on_changed(Update(0))
    slider2.on_changed(Update(1))
    slider3.on_changed(Update(2))

    plt.show()
Esempio n. 26
0
def procimg(imgfilename):
    v.imgdst = None
    v.old_rot_val = 0.0
    v.rot_val = 0.0
    v.image = cv2.cvtColor(cv2.imread(imgfilename), cv2.COLOR_BGR2RGB)
    v.image_dpi = 600
    v.thumb = resize(v.image)
    v.init_angle = -detect_ang(v.thumb)
    if (v.init_angle) > 45:
        v.init_angle -= 90
    if (v.init_angle) < 0:
        v.init_angle += 360
    print(f"init_angle = {v.init_angle}")
    v.thumb_dpi = v.thumb.shape[0] / v.image.shape[0] * v.image_dpi
    v.w_inch = v.thumb.shape[1] / v.thumb_dpi
    v.h_inch = v.thumb.shape[0] / v.thumb_dpi

    v.fig = plt.figure(figsize=(16, 9), dpi=100)
    v.ax_src = plt.subplot(221)
    v.ax_src.imshow(v.thumb, cmap='gray')
    v.ax_src.set_title('Source'), v.ax_src.set_xticks([]), v.ax_src.set_yticks(
        [])

    v.ax_dst = plt.subplot(222)
    v.ax_dst.imshow(v.thumb, cmap='gray')
    v.ax_dst.set_title('Target'), v.ax_dst.set_xticks([]), v.ax_dst.set_yticks(
        [])

    v.ax_slider_rot = plt.axes([0.25, 0.1, 0.6, 0.03],
                               facecolor='lightgoldenrodyellow')
    v.slider_rot = Slider(v.ax_slider_rot,
                          'Rotation',
                          0,
                          360,
                          valinit=0,
                          valstep=0.05)
    v.slider_rot.on_changed(slider_rot_update)

    v.ax_text_rot = plt.axes([0.9, 0.1, 0.05, 0.03],
                             facecolor='lightgoldenrodyellow')
    v.text_rot = TextBox(v.ax_text_rot, '', '0')
    v.text_rot.on_submit(text_rot_on_submit)

    v.ax_button_rot_0 = plt.axes([0.25, 0.07, 0.03, 0.03],
                                 facecolor='lightgoldenrodyellow')
    v.button_rot_0 = Button(v.ax_button_rot_0, 0)
    v.button_rot_0.on_clicked(button_rot_clicked(0.0))

    v.ax_button_rot_90 = plt.axes([0.29, 0.07, 0.03, 0.03],
                                  facecolor='lightgoldenrodyellow')
    v.button_rot_90 = Button(v.ax_button_rot_90, 90)
    v.button_rot_90.on_clicked(button_rot_clicked(90.0))

    v.ax_button_rot_180 = plt.axes([0.33, 0.07, 0.03, 0.03],
                                   facecolor='lightgoldenrodyellow')
    v.button_rot_180 = Button(v.ax_button_rot_180, 180)
    v.button_rot_180.on_clicked(button_rot_clicked(180.0))

    v.ax_button_rot_270 = plt.axes([0.37, 0.07, 0.03, 0.03],
                                   facecolor='lightgoldenrodyellow')
    v.button_rot_270 = Button(v.ax_button_rot_270, 270)
    v.button_rot_270.on_clicked(button_rot_clicked(270.0))

    #s1, s2 = plt.subplots()
    v.rectangle_selector = RectangleSelector(
        v.ax_src,
        line_select_callback,
        drawtype='box',
        useblit=True,
        button=[1, 3],  # don't use middle button
        minspanx=5,
        minspany=5,
        spancoords='pixels',
        interactive=True)

    rot_update()

    #plt.connect('key_press_event', toggle_selector)

    plt.show()

    if v.imgdst is not None:
        cv2.imwrite(
            os.path.splitext(imgfilename)[0] + ".1080.jpg",
            cv2.cvtColor(v.imgdst, cv2.COLOR_RGB2BGR))
Esempio n. 27
0
plt.title("Secant Modified Method")
plt.ylabel("Y axis")
plt.xlabel("X axis")
plt.legend()

# slider functionality
# This create the slider axe, (again remember that an axe is pretty much like a "plot" or "image" on a figure)
# The first 2 numbers are like the where the left and bottom part of the slider starts, so 0.1 and 0.01 so its pretty low
# the last 2 numer is the width and height of the slider
axSlider1 = plt.axes([0.3, 0.01, 0.4, 0.05])

# this line will turn the axe into an actual slider instead of a blank "plot" or image"
# If you want to icnrease the total number of iteration available change valmax
iterationSlider = Slider(axSlider1,
                         "# of iterations",
                         valmin=1,
                         valmax=20,
                         valinit=1,
                         valstep=1)

# This is the function that the slider will use when you change the slider value, will be explained later
# What this function do is like what you read in the textbook the f(xl)*f(xu) < 0 and blah blah rule


def newPoint(val):
    iteration = int(iterationSlider.val)
    initialval = initial
    global deltaval
    deltax = deltaval * initialval

    y0 = equationf(initialval + deltax)
    y1 = equationf(initialval)
Esempio n. 28
0
        r_i + 1,
        U_Eff_Func(r_i) + .005,
        '(r_p=' + str(int(r_i * (10**5)) / (10**5)) + ', e= ' +
        str(int(get_e(r_i, sol.y_events[0][0][0]) * 10**5) / 10**5) + ')')
except IndexError:
    ax2.text(r_i + 1,
             U_Eff_Func(r_i) + .005,
             '(r_p=' + str(int(r_i * (10**5)) / (10**5)) + ', e=???)')
# ax2.text(4+.01, U_Eff_Func(4) + .002, 'E=' + str(int(U_Eff_Func(4)*(10**5))/(10**5)))
# ax2.text(12+.02, U_Eff_Func(12)-.003, 'E=' + str(int(U_Eff_Func(12)*(10**5))/(10**5)))

# Add slider for energy
ax_E = plt.axes([.10, .15, .4, .02], facecolor='lightgoldenrodyellow')
s_E = Slider(ax_E,
             'Energy',
             -.05,
             .05,
             valinit=U_Eff_Func(r_i),
             valstep=.00001)

# Add slider for angular momentum
ax_L = plt.axes([.10, .1, .4, .02], facecolor='lightgoldenrodyellow')
s_L = Slider(ax_L, 'Ang Momentum', 0, 10, valinit=L, valstep=.01)

# Add text box to manually input energy
ax_text_L = plt.axes([.55, .15, .1, .025])
text_bot_E = TextBox(ax_text_L,
                     ' ',
                     initial=str(int(U_Eff_Func(r_i) * (10**5)) / (10**5)))

# Add text box to manually input angular momentum
ax_text_E = plt.axes([.55, .1, .1, .025])
Esempio n. 29
0
def represent(queue):

    # Setup
    fig, ax = plt.subplots()
    frames = queue.get()

    # Remove top and right box segments
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)

    # Slider
    axslider = plt.axes([0.25, .03, 0.50, 0.02])
    slider = Slider(axslider,
                    'Frame',
                    0,
                    len(frames),
                    valinit=len(frames),
                    valstep=1)

    def previous_frame(event):
        slider.set_val(slider.val - 1)

    def next_frame(event):
        slider.set_val(slider.val + 1)

    axprev = plt.axes([0.86, 0.01, 0.06, 0.04])
    axnext = plt.axes([0.92, 0.01, 0.06, 0.04])
    bprev = Button(axprev, '<-')
    bprev.on_clicked(previous_frame)
    bnext = Button(axnext, '->')
    bnext.on_clicked(next_frame)

    # Animation updater
    def update_frame(i):
        global frames
        global previous_slider_value
        # Update frames when the queue is not empty
        if queue.qsize() > 0:
            frames = queue.get()
        minimum = 0
        maximum = len(frames) - 1
        # Update the slider val in case it is out of minimum/maximum range
        # This may happen when using the buttons
        if slider.val < minimum:
            slider.set_val(minimum)
        if slider.val > maximum:
            slider.set_val(maximum)
        # Find out if the slider value is the last (current) value
        updated = slider.val == slider.valmax
        # Update the maximum slider value
        slider.valmax = maximum
        if maximum != 0:
            slider.ax.set_xlim(
                slider.valmin,
                slider.valmax)  # This is necessary to make the valmax stable
        # If the slider is in the maximum value we keep it updated
        if updated:
            slider.set_val(maximum)

        # Check the current slider value
        # If it has no changed since last update then do nothing
        slider_value = int(slider.val)
        if slider_value == previous_slider_value:
            return

        previous_slider_value = slider_value

        # Clear previous segments and rects
        #ax.segments = []
        ax.clear()

        # Get everything to be displayed in the current frame
        segments, rects, traced = frames[slider_value]

        # Draw all segments
        for segment in segments:
            xs = [segment.a.x, segment.b.x]
            ys = [segment.a.y, segment.b.y]
            ploted_segments = ax.plot(xs, ys, color=segment.color)

        # Draw all rect areas
        for rect in rects:
            pulc = rect.get_upper_left_point()
            pbrc = rect.get_bottom_right_point()
            xs = [rect.pmin.x, pulc.x, rect.pmax.x, pbrc.x]
            ys = [rect.pmin.y, pulc.y, rect.pmax.y, pbrc.y]
            # WARNING: Use 'facecolor' instead of 'color' to hide separation segments between fills
            ploted_rects = ax.fill(xs,
                                   ys,
                                   facecolor=rect.fill_color or 'C0',
                                   alpha=0.2)

        # Set the legend with all room names
        handles = []
        for track in traced:
            facecolor = to_rgba(track.fill_color)
            facecolor = (facecolor[0], facecolor[1], facecolor[2], 0.2
                         )  # Reduce the opacity
            patch = mpatches.Patch(facecolor=facecolor,
                                   edgecolor=track.segments_color,
                                   label=track.name)
            handles.append(patch)
        columns_number = math.ceil(len(handles) / 2)
        ax.legend(handles=handles,
                  loc='upper center',
                  bbox_to_anchor=(0.5, 1.15),
                  ncol=columns_number)
        #legend.handles = handles

    # Run the animation and show the plot
    anim = animation.FuncAnimation(fig, update_frame)
    plt.show()
Esempio n. 30
0
def create_result_slider(q, interval, n):
    global is_manual
    fig, ax = plt.subplots()
    l1, = plt.plot([], [], '.')
    l2, = plt.plot([], [], '.')
    axamp = plt.axes([0.25, .03, 0.50, 0.02])
    # Slider
    samp = Slider(axamp,
                  'Step',
                  valmin=0,
                  valmax=q.shape[0] - 1,
                  valstep=1,
                  valinit=0)

    # Animation controls
    is_manual = False  # True if user has taken control of the animation

    def init_animation():
        a = 1
        x_max, x_min = np.max(q[:, :, 0]), np.min(q[:, :, 0])
        y_max, y_min = np.max(q[:, :, 1]), np.min(q[:, :, 1])
        ax.set_xlim(x_min - a, x_max + a)
        ax.set_ylim(y_min - a, y_max + a)
        return l1, l2

    def update_slider(val):
        global is_manual
        is_manual = True
        update(val)

    def update(val):
        # update curve
        l1.set_data(q[val, :n, 0], q[val, :n, 1])
        l2.set_data(q[val, n:, 0], q[val, n:, 1])
        # redraw canvas while idle
        fig.canvas.draw_idle()

    def update_plot(num):
        global is_manual
        if is_manual:
            return l1, l2  # don't change

        samp.set_val(num % q.shape[0])
        is_manual = False  # the above line called update_slider, so we need to reset this
        return l1, l2

    def on_click(event):
        # Check where the click happened
        (xm, ym), (xM, yM) = samp.label.clipbox.get_points()
        if xm < event.x < xM and ym < event.y < yM:
            # Event happened within the slider, ignore since it is handled in update_slider
            return
        else:
            # user clicked somewhere else on canvas = unpause
            global is_manual
            is_manual = False

    # call update function on slider value change
    samp.on_changed(update_slider)

    fig.canvas.mpl_connect('button_press_event', on_click)

    return ani.FuncAnimation(fig,
                             update_plot,
                             interval=interval,
                             init_func=init_animation,
                             frames=q.shape[0])