예제 #1
0
def plot_omega(n):
    X, Y = np.meshgrid(xu, yv)

    fig, ax = plt.subplots()
    ax.set_title(
        r'$\frac{\omega h_{hill}}{u_{hill}}$ $at$ $\frac{t u_{hill}}{h_{hill}} = %0.6f $'
        % (float(n * 1000) * dt * u_hill / h_hill))
    image = ax.contourf(X,
                        Y,
                        results_omega,
                        500,
                        cmap=cm.seismic,
                        norm=colors.CenteredNorm(0))
    ax.axis('scaled')
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='5%', pad=0.05)

    ax.fill(x_fill, y_fill, 'k')
    cb = plt.colorbar(image, cax=cax)
    cb.locator = ticker.MaxNLocator(nbins=5)
    cb.update_ticks()

    ax.set_xlabel(r'$\frac{x}{h_{hill}}$')
    ax.set_ylabel(r'$\frac{y}{h_{hill}}$')

    return
def reshape_nuSGS(res):
    a = np.reshape(res,(Ny+1,Nx+1))
    return a


    fig, ax = plt.subplots()
    ax.set_title(r'$\frac{\omega h_{hill}}{u_{hill}}$ $at$ $\frac{t u_{hill}}{h_{hill}} = %0.6f $' % (float(n*1000)*dt*u_hill/h_hill))
    image = ax.contourf(X, Y, results_omega, 500, cmap=cm.seismic, norm=colors.CenteredNorm(0))
    ax.axis('scaled')
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='5%', pad=0.05)

    # plt.colorbar(image, cax=cax)
    cb = plt.colorbar(image, cax=cax)
    cb.locator = ticker.MaxNLocator(nbins=5)
    cb.update_ticks()
    #mask
    x_fill = np.linspace(0,8,100)
    y_fill = np.exp(-0.5*((x_fill-4)/1.5)**2)
    ax.fill(x_fill,y_fill,'k')

    ax.set_xlabel(r'$\frac{x}{h_{hill}}$')
    ax.set_ylabel(r'$\frac{y}{h_{hill}}$')

    return
def plot_u(n):
    X, Y = np.meshgrid(xu, yu)
    Tau = 1200 * u_hill / h_hill
    fig, ax = plt.subplots()
    ax.set_title(
        r'$\frac{u}{u_{hill}}$ $at$ $\frac{t u_{hill}}{h_{hill}} = %0.6f $' %
        (float(n * 1000) * dt * u_hill / h_hill))
    image = ax.contourf(X,
                        Y,
                        results_u,
                        500,
                        cmap=cm.seismic,
                        norm=colors.CenteredNorm(0))
    ax.axis('scaled')
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='5%', pad=0.05)

    cb = plt.colorbar(image, cax=cax)
    cb.locator = ticker.MaxNLocator(nbins=5)
    cb.update_ticks()

    x_fill = np.linspace(0, 20, 1000)
    y_fill = np.exp(-0.5 * ((x_fill - 4) / 1.5)**2)
    ax.fill_between(x_fill, y_fill, color='k')
    ax.set_xlabel(r'$\frac{x}{h_{hill}}$')
    ax.set_ylabel(r'$\frac{y}{h_{hill}}$')
    return
예제 #4
0
def value_function(ax, X_value, grids,
                   XV=None, cont_lvls=10, mynorm=None, mymap=None,viability_threshold=None):

    if mynorm is None:
        mynorm = colors.CenteredNorm()
    if mymap is None:
        mymap = plt.get_cmap('bwr_r')

    extent = [grids['states'][1][0],
            grids['states'][1][-1],
            grids['states'][0][0],
            grids['states'][0][-1]]

    # * Value Function

    pc = ax.imshow(X_value, origin='lower', extent=extent, aspect='auto',
            interpolation='none', norm=mynorm, cmap=mymap)
    if viability_threshold:
        cont_vibl = ax.contour(grids['states'][1], grids['states'][0], X_value,
                            levels=[viability_threshold, ], colors='k')
    cont1 = ax.contour(grids['states'][1], grids['states'][0], X_value,
                        levels=cont_lvls, colors='k')
    if XV is not None:
        ax.contour(grids['states'][1], grids['states'][0], XV.astype(float),
                    colors=ground_truth_color, levels=[0.,], extend='both',
                    linewidths=2.5, alpha=0.75)

    return pc
예제 #5
0
def reward_function(ax, RX_value, grids,
                   XV=None, mynorm=None, mymap=None,viability_threshold=None):

    if mynorm is None:
        mynorm = colors.CenteredNorm()
    if mymap is None:
        mymap = plt.get_cmap('bwr_r')

    extent = [grids['states'][1][0],
            grids['states'][1][-1],
            grids['states'][0][0],
            grids['states'][0][-1]]


    pc = ax.imshow(RX_value, origin='lower', extent=extent, aspect='auto',
            interpolation='none', norm=mynorm, cmap=mymap)

    if XV is not None:
        cs0 = ax.contourf(grids['states'][1], grids['states'][0], XV, levels=2,
                        hatches=['/', None], colors='none', extend='both', alpha=0.0)
        ax.contour(grids['states'][1], grids['states'][0], XV.astype(float),
                    colors=ground_truth_color, levels=[0.,], extend='both',
                    linewidths=2.5, alpha=0.75)
        # ax.contour(grids['states'][1], grids['states'][0], XV.astype(float),
        #             colors=ground_truth_color, levels105=[0.,], extend='both')

    for c in cs0.collections:
        c.set_edgecolor("face")


    # plt.setp(ax.get_xticklabels(), visible=False)

    return pc
예제 #6
0
 def get_centered_norm(self, clip_threshold_quantile):
     """Return a matplotlib norm to center map data around its mean value."""
     global_mean = self.map_data.mean()
     clip_threshold = (self.map_data -
                       global_mean).abs().quantile(clip_threshold_quantile)
     if np.isclose(clip_threshold, 0):
         clip_threshold = 0.1 if np.isclose(global_mean,
                                            0) else 0.1 * abs(global_mean)
     return mcolors.CenteredNorm(global_mean, clip_threshold)
예제 #7
0
def test_CenteredNorm():
    np.random.seed(0)

    # Assert equivalence to symmetrical Normalize.
    x = np.random.normal(size=100)
    x_maxabs = np.max(np.abs(x))
    norm_ref = mcolors.Normalize(vmin=-x_maxabs, vmax=x_maxabs)
    norm = mcolors.CenteredNorm()
    assert_array_almost_equal(norm_ref(x), norm(x))

    # Check that vcenter is in the center of vmin and vmax
    # when vcenter is set.
    vcenter = int(np.random.normal(scale=50))
    norm = mcolors.CenteredNorm(vcenter=vcenter)
    norm.autoscale_None([1, 2])
    assert norm.vmax + norm.vmin == 2 * vcenter

    # Check that halfrange can be set without setting vcenter and that it is
    # not reset through autoscale_None.
    norm = mcolors.CenteredNorm(halfrange=1.0)
    norm.autoscale_None([1, 3000])
    assert norm.halfrange == 1.0

    # Check that halfrange input works correctly.
    x = np.random.normal(size=10)
    norm = mcolors.CenteredNorm(vcenter=0.5, halfrange=0.5)
    assert_array_almost_equal(x, norm(x))
    norm = mcolors.CenteredNorm(vcenter=1, halfrange=1)
    assert_array_almost_equal(x, 2 * norm(x))

    # Check that halfrange input works correctly and use setters.
    norm = mcolors.CenteredNorm()
    norm.vcenter = 2
    norm.halfrange = 2
    assert_array_almost_equal(x, 4 * norm(x))

    # Check that prior to adding data, setting halfrange first has same effect.
    norm = mcolors.CenteredNorm()
    norm.halfrange = 2
    norm.vcenter = 2
    assert_array_almost_equal(x, 4 * norm(x))

    # Check that manual change of vcenter adjusts halfrange accordingly.
    norm = mcolors.CenteredNorm()
    assert norm.vcenter == 0
    # add data
    norm(np.linspace(-1.0, 0.0, 10))
    assert norm.vmax == 1.0
    assert norm.halfrange == 1.0
    # set vcenter to 1, which should double halfrange
    norm.vcenter = 1
    assert norm.vmin == -1.0
    assert norm.vmax == 3.0
    assert norm.halfrange == 2.0
예제 #8
0
def animate(i):
    global U_prev, U_curr, F, surf, ax

    for j in range(i * draw_every, (i + 1) * draw_every):
        F = get_F(f, j * dt, points)
        # Calculate the left hand side
        B = get_rhs(dt, S, T, U_curr, U_prev, F)

        # move one step
        U_prev = U_curr.copy()
        U_curr = spsolve(A, B)

    # Update the plot
    # Remove elements
    surf.remove()
    # cb.remove()

    # # Get the new colormap levels
    # mid = 0 #(U_curr.min() + U_curr.max())/2
    # m = mid - max(abs(U_curr.min() - mid),abs(U_curr.max() - mid))
    # M = mid + max(abs(U_curr.min() - mid),abs(U_curr.max() - mid))
    # clev = np.linspace(m,M,49)

    # Get the values along the z-plane
    U = np.array([
        np.mean(U_curr[mesh.simplices[mesh.find_simplex([r, z])]]) for r in RR
    ])
    interp = interpolate.make_interp_spline(RR, U)
    U = interp(RR)

    Ff = lambda x, y: interp((x**2 + y**2)**0.5)
    Z = Ff(X, Y)

    # Plot the 3D version
    surf = ax.plot_surface(X,
                           Y,
                           Z,
                           rstride=1,
                           cstride=1,
                           cmap=cm.coolwarm,
                           norm=colors.CenteredNorm(),
                           edgecolor='none')
    # surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap=cm.coolwarm, edgecolor='none')
    # cb = fig.colorbar(surf)

    ax.set_title(r'Wave in $\phi$-slice t=%.2e' % (i * dt))

    progress1.update(i)

    return surf
예제 #9
0
def animation_frame(i):
    ax.set_title(
        r'$\frac{\omega h_{hill}}{u_{hill}}$ $at$ $\frac{t u_{hill}}{h_{hill}} = %0.6f $'
        % (i * save_step * dt * u_hill / h_hill))
    c = ax.contourf(X,
                    Y,
                    results_omega[int(i)],
                    500,
                    cmap=cm.seismic,
                    norm=colors.CenteredNorm(0))
    # divider = make_axes_locatable(ax)
    #
    # cb.update_ticks()
    ax.set_xlim([0, 40])
예제 #10
0
    def plot_stresses(self, show_nodes=True, show_text=True):
        try:
            name = self.model['name']
            nodes = self.model['nodes']
            elements = self.model['elements']
            # Get values from the model and the elements
            x = np.asarray([val[0] for val in nodes.values()])
            y = np.asarray([val[1] for val in nodes.values()])
            tri = np.asarray([el.nodes for el in elements.values()])
            sx = np.asarray([el.stress[0] for el in elements.values()])
            sy = np.asarray([el.stress[1] for el in elements.values()])
            txy = np.asarray([el.stress[2] for el in elements.values()])
            stress = [sx, sy, txy]

            for i in range(3):
                stress_name = ['σ_x', 'σ_y', 'τ_xy']
                fig, ax = plt.subplots(
                    num=
                    f'PlaneTriangular2D: Stress {stress_name[i]} - Model: {name}'
                )
                ax.set_aspect('equal')
                ax.set_xlabel('X')
                ax.set_ylabel('Y')
                # Plot nodes as black dots
                if show_nodes:
                    ax.scatter(x, y, color='k', zorder=4)
                ax.set_title(f'Model: {name} - Stress: {stress_name[i]}')
                tpc = ax.tripcolor(x,
                                   y,
                                   tri,
                                   facecolors=stress[i],
                                   edgecolor='k',
                                   norm=colors.CenteredNorm(),
                                   cmap='bwr')
                fig.colorbar(tpc)
                if show_text:
                    for el in elements.values():
                        ax.text(el.centroid[0],
                                el.centroid[1],
                                str(f'{el.stress[i]:+.3e}'),
                                color='black',
                                ha='center',
                                va='center',
                                fontsize=10,
                                zorder=5)
            plt.show()
        except Exception as e:
            logger.exception(e)
            return None
예제 #11
0
xu = np.arange(0, (Nx+1)*dx, dx)/500.
yu = np.arange(0, Ny*dx, dx)/500.
xv = np.arange(0, Nx*dx, dx)/500.
yv = np.arange(0, (Ny+1)*dx, dx)/500.


# How to animation


X,Y = np.meshgrid(xu,yv)

fig,ax = plt.subplots()

ax.set_title(r'$\frac{\omega h_{hill}}{u_{hill}}$ $at$ $\frac{t u_{hill}}{h_{hill}} = %0.6f $' % (float(0*1000)*dt*u_hill/h_hill))

image = ax.contourf(X, Y, results_omega[0],500, cmap=cm.seismic,norm=colors.CenteredNorm(0))
ax.axis('scaled')


x_fill = np.linspace(0,40,1000)
y_fill = (1+4.5*h/h_hill)*np.exp(-0.5*((x_fill-4)/1.5)**2)
ax.fill(x_fill,y_fill,'k')

ax.set_xlabel(r'$\frac{x}{h_{hill}}$')
ax.set_ylabel(r'$\frac{y}{h_{hill}}$')

def animation_frame(i):
    ax.set_title(r'$\frac{\omega h_{hill}}{u_{hill}}$ $at$ $\frac{t u_{hill}}{h_{hill}} = %0.6f $' % (i*save_step*dt*u_hill/h_hill))
    c  = ax.contourf(X, Y, results_omega[int(i)],500, cmap=cm.seismic,norm=colors.CenteredNorm(0))
    ax.set_xlim([0,40])
anim = animation.FuncAnimation(fig,func = animation_frame, frames = number_of_saves,interval = 500)
예제 #12
0
x = np.arange(-3.0, 4.001, delta)
y = np.arange(-4.0, 3.001, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (0.9 * Z1 - 0.5 * Z2) * 2

# select a divergent colormap
cmap = cm.coolwarm

fig, (ax1, ax2) = plt.subplots(ncols=2)
pc = ax1.pcolormesh(Z, cmap=cmap)
fig.colorbar(pc, ax=ax1)
ax1.set_title('Normalize()')

pc = ax2.pcolormesh(Z, norm=colors.CenteredNorm(), cmap=cmap)
fig.colorbar(pc, ax=ax2)
ax2.set_title('CenteredNorm()')

plt.show()

###############################################################################
# Symmetric logarithmic
# ---------------------
#
# Similarly, it sometimes happens that there is data that is positive
# and negative, but we would still like a logarithmic scaling applied to
# both.  In this case, the negative numbers are also scaled
# logarithmically, and mapped to smaller numbers; e.g., if ``vmin=-vmax``,
# then the negative numbers are mapped from 0 to 0.5 and the
# positive from 0.5 to 1.
h = (xu[1]-xu[0])*h_hill

"""
Omega_plot
"""
n = 2

results_omega = reshape_omega(get_array_from_file('C:/Users/robbe/Documents/GitHub/LMECA_2660_results/Results200000/omega_N%d.bin' % int(n*1000)))*h_hill/u_hill

X, Y = np.meshgrid(xu, yv)

fig, ax = plt.subplots(2,2)
fig.suptitle(r'$\frac{\omega h_{hill}}{u_{hill}}$')
ax[0,0].set_title(r'$\frac{t u_{hill}}{h_{hill}} = %0.6f $' %(float(n*1000)*dt*u_hill/h_hill))
image = ax[0,0].contourf(X, Y, results_omega, 500, cmap=cm.seismic, norm=colors.CenteredNorm(0))
ax[0,0].axis('scaled')
divider = make_axes_locatable(ax[0,0])
cax = divider.append_axes('right', size='5%', pad=0.05)

x_fill = np.linspace(0,20,1000)
y_fill = (1+4.5*h/h_hill)*np.exp(-0.5*((x_fill-4)/1.5)**2)
ax[0,0].fill_between(x_fill,y_fill,color='k')
cb = plt.colorbar(image, cax=cax)
cb.locator = ticker.MaxNLocator(nbins=5)
cb.update_ticks()
ax[0,0].set_xlim(0,8)
ax[0,0].set_ylabel(r'$\frac{y}{h_{hill}}$')

n = 8
예제 #14
0
def animation_frame(i):
    ax.set_title(r'$\frac{\omega h_{hill}}{u_{hill}}$ $at$ $\frac{t u_{hill}}{h_{hill}} = %0.6f $' % (i*save_step*dt*u_hill/h_hill))
    c  = ax.contourf(X, Y, results_omega[int(i)],500, cmap=cm.seismic,norm=colors.CenteredNorm(0))
    ax.set_xlim([0,40])
예제 #15
0
def plot_omega(n, n2):

    X, Y = np.meshgrid(xu, yv)

    fig, ax = plt.subplots(2, 1)
    ax[0].set_title(
        r'$\frac{\omega h_{hill}}{u_{hill}}$ $at$ $\frac{t u_{hill}}{h_{hill}} = %0.6f$ $with$ $N_x=800$'
        % (float(n * 1000) * dt * u_hill / h_hill))

    image = ax[0].contourf(X,
                           Y,
                           results_omega,
                           500,
                           cmap=cm.seismic,
                           norm=colors.CenteredNorm(0))
    ax[0].axis('scaled')
    divider = make_axes_locatable(ax[0])
    cax = divider.append_axes('right', size='5%', pad=0.05)

    ax[1].set_xlabel(r'$\frac{x}{h_{hill}}$')
    ax[0].set_ylabel(r'$\frac{y}{h_{hill}}$')

    #plt.colorbar(image, cax=cax)
    x_fill = np.linspace(0, 8, 100)
    y_fill = np.exp(-0.5 * ((x_fill - 4) / 1.5)**2)
    ax[0].fill(x_fill, y_fill, 'k')

    X2, Y2 = np.meshgrid(xu2, yv2)
    cb = plt.colorbar(image, cax=cax)
    cb.locator = ticker.MaxNLocator(nbins=5)
    cb.update_ticks()

    image2 = ax[1].contourf(X2,
                            Y2,
                            results_omega2,
                            500,
                            cmap=cm.seismic,
                            norm=colors.CenteredNorm(0))

    ax[1].set_title(r'$with$ $Nx = 1600$ ')

    ax[1].axis('scaled')
    divider = make_axes_locatable(ax[1])
    cax = divider.append_axes('right', size='5%', pad=0.05)

    #plt.colorbar(image2, cax=cax)

    cb = plt.colorbar(image2, cax=cax)
    cb.locator = ticker.MaxNLocator(nbins=5)
    cb.update_ticks()

    ax[1].set_ylabel(r'$\frac{y}{h_{hill}}$')
    ax[1].fill(x_fill, y_fill, 'k')
    # ax[0].set_xlim([0,10])
    # ax[1].set_xlim([0,10])

    ax[0].set_xlim([1, 6.5])
    ax[1].set_xlim([1, 6.5])

    ax[0].set_ylim([0.5, 1.5])
    ax[1].set_ylim([0.5, 1.5])

    return
예제 #16
0
    return Re_h, CFL, Four


Re_h, CFL, Four = ReCFL_field(results_u, results_v, results_nuSGS)

X, Y = np.meshgrid(xv, yu)
fig, ax = plt.subplots()
ax.set_title(
    r'$Re_h = \frac{h(|u|+|v|)}{\nu_{SGS}}$ $at$ $\frac{t u_{hill}}{h_{hill}} = %0.6f $'
    % (float(n * 1000) * dt * u_hill / h_hill))
image = ax.contourf(X,
                    Y,
                    Re_h,
                    500,
                    cmap=cm.seismic,
                    norm=colors.CenteredNorm(0))
ax.axis('scaled')
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)

cb = plt.colorbar(image, cax=cax)
cb.locator = ticker.MaxNLocator(nbins=5)
cb.update_ticks()

x_fill = np.linspace(0, 8, 100)
y_fill = np.exp(-0.5 * ((x_fill - 4) / 1.5)**2)
ax.fill(x_fill, y_fill, 'k')
ax.set_xlabel(r'$\frac{x}{h_{hill}}$')
ax.set_ylabel(r'$\frac{y}{h_{hill}}$')

fig, ax = plt.subplots()
예제 #17
0
def _loop_once():
    '''Run the main loop once
    This uses the global variables from setup and start, and adds a set of global variables
    '''
    global parser, args, config, r, response, patch
    global monitor, H, A
    global D, stepsize
    global data_A, filepath_A
    global data_B, filepath_B
    global scale_lowpass, scale_highpass, scale_notchfilter, offset_lowpass, offset_highpass, offset_notchfilter, scale_filtorder, scale_notchquality, offset_filtorder, offset_notchquality
    global nChannels, fSample, nSamples, labels
    global lpfreq, hpfreq, filtorder, hp, lp
    global filenames, indx, filenr, filename, f, data, chanindx, filters, cmap, fig, axes, i, ax, im, divider, cax, prefix, icomp, comp, iweight, weight, key

    if fileformat == 'edf':

        filenames = glob.glob(filepath_A) + glob.glob(filepath_B)
        indx      = np.concatenate(   (  np.zeros(len(glob.glob(filepath_A))), np.ones(len(glob.glob(filepath_B)))  )  )
        monitor.info('Found %d files for condition A, and %d files for condition B' % (len(glob.glob(filepath_A)), len(glob.glob(filepath_B))))

        # get info about available recordings
        nChannels   = []
        fSample     = []
        nSamples    = []
        for filenr, filename in enumerate(filenames):
            f = EDF.EDFReader()
            f.open(filename)

            if any(np.diff(f.getSignalFreqs())):
                raise AssertionError('unequal SignalFreqs in recording')
            if any(np.diff(f.getNSamples())):
                raise AssertionError('unequal NSamples in recording')

            nChannels.append(len(f.getSignalFreqs()))
            nSamples.append(f.getNSamples()[0])
            fSample.append(f.getSignalFreqs()[0])
            monitor.info('%d channels with %d samples at %d Hz found in: %s' % (nChannels[-1], nSamples[-1], fSample[-1], filename))
            f.close()

        if any(np.diff(nChannels)):
            raise AssertionError('Different number of channels in files!')

        if any(np.diff(fSample)):
            raise AssertionError('Different samplerates in files!')

        if any(np.diff(nSamples)):
            monitor.info('Different number of samples in files, will only read the minimum of (%d samples)' % (min(nSamples)))

        # read condition A
        data = np.ndarray(shape=(len(filenames), nChannels[0], min(nSamples)), dtype=np.float32)
        for filenr, filename in enumerate(filenames):
            with open(filename, 'r') as f:
                monitor.info('Adding condition %d: %s' % (indx[filenr], filename))
                f = EDF.EDFReader()
                f.open(filename)

                # read all the data from the file
                for chanindx in range(nChannels[0]):
                    data[filenr][chanindx, :] = f.readSignal(chanindx)[0:min(nSamples)]
                    data[filenr, chanindx, :] = data[filenr, chanindx, :] - data[filenr, chanindx, :].mean(axis = 0)

                    if hpfreq:
                        monitor.debug('Applying highpassfilter at %.1f Hertz' % (hpfreq))
                        data[filenr, chanindx, :] = EEGsynth.butter_highpass_filter(data[filenr, chanindx, :], hpfreq, int(fSample[0]), filtorder)

                    if lpfreq:
                        monitor.debug('Applying lowpassfilter at %.1f Hertz' % (lpfreq))
                        data[filenr, chanindx, :] = EEGsynth.butter_lowpass_filter(data[filenr, chanindx, :], lpfreq, int(fSample[0]), filtorder)

                f.close()

    else:
        raise NotImplementedError('unsupported file format')

    # plot timecourses for debugging
    if patch.getint('general', 'debug') == 3:
        for filenr, filename in enumerate(filenames):
            fig = plt.figure(filenr+1)
            for chanindx in range(nChannels[0]):
                print('file nr. %d channel nr. %d' % (filenr, chanindx))
                plt.subplot(8, 1, chanindx+1)
                plt.plot(data[filenr][chanindx, :])
            plt.show()

    # calculate CSP
    filters = CSP(data[indx==0], data[indx==1])

    # plot CSP when debugging
    if patch.getint('general', 'debug') == 3:
        cmap = cm.coolwarm
        fig, axes = plt.subplots(1,2, figsize=(8,8))
        for i, ax in enumerate(axes.flat):
            im = ax.imshow(filters[i], norm=colors.CenteredNorm(0), cmap = cmap)
            # pc = ax.imshow(filters[i])
            # plt.colorbar(pc, ax=ax)
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.05)
            plt.colorbar(im, cax=cax)
            # pc = ax.pcolormesh(filters[i], norm=colors.CenteredNorm(), cmap=cmap)
            # fig.colorbar(pc, ax=ax2)
            ax.set_title('CSP %d' % i)
        plt.show()

    # only write first filter (only 2 state solution)
    prefix = 'csp'
    for icomp, comp in enumerate(filters[0]):
        for iweight, weight in enumerate(filters[0][icomp, :]):
            key = '{prefix}.{icomp}.{iweight}'.format(prefix=prefix, icomp=icomp+1, iweight=iweight+1)
            patch.setvalue(key, float(weight))
            monitor.debug(key + ' = ' + str(weight))

    # there should not be any local variables in this function, they should all be global
    if len(locals()):
        print('LOCALS: ' + ', '.join(locals().keys()))
props0 = dict(
    cmap='plasma',
    **props_base)  # The addition of vmin and vmax is same to "Normalize()"
props1 = dict(norm=cls.Normalize(vmin=-0.3, vmax=0.9),
              cmap='plasma',
              **props_base)
props2 = dict(norm=cls.LogNorm(vmin=0.01, vmax=1), cmap='plasma', **props_base)

bounds = np.arange(-0.2, 0.81, 0.2)
props3 = dict(norm=cls.BoundaryNorm(boundaries=bounds,
                                    ncolors=256,
                                    extend='both'),
              cmap='RdYlBu_r',
              **props_base)
#<--- Colormaps are composed of total 256 colors usually; contourf() is based on BoundaryNorm
props4 = dict(norm=cls.CenteredNorm(vcenter=0), cmap='RdYlBu_r', **props_base)
props5 = dict(norm=cls.TwoSlopeNorm(vmin=-0.3, vcenter=0, vmax=0.9),
              cmap='RdYlBu_r',
              **props_base)

nrow, ncol = 2, 3
for i, (tit, props) in enumerate(
        zip(panel_names, [eval('props' + str(num)) for num in range(6)])):
    ax1 = fig.add_subplot(nrow, ncol,
                          i + 1)  # subplot(# of rows, # of columns, indicater)
    pic1 = ax1.imshow(Z, **props)
    subtit = '({}) {}'.format(abc[i], panel_names[i])
    ax1.set_title(subtit, fontsize=12)
    ax1.tick_params(axis='both', which='major', labelsize=10)

    cb = draw_colorbar(ax1,
예제 #19
0
def make_pca_plot(pca_vecs,
                  fourier_feats,
                  det_edges,
                  r_edges,
                  n_rows=1,
                  n_cols=None,
                  fourier_size=16):
    """ Make an expansive plot showing the top 12 PCA components, and the value of each
        of them everywhere in (Δ, Rb) space.
    """
    print("Preparing Top-12 PCA visualization plot...")
    num_pca_comps = pca_vecs.shape[0]
    if n_cols is None:
        n_cols = int(np.ceil(num_pca_comps / n_rows))

    fig, axs = plt.subplots(2 * n_rows,
                            n_cols,
                            figsize=(7 * n_cols, 11 * n_rows),
                            gridspec_kw={
                                "wspace": 0.1,
                                "hspace": 0.4,
                                "top": 0.97,
                                "bottom": 0.05,
                                "left": 0.04,
                                "right": 0.97
                            })

    # Custom color map going from black to yellow
    cdict = {
        'red': [[0.0, 0.0, 0.0], [0.5, 1.0, 1.0], [0.6, 245 / 255, 245 / 255],
                [1.0, 132 / 255, 132 / 255]],
        'green': [[0.0, 0.0, 0.0], [0.5, 1.0, 1.0],
                  [0.6, 218 / 255, 218 / 255], [1.0, 130 / 255, 130 / 255]],
        'blue': [[0.0, 0.0, 0.0], [0.5, 1.0, 1.0], [0.6, 10 / 255, 10 / 255],
                 [1.0, 26 / 255, 26 / 255]]
    }
    newcmp = colors.LinearSegmentedColormap('ylblk', segmentdata=cdict, N=256)

    for i in range(num_pca_comps):
        row, col = divmod(i, n_cols)

        fourier_vec = pca_vecs[i]
        # Un-flatten back out into the [16 x 16] 2D fourier space
        fourier_vec = fourier_vec.reshape((fourier_size, fourier_size))
        # Add on the extra row/column to add 2π to k space
        fourier_vec = np.pad(fourier_vec, ((0, 1), (0, 1)), mode='wrap')

        # Add the top panel: The actual principal component in Fourier space
        im = axs[2 * row, col].imshow(fourier_vec,
                                      norm=colors.CenteredNorm(),
                                      cmap=newcmp,
                                      origin='lower')
        axs[2 * row, col].set_xlabel(r'$k_x$')
        axs[2 * row, col].set_ylabel(r'$k_y$')
        axs[2 * row, col].set_xticks(fourier_size *
                                     np.array([0, 1 / 4, 1 / 2, 3 / 4, 1]))
        axs[2 * row, col].set_yticks(fourier_size *
                                     np.array([0, 1 / 4, 1 / 2, 3 / 4, 1]))
        axs[2 * row, col].set_xticklabels(
            [r"$0$", r"$\pi/2$", r"$\pi$", r"$3\pi/2$", r"$2\pi$"])
        axs[2 * row, col].set_yticklabels(
            [r"$0$", r"$\pi/2$", r"$\pi$", r"$3\pi/2$", r"$2\pi$"])

        divider = make_axes_locatable(axs[2 * row, col])
        cax = divider.append_axes("top", size="5%", pad=0.05)
        cbar = plt.colorbar(im, cax=cax, orientation='horizontal')
        cbar.ax.tick_params(labelsize=18, direction='inout')
        cbar.ax.xaxis.set_ticks_position('top')
        axs[2 * row, col].text(fourier_size / 16, (7 * fourier_size) / 8,
                               "PC{}".format(i + 1),
                               fontweight='bold',
                               fontsize=30)

        # Add the bottom panel: The projection onto this component across (Δ, Rb) space
        m = axs[2 * row + 1, col].pcolormesh(det_edges,
                                             r_edges,
                                             fourier_feats[..., i],
                                             cmap='inferno')
        axs[2 * row + 1, col].set_xlabel(r'$\Delta / \Omega$')
        axs[2 * row + 1, col].set_xticks([-2, 0, 2, 4])
        axs[2 * row + 1, col].set_yticks([1, 1.2, 1.4, 1.6, 1.8, 2])
        if col == 0:
            axs[2 * row, col].set_ylabel(r"$k_y$")
            axs[2 * row + 1, col].set_ylabel(r'$R_b / a$')
        if col != 0:
            axs[2 * row + 1, col].set_yticklabels(["", "", "", "", "", ""])
        axs[2 * row + 1, col].tick_params(axis='both', direction='inout')

        divider = make_axes_locatable(axs[2 * row + 1, col])
        cax = divider.append_axes("top", size="5%", pad=0.05)
        cbar = plt.colorbar(m, cax=cax, orientation='horizontal')
        cbar.ax.tick_params(labelsize=18, direction='inout')
        cbar.ax.xaxis.set_ticks_position('top')

    plt.show()