Example #1
0
def plot_figs():
    pylab.subplot(221, aspect="equal")
    X, Y = pylab.meshgrid(list(range(ins.num_atoms)), list(range(ins.num_atoms)))
    pylab.pcolor(X, Y, ins.norm_cross_correlation)
    pylab.colorbar()
    pylab.clim(-0.15, 0.15)
    pylab.title("Cross Correlations")

    pylab.subplot(222)
    pylab.plot(pdb_Bfactors, "bo-", label="ex.")
    pylab.plot(ins.Bfactors, "ro-", label="calc.")
    pylab.legend()
    pylab.xlabel("Residue")
#    pylab.ylabel("a.u.")
    pylab.title("B factors")
    pylab.grid()

    pylab.subplot(223, aspect="equal")
    X, Y = pylab.meshgrid(list(range(ins.num_atoms)), list(range(ins.num_atoms)))
    pylab.pcolor(X, Y, ins.adj_mat)
    pylab.colorbar()
    pylab.title("Adjacency Mat.")

    pylab.subplot(224)
    pylab.plot(ins.graph_eigvec[:, 1], "go-")
    pylab.xlabel("Residue")
    pylab.grid()

    pylab.show()
Example #2
0
def main():
    zf = np.vectorize(z_function)
    find_extremum(1)
    x, y = np.arange(0.1, 7.0, 0.1), np.arange(0.1, 7.0, 0.1)
    X, Y = pl.meshgrid(x, y)
    Z = zf(X, Y, 1)
    im = pl.imshow(Z, cmap=pl.cm.RdBu)
    cset = pl.contour(Z, np.arange(21, 100, 10), linewidths=2, cmap=pl.cm.Set2)

    pl.clabel(cset, inline=True, fmt='%1.1f', fontsize=15)
    pl.colorbar(im)
    pl.title('z = x*y + 50/x + 20/y')
    pl.show()

    print()

    find_extremum(2)
    x, y = np.arange(0.1, 5.0, 0.1), np.arange(0.1, 5.0, 0.1)
    X, Y = pl.meshgrid(x, y)
    Z = zf(X, Y, 2)
    im = pl.imshow(Z, cmap=pl.cm.RdBu)
    cset = pl.contour(Z, np.arange(-10, 0, 1), linewidths=3, cmap=pl.cm.Set2)
    pl.clabel(cset, inline=True, fmt='%1.1f', fontsize=10)
    pl.colorbar(im)
    pl.title('z = x^2 + y^2 - 2*log(x) - 18*log(y)')
    pl.show()
    print()
    find_extremum(3)
Example #3
0
def main():
    # Create the grid
    x = arange(-100, 101)
    y = arange(-100, 101)

    # Create the meshgrid
    Y, X = meshgrid(x, y)
    A = 1
    B = 2
    V = 6*pi / 201
    W = 4*pi / 201
    F = A*sin(V*X) + B*cos(W*Y)
    Fx = V*A*cos(V*X)
    Fy = W*B*-sin(W*Y)

    # Show the images
    show_image(F)
    show_image(Fx)
    show_image(Fy)

    # Create the grid for the quivers
    xs = arange(-100, 101, 10)
    ys = arange(-100, 101, 10)

    # Here we determine the direction of the quivers
    Ys, Xs = meshgrid(ys, xs)
    FFx = V*A*cos(V*Xs)
    FFy = W*B*-sin(W*Ys)

    # Draw the quivers and the image
    clf()
    imshow(F, cmap=cm.gray, extent=(-100, 100, -100, 100))
    quiver(ys, xs, -FFy, FFx, color='red')
    show()
def computeKOPgrid():
    #compute KOP grid
    KOPgrid = pb.zeros((len(noise2),len(noise3),len(x0s)))
    i,j,k=0,0,0
    for i in range(len(noise2)):
        for j in range(len(noise3)):
            for k in range(len(x0s)):
                radical="_%i_HMR_%i_ML_CpES1_100_CpES2_100_x0_%i_noise3_%i_noise2_%i_noise1_%i_15s" %(nbn1, nbn2, int(x0s[k]*10), int(noise3[j]), int(noise2[i]*100),  int(noise2[i]*200),)
                KOP1 = np.load('traces_may22/KOP1'+radical+".npy")
                KOP2 = np.load('traces_may22/KOP2'+radical+".npy")
                KOPgrid[i,j,k] = KOP1[0,:].mean() + KOP2[0,:].mean()
    
    kopmin = KOPgrid.min()
    kopmax = KOPgrid.max()
    print KOPgrid
    #plot
    fig = pb.figure()
    ax = fig.add_subplot(311, projection='3d')
    #k=0 
    X,Y = pb.meshgrid(noise2,noise3)
    for k in range(len(x0s)):
        #img = ax.contourf(KOPgrid[:,:,k], vmin=kopmin, vmax=kopmax), offset=x0s[k])
        img = ax.contourf(X, Y, KOPgrid[:,:,k].T, zdir='z', levels=pb.linspace(kopmin, kopmax, 50), vmin=kopmin, vmax=kopmax, offset=x0s[k])
        #cbar = pb.colorbar(img)
        #fig.savefig("param3Dspace_CpES1_%i_CpES2_%i_x0_%i.png" %(int(CpES1s[i]*100), int(CpES2s[j]*100), int(x0s[k]*10)))
    ax.set_xlabel("noise2")
    ax.set_xticks(pb.linspace(min(noise2),max(noise2),5))
    ax.set_ylabel("noise3")
    ax.set_yticks(pb.linspace(min(noise3),max(noise3),5))
    ax.set_zlabel("x0")
    ax.set_zticks(pb.linspace(min(x0s),max(x0s),5))
    ax.set_zlim(min(x0s), max(x0s))
    
    ax2=fig.add_subplot(312)
    index_noise3=0;
    X2,Y2=pb.meshgrid(x0s, noise2)
    img2 = ax2.contourf(X2, Y2,KOPgrid[:,index_noise3,:],levels=pb.linspace(kopmin, kopmax, 50), vmin=kopmin, vmax=kopmax)
#    img = ax2.imshow(KOPgrid[index_noise2,:,:].T, interpolation="nearest", origin="lower")
    ax2.set_xlabel("|x0|")
    ax2.set_ylabel("noise_1_2")
    cbar=pb.colorbar(img2)
    
    noiseGrid=pb.zeros((len(noise2),len(x0s)))
    for n in range(len(noise2)):
        noiseGrid[n,:] = KOPgrid[n,0,:]
    ngmin=noiseGrid.min()
    ngmax=noiseGrid.max()
    
    ax3=fig.add_subplot(313)
    X3,Y3=pb.meshgrid(x0s, range(len(noise2)))
    img3 = ax3.contourf(X3, Y3, noiseGrid, levels=pb.linspace(ngmin, ngmax, 50), vmin=ngmin, vmax=ngmax)
    #img2 = ax3.imshow(noiseGrid.T, interpolation="nearest", origin="lower")
    cbar2=pb.colorbar(img3)
    ax3.set_xlabel("|x0|")
    ax3.set_ylabel("noise_1_2_3")
    
    print noiseGrid.T
    
    pb.show()
Example #5
0
    def boundary_layer(self): 
        self.dpi3 = 102
        self.fig2 = Figure((3.0, 3.0), dpi=self.dpi3)
        self.axes3 = self.fig2.add_subplot(111)
        self.axes3.set_axis_bgcolor('white')
        self.x = arange(0,10,.5)
        self.y = arange(0,10,.5) 
        self.X, self.Y = pylab.meshgrid(self.x,self.y)
        self.Z, self.Zt = pylab.meshgrid(self.x,self.y)

        if not self.update:
            self.axes3.contourf(self.X,self.Y,self.Z)
Example #6
0
    def __init__( self, t, x, y, A=[1., 0.85], a=[0.25, 0.85] ):
        '''
        
        Initializing generalized thalamo-cortical loop. Full
        functionality is only obtained in the subclasses, like DOG,
        full_eDOG, etc.
        
        Parameters
        ----------
        
        t : array
            1D Time vector
        x : np.array
            1D vector for x-axis sampling points
        y : np.array
            1D vector for y-axis sampling points

        Keyword arguments
        -----------------
        
        A : sequence (default A = [1., 0.85])
            Amplitudes for DOG receptive field for center and surround, 
            respectively
        a : sequence (default a = [0.25, 0.85])
            Width parameter for DOG receptive field for center and surround,
            respectively

        Usage
        -----
            Look at subclasses for example usage            
        '''
        # Set parameteres as attributes
        self.name = 'pyDOG Toolbox'
        self.t = t
        self.A = A
        self.a = a
        self.x = x
        self.y = y
        # Find sampling rates and sampling freqs and 
        self.nu_xs = 1./(x[1]-x[0])
        self.nu_ys = 1./(y[1]-y[0])
        self.fs = 1./(t[1]-t[0])
        self.f = fft.fftfreq(pl.asarray(t).size, t[1]-t[0])
        # fftshift spatial frequency,
        self.nu_x = fft.fftfreq(pl.asarray(x).size, x[1]-x[0])
        self.nu_y = fft.fftfreq(pl.asarray(y).size, y[1]-y[0])
        # Make meshgrids, may come in handy
        self._xx, self._yy = pl.meshgrid(self.x, self.y)
        self._nu_xx, self._nu_yy = pl.meshgrid(self.nu_x, self.nu_y)
        # r is needed for all circular rfs
        self.r = pl.sqrt(self._xx**2 + self._yy**2)
        self.k = 2 * pl.pi * pl.sqrt(self._nu_xx**2 + self._nu_yy**2)
Example #7
0
def resize_ncollev(lat, lon, lev):
    """
    For 3d variables (ie including a height coordinate) with a ncol dim instead of separate
    lat/lon dims (i.e. for native rather than regridded data), this function makes lat and lon
    be copied over the vertical dimension so they have the same size as var.
    """
    if np.isscalar(lev) or len(lev.shape) != 2:
        raise Exception('resize_ncollev only works with 2 dim lev array')

    junk, LAT = pl.meshgrid(lev[:, 0], lat)
    junk, LON = pl.meshgrid(lev[:, 0], lon)

    return LAT, LON
Example #8
0
    def init_contour(self):
        self.data2 = []
        self.x = arange(0,10,.5)
        self.y = arange(0,10,.5) 
        self.X, self.Y = pylab.meshgrid(self.x,self.y)
        self.Z, self.Zt = pylab.meshgrid(self.x,self.y)
        self.dpi2 = 101
        self.fig1 = Figure((3.0, 3.0), dpi=self.dpi2)
        self.axes2 = self.fig1.add_subplot(111)
        self.axes2.set_axis_bgcolor('white')

        if not self.update:
            initplot = self.plot_data2 = self.axes2.contourf(self.X,self.Y,self.Z)
            self.cb = self.fig1.colorbar(initplot)
Example #9
0
    def vecPlot(self, row, col, mWx, mWy, frmSize, winSize):
        pl.clf()
        pl.ion()

        #pWy = mWy[row][col]
        #まずはx方向のWx
        pWx = mWx[row,col:(frmSize-winSize+1)+row,0,:]
        #print "pWx sum:",np.sum(pWx[0,:])
        print np.mean(pWx*pWx, axis=0)
        pWx = np.sqrt(pWx * pWx)
        r,c = pWx.shape
        x = pl.arange(c+1)
        y = pl.arange(r+1)
        X, Y = pl.meshgrid(x, y)

        pl.subplot2grid((2,2),(0,0))
        pl.pcolor(X, Y, pWx)
        pl.xlim(0,c)
        pl.ylim(0,r)
        pl.colorbar()
        pl.title("user_1 (t:"+str(row)+")")
        pl.gray()

        #いまだけ
        pWy = mWy[row,col:(frmSize-winSize+1)+row,0,:]
        #print "pWy sum:",np.sum(pWy[0,:],axis=1)
        #print np.sum(pWy*pWy,axis=1)
        #print np.mean(pWy*pWy, axis=0)
        pWy = np.sqrt(pWy * pWy)
        r,c = pWx.shape
        x = pl.arange(c+1)
        y = pl.arange(r+1)
        X, Y = pl.meshgrid(x, y)

        pl.subplot2grid((2,2),(0,1))
        pl.pcolor(X, Y, pWy)    
        pl.xlim(0,c)
        pl.ylim(0,r)
        pl.colorbar()
        pl.title("user_2 (t:"+str(col)+")")
        pl.gray()

        pl.subplot2grid((2,2),(1,0),colspan=2)
        pl.plot(np.mean(pWx*pWx, axis=0),color="r")
        pl.plot(np.mean(pWy*pWy, axis=0),color="b")

        pl.draw()

        print "pWx shape:",pWx.shape
Example #10
0
    def updateColorTable(self, cItem):
        print "now viz!"+str(cItem.row())+","+str(cItem.column())

        row = cItem.row()
        col = cItem.column()

        pl.clf()
        #pl.ion()
        x = pl.arange(self.dataDimen+1)
        y = pl.arange(self.dataDimen+1)
        X, Y = pl.meshgrid(x, y)
        pl.subplot(1,2,1)
        pl.pcolor(X, Y, self.mWx[row*self.dataMaxRange+col])
        pl.gca().set_aspect('equal')
        pl.colorbar()
        pl.gray()
        pl.title("user 1")

        pl.subplot(1,2,2)
        pl.pcolor(X, Y, self.mWy[row*self.dataMaxRange+col])
        pl.gca().set_aspect('equal')
        pl.colorbar()
        pl.gray()
        pl.title("user 2")
        #pl.tight_layout()

        pl.draw()
        #pl.show()
        pl.show(block=False) 
Example #11
0
def plot_layered_images(fig):
    def func3(x,y):
        return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2)

    # make these smaller to increase the resolution
    dx, dy = 0.05, 0.05

    x = arange(-3.0, 3.0, dx)
    y = arange(-3.0, 3.0, dy)
    X,Y = meshgrid(x, y)

    # when layering multiple images, the images need to have the same
    # extent.  This does not mean they need to have the same shape, but
    # they both need to render to the same coordinate system determined by
    # xmin, xmax, ymin, ymax

    xmin, xmax, ymin, ymax = min(x), max(x), min(y), max(y)
    extent = xmin, xmax, ymin, ymax
    Z1 = array(([0,1]*4 + [1,0]*4)*4); Z1.shape = 8,8  # chessboard
    Z2 = func3(X, Y)

    axes = fig.gca()
    axes.imshow(Z1, cmap=cm.gray, interpolation='nearest',
                 extent=extent)
    axes.hold(True)
    axes.imshow(Z2, cmap=cm.jet, alpha=.9, interpolation='bilinear',
                 extent=extent)
Example #12
0
    def projectOnFinerGrid_f29(self, Xc, Yc, q):
        dx = Xc[1] - Xc[0]
        dy = Yc[1] - Yc[0]
        nx = Xc.shape[0]
        ny = Yc.shape[0]

        # mesh coordinates
        Xn = pylab.linspace(Xc[0] - 0.5 * dx, Xc[-1] + 0.5 * dx,
                            3 * nx + 1)  # one more
        Yn = pylab.linspace(Yc[0] - 0.5 * dy, Yc[-1] + 0.5 * dy,
                            3 * ny + 1)  # one more
        XXn, YYn = pylab.meshgrid(Xn, Yn)

        # data
        qn = pylab.zeros((3 * Xc.shape[0], 3 * Yc.shape[0]), float)

        v1 = q[:, :, 0]
        v2 = q[:, :, 1]
        v3 = q[:, :, 2]
        v4 = q[:, :, 3]

        vList = [v1, v2, v3, v4]

        # node 1
        c1 = [25.0 / 36.0, 5.0 / 36.0, 1.0 / 36.0, 5.0 / 36.0]
        qn[0:3 * nx:3, 0:3 * ny:3] = self.evalSum(c1, vList)

        # node 2
        c2 = [5.0 / 12.0, 5.0 / 12.0, 1.0 / 12.0, 1.0 / 12.0]
        qn[1:3 * nx:3, 0:3 * ny:3] = self.evalSum(c2, vList)

        # node 3
        c3 = [5.0 / 36.0, 25.0 / 36.0, 5.0 / 36.0, 1.0 / 36.0]
        qn[2:3 * nx:3, 0:3 * ny:3] = self.evalSum(c3, vList)

        # node 4
        c4 = [5.0 / 12.0, 1.0 / 12.0, 1.0 / 12.0, 5.0 / 12.0]
        qn[0:3 * nx:3, 1:3 * ny:3] = self.evalSum(c4, vList)

        # node 5
        c5 = [1.0 / 4.0, 1.0 / 4.0, 1.0 / 4.0, 1.0 / 4.0]
        qn[1:3 * nx:3, 1:3 * ny:3] = self.evalSum(c5, vList)

        # node 6
        c6 = [1.0 / 12.0, 5.0 / 12.0, 5.0 / 12.0, 1.0 / 12.0]
        qn[2:3 * nx:3, 1:3 * ny:3] = self.evalSum(c6, vList)

        # node 7
        c7 = [5.0 / 36.0, 1.0 / 36.0, 5.0 / 36.0, 25.0 / 36.0]
        qn[0:3 * nx:3, 2:3 * ny:3] = self.evalSum(c7, vList)

        # node 8
        c8 = [1.0 / 12.0, 1.0 / 12.0, 5.0 / 12.0, 5.0 / 12.0]
        qn[1:3 * nx:3, 2:3 * ny:3] = self.evalSum(c8, vList)

        # node 9
        c9 = [1.0 / 36.0, 5.0 / 36.0, 25.0 / 36.0, 5.0 / 36.0]
        qn[2:3 * nx:3, 2:3 * ny:3] = self.evalSum(c9, vList)

        return XXn, YYn, qn
Example #13
0
File: run.py Project: yusme/DDPG
def plot_function_countur3D(min, max, action, episode):
    x = np.arange(min, max, 0.025)
    y = np.arange(min, max, 0.025)
    # meshgrid create a matrix von min to max with 0.1 as distance
    # the output is 2 matrix where one is the transport of the other one
    X, Y = pyl.meshgrid(x, y)
    #Z=z_function(X,np.transpose(X))
    Z = action
    print Y
    #==========
    #  3D
    #==========
    fig = plt.figure()
    #plt.ion()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(Y,
                           X,
                           Z,
                           rstride=1,
                           cstride=1,
                           cmap=plt.cm.RdBu,
                           linewidth=0,
                           antialiased=False)
    ax.set_xlim([min, max])
    ax.set_ylim([min, max])
    ax.zaxis.set_major_locator(plt.LinearLocator(3))
    ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.02f'))
    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.show(False)
    plt.draw()
    name_file = 'exp/episode3D' + str(episode) + '.png'
    print name_file.__str__()
    plt.savefig(name_file.__str__())
    plt.close()
Example #14
0
def plot_wt_layout(wt_layout, borders=None, depth=None):
    fig = plt.figure(figsize=(6, 6), dpi=2000)
    fs = 14
    ax = plt.subplot(111)

    if depth is not None:
        N = 100
        X, Y = plt.meshgrid(
            plt.linspace(depth[:, 0].min(), depth[:, 0].max(), N),
            plt.linspace(depth[:, 1].min(), depth[:, 1].max(), N))
        Z = plt.griddata(depth[:, 0],
                         depth[:, 1],
                         depth[:, 2],
                         X,
                         Y,
                         interp='linear')
        plt.contourf(X, Y, Z, label='depth [m]')
        plt.colorbar().set_label('water depth [m]')
    #ax.plot(wt_layout.wt_positions[:,0], wt_layout.wt_positions[:,1], 'or', label='baseline position')

    ax.scatter(wt_layout.wt_positions[:, 0],
               wt_layout.wt_positions[:, 1],
               wt_layout._wt_list('rotor_diameter'),
               label='baseline position')

    if borders is not None:
        ax.plot(borders[:, 0], borders[:, 1], 'r--', label='border')

    ax.set_xlabel('x [m]')
    ax.set_ylabel('y [m]')
    ax.axis('equal')
    ax.legend(loc='lower left')
Example #15
0
def exactSol(a, b, X, Y):
    c1, d0 = 0, 0
    c0 = a/12.0 - 1.0/2.0
    d1 = b/12.0 - 1.0/2.0

    XX, YY = pylab.meshgrid(X, Y)
    return (XX**2/2 - a*XX**4/12 + c0*XX + c1)*(YY**2/2 - b*YY**4/12 + d0*YY + d1)
Example #16
0
def plot_variance(plot, head, num_classes):
    # make these smaller to increase the resolution
    x = np.arange(0.0, 1.05, 0.05)
    x_1, x_2 = np.array(meshgrid(x, x))
    grid = np.stack((x_1, x_2))
    grid = grid.T.reshape(-1, 2)
    num_samples = 50
    outs = []
    for i in range(num_samples):
        outs.append(head.predict(grid))
    outs = np.array(outs)
    stds = np.mean(np.std(outs, axis=0), axis=-1)

    # vgp = head.layers[0]
    # outs = tf.nn.softmax(vgp(grid).sample(100))
    # stds = np.mean(np.std(outs, axis=0), axis=-1)

    std_plot = stds.reshape(x.shape[0], x.shape[0])
    plot.contourf(x, x, std_plot, cmap='Greys', vmin=0.0, vmax=0.3,
                  alpha=0.7)  #  norm=Normalize(),
    thresholds = [0.9, 1.1]
    colours = [
        'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple',
        'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'
    ]
    for class_id in range(num_classes):
        class_pred = np.mean(outs, axis=0)[:, class_id]
        class_pred = class_pred.reshape(x.shape[0], x.shape[0])
        plot.contourf(x,
                      x,
                      class_pred,
                      colors=[colours[class_id]],
                      levels=thresholds,
                      alpha=0.2)
    def _plot_bar3d(self):
        logging.debug('')
        if self.dimension > 0:
            return
        array = self._data_to_array()

        # width, depth, and height of the bars (array == height values == dz)
        dx = list(numpy.array([1.0/len(array[0]) for x in range(0, array.shape[1])]))
        dy = list(numpy.array([1.0/len(array) for x in range(0, array.shape[0])]))
        dx *= len(array)
        dy *= len(array[0])
        dz = array.flatten()+0.00000001 # dirty hack to cirumvent ValueError

        # x,y,z position of each bar
        x = pylab.linspace(0.0, 1.0, len(array[0]), endpoint=False)
        y = pylab.linspace(0.0, 1.0, len(array), endpoint=False)
        xpos, ypos = pylab.meshgrid(x, y)
        xpos = xpos.flatten()
        ypos = ypos.flatten()
        zpos = numpy.zeros(array.shape).flatten()

        fig = MyFig(self.options, xlabel='Probability p', ylabel='Fraction of Nodes', zlabel='Fraction of Executions', ThreeD=True)
        fig.ax.set_zlim3d(0.0, 1.01)
        fig.ax.set_xlim3d(0.0, 1.01)
        fig.ax.set_ylim3d(0.0, 1.01)
        fig.ax.set_autoscale_on(False)

        assert(len(dx) == len(dy) == len(array.flatten()) == len(xpos) == len(ypos) == len(zpos))
        fig.ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=['#CCBBDD'])
        try:
            self.figures['bar3d'] = fig.save('bar3d' + str(self.data_filter))
        except ValueError, err:
            logging.warning('%s', err)
Example #18
0
    def fresnelConvolutionTransform(self, d):
        # make intensity distribution
        i2 = Intensity2D(self.nx, self.startx, self.endx, self.ny, self.starty,
                         self.endy, self.wl)

        # FT on inital distribution
        u1ft = pl.fft2(self.i)

        # 2d convolution kernel
        k = 2 * pl.pi / i2.wl

        # make spatial frequency matrix
        maxsfx = 2 * pl.pi / self.dx
        maxsfy = 2 * pl.pi / self.dy

        dsfx = 2 * maxsfx / (self.nx)
        dsfy = 2 * maxsfy / (self.ny)

        self.sfx = pl.arange(-maxsfx / 2, maxsfx / 2 + 1e-15, dsfx / 2)
        self.sfy = pl.arange(-maxsfy / 2, maxsfy / 2 + 1e-15, dsfy / 2)

        [self.sfxgrid,
         self.sfygrid] = pl.fftshift(pl.meshgrid(self.sfx, self.sfy))

        # make convolution kernel
        kern = pl.exp(1j * d * (self.sfxgrid**2 + self.sfygrid**2) / (2 * k))

        # apply convolution kernel and invert
        i2.i = pl.ifft2(kern * u1ft)

        return i2
Example #19
0
    def fresnelConvolutionTransform(self,d) :
        # make intensity distribution
        i2 = Intensity2D(self.nx,self.startx,self.endx,
                         self.ny,self.starty,self.endy,
                         self.wl)       

        # FT on inital distribution 
        u1ft = pl.fft2(self.i)

        # 2d convolution kernel
        k = 2*pl.pi/i2.wl
        
        # make spatial frequency matrix
        maxsfx = 2*pl.pi/self.dx
        maxsfy = 2*pl.pi/self.dy
        
        dsfx = 2*maxsfx/(self.nx)
        dsfy = 2*maxsfy/(self.ny)
        
        self.sfx = pl.arange(-maxsfx/2,maxsfx/2+1e-15,dsfx/2)
        self.sfy = pl.arange(-maxsfy/2,maxsfy/2+1e-15,dsfy/2)

        [self.sfxgrid, self.sfygrid] = pl.fftshift(pl.meshgrid(self.sfx,self.sfy))
                
        # make convolution kernel 
        kern = pl.exp(1j*d*(self.sfxgrid**2+self.sfygrid**2)/(2*k))
        
        # apply convolution kernel and invert
        i2.i = pl.ifft2(kern*u1ft) 

        return i2
Example #20
0
def main():

    nx = floor(roh[0]/(box[1]/N))
    ny = floor(roh[1]/(box[1]/N))
   # print nx, ny
    field=zeros([N,N])
    #field[nx][ny] = 1./(dx*dx)
    field[nx+9][ny+9] = 1./(dx*dx)
    field[nx-9][ny-9] = 1./(dx*dx)
    field[nx-9][ny+9] = 1./(dx*dx)
    field[nx+9][ny-9] = 1./(dx*dx)
    #plot the initial field;
    initFig=p.figure()
    gx,gy=p.meshgrid(gridpnts,gridpnts)
    ax = p3.Axes3D(initFig)
    ax.scatter3D(ravel(gy),ravel(gx),ravel(field))
    ax.set_xlabel('$x$')
    ax.set_ylabel('$y$')
    ax.set_zlabel('$\psi(x,y)$')
    plt.savefig("ROHxySP3.png")
    
    
    
    jacobi(field)
    gauss_seidel(field)
Example #21
0
def gaussian2d(data, nxw, nyw=None, sxw=1 / 3., syw=1 / 3., rmax=3., **kwargs):
    """Gaussian 2D filter

    - **data**: Data array
    - **nxw**: Size of gaussian weights array along X (and Y if nyw not given)
    - *nyw*: Size of gaussian weights array along Y [default: nxw]
    - *sxw*: Standard deviation of the gaussian distribution along X.
      If <1, its size is relative to nxw. If > 1, it is directly expressed in grid
      steps.
    - *syw*: Same as sxw for Y direction.
    - *rmax*: Distance relative to sqrt(sxw**2+syw**2) after with weights are
      nullified.
    - Other keywords are passed to :func:`generic2d`
    """
    if nyw is None: nyw = nxw
    assert nxw % 2 == 1 and nyw % 2 == 1, 'nxw and nyw must be odd numbers'
    assert sxw > 0 and syw > 0, 'sxw and syw must be positive'

    xx, yy = meshgrid(N.arange(nxw) - nxw / 2, N.arange(nyw) - nxw / 2)

    if sxw < 1:
        sxw *= nxw / 2
    if syw < 1:
        syw *= nyw / 2

    weights = N.exp(-(xx**2 / sxw**2 + yy**2 / syw**2))

    weights[weights < N.exp(-rmax**2)] = 0.

    return generic2d(data, weights, **kwargs)
Example #22
0
    def init(self, img, box):
        img_now = ops.read_image(img)
        self.target_sz = np.array([box[3], box[2]])
        self.pos = np.array([box[1], box[0]]) + self.target_sz / 2
        # print(self.pos)
        # ground_truth =

        # window size, taking padding into account
        self.sz = pylab.floor(self.target_sz * (1 + self.padding))

        # desired output (gaussian shaped), bandwidth proportional to target size
        self.output_sigma = pylab.sqrt(pylab.prod(
            self.target_sz)) * self.output_sigma_factor

        grid_y = pylab.arange(self.sz[0]) - pylab.floor(self.sz[0] / 2)
        grid_x = pylab.arange(self.sz[1]) - pylab.floor(self.sz[1] / 2)
        #[rs, cs] = ndgrid(grid_x, grid_y)
        rs, cs = pylab.meshgrid(grid_x, grid_y)
        y = pylab.exp(-0.5 / self.output_sigma**2 * (rs**2 + cs**2))
        self.yf = pylab.fft2(y)
        # print(self.yf)
        #print("yf.shape ==", yf.shape)
        #print("y.shape ==", y.shape)

        # store pre-computed cosine window
        self.cos_window = pylab.outer(pylab.hanning(self.sz[0]),
                                      pylab.hanning(self.sz[1]))
        if img_now.ndim == 3:
            img_now = ops.rgb2gray(img_now)
        x = ops.get_subwindow(img_now, self.pos, self.sz, self.cos_window)
        k = ops.dense_gauss_kernel(self.sigma, x)
        self.alphaf = pylab.divide(
            self.yf, (pylab.fft2(k) + self.lambda_value))  # Eq. 7
        self.z = x
def demo1():
    theta = RiemannTheta_Function()
    Omega = np.array([[1.j, .5], [.5, 1.j]])
    print
    print "Calculating 3,600 points of the Riemann Theta Function in C..."
    print
    print "Omega = [i   .5]"
    print "        [.5   i]"
    print 
    print "z = (x + iy, 0) where (0 < x < 1) and (0 < y < 5)"
    SIZE = 60
    x = np.linspace(0,1,SIZE)
    y = np.linspace(0,5,SIZE)
    X,Y = p.meshgrid(x,y)
    Z = X + Y*1.0j
    Z = Z.flatten()
    start = time.clock()
    U,V = theta.exp_and_osc_at_point([[z,0] for z in Z], Omega, gpu=False, batch=True)
    done = time.clock() - start
    print "Time to perform the calculation: " + str(done)
    print
    Z = (V.reshape(60,60)).imag
    print "\Plotting the imaginary part of the function..."
    plt.contourf(X,Y,Z,7,antialiased=True)
    plt.show()
def demo3():
    theta = RiemannTheta_Function()
    Omega = np.array([[1.j, .5], [.5, 1.j]])
    print
    print "Calculating 1,000,000 points of the Riemann Theta Function on GPU..."
    print
    print "Omega = [i   .5]"
    print "        [.5   i]"
    print 
    print "z = (x + iy, 0) where (0 < x < 1) and (0 < y < 5)"
    SIZE = 1000
    x = np.linspace(0,1,SIZE)
    y = np.linspace(0,5,SIZE)
    X,Y = p.meshgrid(x,y)
    Z = X + Y*1.0j
    Z = Z.flatten()
    Z = [[z,0] for z in Z]
    print "Starting computation on the GPU"
    start = time.clock()
    U,V = theta.exp_and_osc_at_point(Z, Omega, batch=True)
    done = time.clock() - start
    print "Time to perform the calculation: " + str(done)
    print
    print "Starting computation on the CPU"
    start = time.clock()
    U,V = theta.exp_and_osc_at_point(Z, Omega, batch=True, gpu=False)
    done = time.clock() - start
    print "Time to perform the calculation: " + str(done)
    print
Example #25
0
def dist2(x):
    R, GSIGMAS = pylab.meshgrid(r[r < fit_rcutoff], gsigmas)
    g = pylab.zeros_like(GSIGMAS)
    g = evalg(x, GSIGMAS, R)
    gfit = pylab.reshape(g, len(eta) * len(r[r < fit_rcutoff]))
    return gfit - pylab.reshape([g[r < fit_rcutoff] for g in ghs],
                                len(gsigmas) * len(r[r < fit_rcutoff]))
Example #26
0
def showSF( N, label = '' ):
    fig = P.figure()
    ax1 = fig.add_subplot(1, 2, 1, projection='3d')
    ax2 = fig.add_subplot(1, 2, 2)
    
    Nx = 21
    Ny = 21
    nLevels = 12

    tix = P.linspace( 0.0, 1.0, Nx )
    tiy = P.linspace( 0.0, 1.0, Ny )
    (X,Y) = P.meshgrid( tix, tiy )
    z = g.RVector( len( X.flat ) )
    
    for i, x in enumerate( X.flat ):
        p = g.RVector3( X.flat[ i ], Y.flat[ i ] )
        z[ i ] = N(p)
    
    Z = P.ma.masked_where( z == -99., z )
    Z = Z.reshape( Ny, Nx )
    
    ax2.contourf( X, Y, Z )
    ax2.set_aspect( 'equal' )
    surf = ax1.plot_surface( X, Y, Z, rstride = 1, cstride = 1, cmap=P.cm.jet,linewidth=0 )
    
    ax2.set_title( label + N.__str__() )
    fig.colorbar( surf )
Example #27
0
def plot_risk():
    """
        plot a two dimensional slack surface
    """
    mua, vra, pra = pgen.get_pdf(plot=False, write=False)
    deadline = ptsl.D

    a1 = range(1, 17)
    a2 = range(1, 17)
    shape = (len(a1), len(a2))
    X, Y = meshgrid(a1, a2)
    Z1 = np.full(shape, -1.0)  # Risk Power Surface
    Z2 = np.full(shape, -1.0)  # Peak Power Surface

    for x in a1:
        for y in a2:
            mu = mua[x - 1] + mua[y - 1]
            vr = vra[x - 1] + vra[y - 1]

            dist = stats.norm(loc=mu, scale=np.sqrt(vr))
            risk = dist.sf(deadline)

            Z1[x - 1, y - 1] = risk
            Z2[x - 1, y - 1] = np.max([pra[x - 1], pra[y - 1]])

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(X,
                           Y,
                           Z1,
                           rstride=1,
                           cstride=1,
                           cmap=cm.Greys,
                           linewidth=0,
                           antialiased=False)
    ax.set_xlabel("alloc ph1")
    ax.set_ylabel("alloc ph2")
    ax.set_zlabel("Risk")
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.savefig("risk-surface.pdf", bbox_inches='tight')
    plt.close()

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(X,
                           Y,
                           Z2,
                           rstride=1,
                           cstride=1,
                           cmap=cm.Greys_r,
                           linewidth=0,
                           antialiased=False)
    ax.set_xlabel("alloc ph1")
    ax.set_ylabel("alloc ph2")
    ax.set_zlabel("peak power")
    # print(ax.azim)
    ax.view_init(azim=-30)
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.savefig("pkp-surface.pdf", bbox_inches='tight')
    plt.close()
    def graph_func(self):

        plt.style.use('seaborn-paper')
        x = arange(-3.0, 3.0, 0.1)
        y = arange(-3.0, 3.0, 0.1)
        X, Y = meshgrid(x, y)  # grid of point
        Z = self.function(X, Y)  # evaluation of the function on the grid
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        surf = ax.plot_surface(X,
                               Y,
                               Z,
                               rstride=1,
                               cstride=1,
                               cmap=cm.RdBu,
                               linewidth=0,
                               antialiased=False)

        ax.zaxis.set_major_locator(LinearLocator(10))
        ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
        fig.colorbar(surf, shrink=0.5, aspect=5)
        title('$z=3x^2 - 3xy + 4y^2 - 2x + y $')
        plt.xlabel("X")
        plt.ylabel("Y")
        plt.show()
Example #29
0
    def plot_ppi(self,index):
        data = self.ppis[index]
        fig = pylab.figure()
            
        ax = pylab.axes(axisbg = 'k', polar=True)
        
        chan    = self.channels[self.ppis_header[index].Description.channel]
        start_range = chan.cell_lenght/2.
        stop_range  = start_range + chan.cell_lenght*chan.number_of_cells
        
        ranges = pylab.linspace(start_range, stop_range, chan.number_of_cells)
        
        start_ang   = self.ppis_header[index].Description.start_az
        stop_ang    = self.ppis_header[index].Description.finish_az
        
        angles = pylab.linspace(start_ang, stop_ang, 
                            self.ppis_header[index].Description.sectorCount)
        
        rad, theta = pylab.meshgrid(ranges/1000., (90-angles)*pylab.pi/180)
        X = theta
        Y = rad 

        ax.pcolormesh(X, Y, data)
        pylab.title('pulse: %s, elev: %.2f, unit: %s' % (chan.pulse, 
                        self.ppis_header[index].Description.angle,
                        self.ppis_header[index].Description.meassurement))
        pylab.savefig('../ppis/ppi_%i.png' % index)
Example #30
0
def dist2(x):
  R, ETA = pylab.meshgrid(r[r<fit_rcutoff], eta)
  g = pylab.zeros_like(ETA)
  g = evalg(x, ETA, R)
  gfit = pylab.reshape(g, len(eta)*len(r[r<fit_rcutoff]))
  return gfit - pylab.reshape([g[r<fit_rcutoff] for g in ghs],
                              len(eta)*len(r[r<fit_rcutoff]))
Example #31
0
def dist2(x):
  R, ETA = pylab.meshgrid(r[r<fit_rcutoff], eta)
  g = pylab.zeros_like(ETA)
  g = evalg(x, ETA, R)
  gfit = pylab.reshape(g, len(eta)*len(r[r<fit_rcutoff]))
  return gfit - pylab.reshape([g[r<fit_rcutoff] for g in ghs],
                              len(eta)*len(r[r<fit_rcutoff]))
Example #32
0
    def plot_traj_by_vec_strength(self, ax, mn_drxn, vec_strength, **kwargs):

        ax.plot(mn_drxn, vec_strength)
        ax.get_yaxis().set_ticks([])
        ax.title.set_visible(False)
        ax.get_xaxis().set_ticklabels([])
        ax.spines['polar'].set_color('none')

        cr_mn = mn_drxn
        cr_ln = vec_strength

        binvls = [72, 20]
        rangevls = [[0, 2 * np.pi], [0, 1]]

        if cr_mn.size:

            heatmap, xedges, yedges = np.histogram2d(cr_mn,
                                                     cr_ln,
                                                     bins=binvls,
                                                     range=rangevls)

            xbins = np.linspace(0, 2 * np.pi, binvls[0])
            ybins = np.linspace(0, 1, binvls[1])
            theta, r = pylab.meshgrid(ybins, xbins)

            heatmap_norm = self.norm_heat_map(heatmap)

            heat_map_data = self.save_heat_map_data(heatmap_norm, xedges,
                                                    yedges, r, theta)
Example #33
0
def dist2(x):
  R, GSIGMAS = pylab.meshgrid(r[r<fit_rcutoff], gsigmas)
  g = pylab.zeros_like(GSIGMAS)
  g = evalg(x, GSIGMAS, R)
  gfit = pylab.reshape(g, len(eta)*len(r[r<fit_rcutoff]))
  return gfit - pylab.reshape([g[r<fit_rcutoff] for g in ghs],
                              len(gsigmas)*len(r[r<fit_rcutoff]))
Example #34
0
def plot_skin_temp(file_name, cntr_lvl=None, save_frames=False):
    file, vars = peek(file_name, show_vars=False)
    lon = vars['lon'].get_value()
    lat = vars['lat'].get_value()
    skin_temp = vars['skin_temp']
    skin_temp = skin_temp_var.get_value()[0]
    valid_date = str(vars['valid_date'].get_value()[0])
    valid_time = zfill(str(vars['valid_time'].get_value()[0]), 4)
    valid_when = valid_date[6:] + ' ' \
      + cardinal_2_month(int(valid_date[4:6])) + ' ' \
      + valid_date[0:4] \
      + ' ' + valid_time[:2] + ':' \
      + valid_time[2:] + ' UTC'
    m = set_default_basemap(lon,lat)
    # must plot using 2d lon and lat
    LON, LAT = p.meshgrid(lon,lat)
    p.figure()
    if cntr_lvl is not None:
        m.contourf(LON,LAT,skin_temp, cntr_lvl)
    else:
        m.contourf(LON,LAT,skin_temp)
    m.drawcoastlines()
    m.drawmeridians(n.array(n.arange(lon.min(), lon.max() + a_small_number, 15.)), labels=[1,0,0,1])
    m.drawparallels(n.array(n.arange(lat.min(), lat.max() + a_small_number, 15.)), labels=[1,0,0,1])
    p.colorbar(orientation='horizontal', shrink=0.7, fraction=0.02, pad=0.07, aspect=70)
    title_string = 'Surface pressure (K) valid at' \
      + '\n' + valid_when + ' ' \
      + ' from LAPS'
    p.title(title_string)
    if save_frames:
        p.savefig('frames/frame_' + zfill(str(frame_number),3) +'_skin_temp_' + str(int(lvl[lvl_idx])) + '.png')
    return 
Example #35
0
def explore_cont(fun,
                 bounds,
                 x1resolution,
                 x2resolution,
                 V,
                 ax=None,
                 points=None):
    x1range = bounds[0]
    x2range = bounds[1]
    if ax is None:
        ax = pylab.gca()
    xx, yy = pylab.meshgrid(
        pylab.linspace(x1range[0], x1range[1], x1resolution),
        pylab.linspace(x2range[0], x2range[1], x2resolution))

    zz = np.zeros(xx.shape)
    for i in range(xx.shape[0]):
        for j in range(xx.shape[1]):
            zz[i, j] = fun([xx[i, j], yy[i, j]])

    # plot the calculated function values
    #ax.pcolor(xx, yy, zz)
    im = ax.contourf(xx, yy, zz, V)
    if points is not None:
        ax.plot(points[:, 0], points[:, 1], 'rx')

    return im
Example #36
0
def gaussian2d(data, nxw, nyw=None, sxw=1/3., syw=1/3., rmax=3., **kwargs):
    """Gaussian 2D filter

    - **data**: Data array
    - **nxw**: Size of gaussian weights array along X (and Y if nyw not given)
    - *nyw*: Size of gaussian weights array along Y [default: nxw]
    - *sxw*: Standard deviation of the gaussian distribution along X.
      If <1, its size is relative to nxw. If > 1, it is directly expressed in grid
      steps.
    - *syw*: Same as sxw for Y direction.
    - *rmax*: Distance relative to sqrt(sxw**2+syw**2) after with weights are
      nullified.
    - Other keywords are passed to :func:`generic2d`
    """
    if nyw is None: nyw = nxw
    assert nxw % 2 == 1 and nyw % 2 == 1, 'nxw and nyw must be odd numbers'
    assert sxw > 0 and syw > 0,  'sxw and syw must be positive'

    xx,yy = meshgrid(N.arange(nxw)-nxw/2, N.arange(nyw)-nxw/2)

    if sxw < 1:
        sxw *= nxw/2
    if syw < 1:
        syw *= nyw/2

    weights = N.exp(-(xx**2/sxw**2 + yy**2/syw**2))

    weights[weights<N.exp(-rmax**2)] = 0.

    return generic2d(data, weights, **kwargs)
Example #37
0
def explore_EI(fun,
               x1range,
               x2range,
               x1resolution,
               x2resolution,
               title,
               ax=None,
               *args):
    if ax is None:
        ax = pylab.gca()
    X, Y, model, method = args
    #print(args)
    xx, yy = pylab.meshgrid(
        pylab.linspace(x1range[0], x1range[1], x1resolution),
        pylab.linspace(x2range[0], x2range[1], x2resolution))

    zz = np.zeros(xx.shape)
    for i in range(xx.shape[0]):
        for j in range(xx.shape[1]):
            zz[i, j] = fun(np.array([xx[i, j], yy[i, j]]), X, Y, model, method)

    # plot the calculated function values
    ax = ax.pcolor(xx, yy, zz)
    # if points is not None:
    #     pylab.plot(points[:, 0], points[:, 1], 'rx')
    #pylab.colorbar()
    #    ax.title(title)
    #pylab.show()
    return ax
Example #38
0
def grid(x, y, z , resX=90, resY=90):
    "Convert 3 column data to matplotlib grid"
    xi = pl.linspace(min(x), max(x), resX)
    yi = pl.linspace(min(y), max(y), resY)
    Z = pl.griddata(x, y, z, xi, yi , interp='linear')
    X, Y = pl.meshgrid(xi, yi )
    return X, Y, Z
Example #39
0
def plot_thresholds(rawdata, scan_values, plane='horizontal',
                    xlabel='turns', ylabel='intensity [particles]', zlabel='normalized emittance',
                    xlimits=((0.,8192)), ylimits=((0.,7.1e11)), zlimits=((0., 10.))):

    # Prepare input data.
    # x axis
    t = rawdata[0,:,:]
    turns = plt.ones(t.shape).T * plt.arange(len(t))
    turns = turns.T

    # z axis
    epsn_abs = {}
    epsn_abs['horizontal'] = plt.absolute(rawdata[11,:,:])
    epsn_abs['vertical']   = plt.absolute(rawdata[12,:,:])

    # Prepare plot environment.
    ax11, ax13 = _create_axes(xlabel, ylabel, zlabel, xlimits, ylimits, zlimits)
    cmap = plt.cm.get_cmap('jet', 2)
    ax11.patch.set_facecolor(cmap(range(2))[-1])
    cmap = plt.cm.get_cmap('jet')

    x, y = plt.meshgrid(turns[:,0], scan_values)
    z = epsn_abs[plane]

    threshold_plot = ax11.contourf(x, y, z.T, levels=plt.linspace(zlimits[0], zlimits[1], 201),
                                   vmin=zlimits[0], vmax=zlimits[1], cmap=cmap)
    cb = plt.colorbar(threshold_plot, ax13, orientation='vertical')
    cb.set_label(zlabel)

    plt.tight_layout()
Example #40
0
	def plotAngleGrid(self):
		
		self.plotter.clearFigure()
		
		val = self.angleGridMatrix[0, : , : ]
		y = range(0, self.yAngleDim-1, 1)	
		z = range(0, self.zAngleDim-1, 1)
		Z,Y = meshgrid( z, y)

		
		valRange = [ 0 , self.yAngleDim, 0, self.zAngleDim ]
		title="Travel Angle Grid"
		colorBar=True
		print "Plotting"
		
		axis = self.plotter.getAxis()
		axis.set_xlabel("Y")
		axis.set_ylabel("Z")
		self.plotter.setAspectRatioEven(even=True)
		self.plotter.applyAspectRatio()
		self.plotter.plotXYZData( Y, Z, val, title,colorBar, valRange)
		# flip the axis
		lims = self.plotter.getAxisLimits()
		self.plotter.limitAxis(lims[0], lims[1], lims[3], lims[2])
		
		self.plotter.drawFigure()
		
		print "Done"
		
		self.lastPlot = self.LAST_PLOT_TRAVEL_ANGLE
		
		return True
Example #41
0
def test_operation_approx():
    def flux_qubit_potential(phi_m, phi_p):
        return 2 + alpha - 2 * pl.cos(phi_p)*pl.cos(phi_m) - alpha * pl.cos(phi_ext - 2*phi_p)
    alpha = 0.7
    phi_ext = 2 * np.pi * 0.5
    phi_m = pl.linspace(0, 2*np.pi, 100)
    phi_p = pl.linspace(0, 2*np.pi, 100)
    X,Y = pl.meshgrid(phi_p, phi_m)
    Z = flux_qubit_potential(X, Y).T

    # the diagram creatinos
    from diagram.operations.computations import multiply
    from diagram.ternary import AEV3DD

    aevdd = AEV3DD()
    diagram3 = aevdd.create(Z, 0, True)
    diagram4 = aevdd.create(Z, 0, True)

    aevdd_mat = multiply(diagram3, diagram4, 9).to_matrix(77, True)
    aevdd_mat_approx = multiply(diagram3, diagram4, 9, approximation_precision=1, in_place='1').to_matrix(27, True)

    pl.plt.figure()
    fig, ax = pl.plt.subplots()
    p = ax.pcolor(X/(2*pl.pi), Y/(2*pl.pi), Z, cmap=pl.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max())
    cb = fig.colorbar(p, ax=ax)
    p = ax.pcolor(X/(2*pl.pi), Y/(2*pl.pi), Z, cmap=pl.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max())
    cb = fig.colorbar(p, ax=ax)
    # cnt = ax.contour(Z, cmap=pl.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])
    pl.show()
Example #42
0
 def surface(self) :
     x = pl.arange(-self.dimension[0],self.dimension[0]+1e-8,self.dimension[0]/5)
     y = pl.arange(-self.dimension[1],self.dimension[1]+1e-8,self.dimension[1]/5)
     xx,yy = pl.meshgrid(x,y)
     zz = 1/self.placement.orientation[2]*(pl.linalg.dot(self.placement.orientation,self.placement.location)-self.placement.orientation[0]*xx-self.placement.orientation[1]*yy)
     
     return [xx,yy,zz]        
Example #43
0
def LeapFrog(func, eps=0.0001, bounds=3 , delay=0.01, iterations=3000, printV=False, draw=True):
	plt.figure()

	players = (2*np.random.rand(20,2)-1)*bounds
	x= np.arange(-bounds, bounds, 0.01)
	y= np.arange(-bounds, bounds, 0.01)
	X,Y = meshgrid(x, -y)
	Z = func(X, Y)
	im = plt.imshow(Z,cmap=cm.RdBu,extent=[-bounds, bounds, -bounds, bounds])
	points, =plt.plot(players[:,0],players[:,1],'yo', marker='x')
	colorbar(im) 

	for i in range(1,iterations):
		z=func(players[:,0], players[:,1])
		maxZ=np.argmax(z)
		minZ = np.argmin(z)
		r = np.random.rand(1,2)
		players[maxZ, :]=players[minZ, :]-r*(players[maxZ, :]-players[minZ, :])
		if(abs(z[maxZ]-z[minZ])<eps):
			if(printV):
				print("Minimum at: {0}".format(players[minZ,:]))
			return players[minZ,:];
		if(printV):
			print([z[minZ], players[minZ,:]])
		points.set_xdata(players[:,0])
		points.set_ydata(players[:,1])
		if(draw):
			plt.pause(delay)
			plt.draw()
Example #44
0
def plotInit(Plotting, Elements):
	if (Plotting == 2):
		loc = [i.xy for i in Elements]
		x = [i.real for i in loc]
		y = [i.imag for i in loc]
		x = list(sorted(set(x))) 
		x.remove(-10)
		y = list(sorted(set(y)))

		X, Y = pylab.meshgrid(x, y)
		U = pylab.ones(shape(X))
		V = pylab.ones(shape(Y))

		pylab.ion()
		fig, ax = pylab.subplots(1,1)
		graph = ax.quiver(X, Y, U, V)
		pylab.draw()
	else:
		pylab.ion()
		graph, = pylab.plot(1, 'ro', markersize = 2) 
		x = 2
		pylab.axis([-x,x,x,-x])

		graph.set_xdata(0)
		graph.set_ydata(0)
		pylab.draw()

	return graph
Example #45
0
 def __init__( self, t, x, y, contrast=1 ):
     self.t = t
     self.x = x
     self.y = y
     self.contrast = float(contrast)
     self._xx, self._yy = pl.meshgrid(self.x, self.y)
     self.make_frames()
Example #46
0
def griddata( X, Y, Z, xl, yl, xr, yr, dx):
    # define grid.
    xi, yi = p.meshgrid( p.linspace(xl,xr, int((xr-xl)/dx)+1), p.linspace(yl,yr, int((yr-yl)/dx)+1))
    # grid the data.
    zi = mgriddata(X,Y,Z,xi,yi)
    New = grid( zi, xl, yl, dx)
    return New
Example #47
0
def showSF(N, label=''):
    fig = P.figure()
    ax1 = fig.add_subplot(1, 2, 1, projection='3d')
    ax2 = fig.add_subplot(1, 2, 2)

    Nx = 21
    Ny = 21
    nLevels = 12

    tix = P.linspace(0.0, 1.0, Nx)
    tiy = P.linspace(0.0, 1.0, Ny)
    (X, Y) = P.meshgrid(tix, tiy)
    z = g.RVector(len(X.flat))

    for i, x in enumerate(X.flat):
        p = g.RVector3(X.flat[i], Y.flat[i])
        z[i] = N(p)

    Z = P.ma.masked_where(z == -99., z)
    Z = Z.reshape(Ny, Nx)

    ax2.contourf(X, Y, Z)
    ax2.set_aspect('equal')
    surf = ax1.plot_surface(X,
                            Y,
                            Z,
                            rstride=1,
                            cstride=1,
                            cmap=P.cm.jet,
                            linewidth=0)

    ax2.set_title(label + N.__str__())
    fig.colorbar(surf)
    def plot_wire_surface_pcolor(self):
        """
        Plot the fraction of executions as a function of the fraction of nodes for
        each source. Three plots are created: wireframe, surface, and pseudocolor.

        """
        logging.debug('')
        if self.dimension > 0:
            return
        array = self._data_to_array()

        x = pylab.linspace(0.0, 1.0, len(array[0])+1)
        y = pylab.linspace(0.0, 1.0, len(array)+1)
        X, Y = pylab.meshgrid(x, y)

        #fig_wire = MyFig(self.options, xlabel='Probability p', ylabel='Fraction of Nodes', ThreeD=True)
        #fig_surf = MyFig(self.options, xlabel='Probability p', ylabel='Fraction of Nodes', ThreeD=True)
        fig_pcol = MyFig(self.options, xlabel='Probability p', ylabel='Fraction of Nodes')

        #fig_wire.ax.plot_wireframe(X, Y, array)
        #fig_surf.ax.plot_surface(X, Y, array, rstride=1, cstride=1, linewidth=1, antialiased=True)
        pcolor = fig_pcol.ax.pcolor(X, Y, array, cmap=cm.jet, vmin=0.0, vmax=1.0)
        cbar = fig_pcol.fig.colorbar(pcolor, shrink=0.8, aspect=10)
        cbar.ax.set_yticklabels(pylab.linspace(0.0, 1.0, 11), fontsize=0.8*self.options['fontsize'])

        #for ax in [fig_wire.ax, fig_surf.ax]:
            #ax.set_zlim3d(0.0, 1.01)
            #ax.set_xlim3d(0.0, 1.01)
            #ax.set_ylim3d(0.0, 1.01)

        #self.figures['wireframe'] = fig_wire.save('wireframe_' + str(self.data_filter))
        #self.figures['surface'] = fig_surf.save('surface_' + str(self.data_filter))
        self.figures['pcolor'] = fig_pcol.save('pcolor_' + str(self.data_filter))
Example #49
0
def plotField(x, F, titleStr, filename):
    import pylab as p
    import griddata as g
    import numpy
    p.ion()
    p.clf()
    xhat = Vector3d(1, 0, 0)
    yhat = Vector3d(0, 1, 0)
    numInternalNodes = len(x.internalValues())
    indices = [i for i in xrange(numInternalNodes) if abs(x[i].z) < 1e-8]
    xs = numpy.array([x[i].dot(xhat) for i in indices])
    ys = numpy.array([x[i].dot(yhat) for i in indices])
    x1 = p.linspace(-0.5, 1.5, 50)
    y1 = p.linspace(-0.5, 1.5, 50)
    xg, yg = p.meshgrid(x1, y1)
    if isinstance(F, VectorField3d) or isinstance(F[0], Vector3d):
        Fxs = numpy.array([F[i].dot(xhat) for i in indices])
        Fys = numpy.array([F[i].dot(yhat) for i in indices])
        Fxg = g.griddata(xs, ys, Fxs, xg, yg)
        Fyg = g.griddata(xs, ys, Fys, xg, yg)
        p.quiver(xg, yg, Fxg, Fyg)
    else:
        #      levels = [0.1*i for i in xrange(32)]
        Fs = numpy.array([F[i] for i in indices])
        Fg = g.griddata(xs, ys, Fs, xg, yg)
        p.contour(xg, yg, Fg, 30)
        p.colorbar()
    p.title(titleStr)
    p.savefig(filename)
def plot_ratio(df,
               bins=[np.linspace(0, .25, 100),
                     np.linspace(0, 1, 100)],
               alpha=1,
               cmap=None,
               mc_field='mc',
               stdc_field='stdc',
               response_field='response'):
    C, M = plt.meshgrid(*bins)
    resp1 = plt.histogram2d(
        df[df.loc[:, response_field] == 1].loc[:, stdc_field].values,
        df[df.loc[:, response_field] == 1].loc[:, mc_field].values,
        bins=bins)[0] + 1
    #resp1[resp1==1] = np.nan
    resp2 = plt.histogram2d(
        df[df.loc[:, response_field] == -1].loc[:, stdc_field].values,
        df[df.loc[:, response_field] == -1].loc[:, mc_field].values,
        bins=bins)[0] + 1
    #resp2[resp2==1] = np.nan
    resp1 = resp1.astype(float) / np.nansum(resp1)
    resp2 = resp2.astype(float) / np.nansum(resp2)
    plane = np.log(resp1 / resp2)
    #plane[plane==1] = np.nan
    plt.pcolormesh(bins[1],
                   bins[0],
                   np.ma.masked_invalid(plane),
                   cmap=cmap,
                   vmin=-2.4,
                   vmax=2.4)
Example #51
0
def gabor_patch(
        sigma_deg=2,
        radius_deg=6,
        px_deg=50,
        sf_cyc_deg=2,
        phase_deg=0,  #phase of cosine in degrees
        contrast=1.0):
    """Return a gabor patch texture of the given dimensions and parameters."""

    height = width = radius_deg * px_deg
    x = pylab.linspace(-radius_deg, radius_deg, width)
    X, Y = pylab.meshgrid(x, x)
    L = pylab.exp(-(X**2 + Y**2) / sigma_deg**2)  #gaussian envelope
    #use around to round towards zero, otherwise you will get banding artifacts
    #dtype must be int for proper conversion to int and init of image data
    #I = pylab.array(-pylab.zeros(X.size)*max_range + neutral_gray, dtype='int')
    I = pylab.array(pylab.around(
        contrast * pylab.cos(2 * pylab.pi *
                             (sf_cyc_deg) * X + phase_deg * pylab.pi / 180.) *
        L * max_range) + neutral_gray,
                    dtype='int').ravel()
    IA = pylab.ones(I.size * 2, dtype='int') * 255
    IA[:-1:2] = I  #Need alpha=255 otherwise image is mixed with background
    #Data format for image http://www.pyglet.org/doc/programming_guide/accessing_or_providing_pixel_data.html
    data = array.array('B', IA)
    gabor = pyglet.image.ImageData(width, height, 'IA', data.tostring())
    return gabor
    def prepare_sensors(sensor_locations, resolution=51):
        """
        Common method, to pre-process sensors before display (project them in 2D).
        """


        def sphere_fit(params):
            """Function to fit the sensor locations to a sphere"""
            return ((sensor_locations[:, 0] - params[1]) ** 2 + (sensor_locations[:, 1] - params[2]) ** 2
                    + (sensor_locations[:, 2] - params[3]) ** 2 - params[0] ** 2)


        (radius, circle_x, circle_y, circle_z) = leastsq(sphere_fit, (1, 0, 0, 0))[0]
        # size of each square
        ssh = float(radius) / resolution         # half-size
        # Generate a grid and interpolate using the gridData module
        x_arr = numpy.arange(circle_x - radius, circle_x + radius, ssh * 2.0) + ssh
        y_arr = numpy.arange(circle_y - radius, circle_y + radius, ssh * 2.0) + ssh
        x_arr, y_arr = pylab.meshgrid(x_arr, y_arr)

        # project the sensor locations onto the sphere
        sproj = sensor_locations - numpy.array((circle_x, circle_y, circle_z))
        sproj = radius * sproj / numpy.c_[numpy.sqrt(numpy.sum(sproj ** 2, axis=1))]
        sproj += numpy.array((circle_x, circle_y, circle_z))
        return dict(sproj=sproj, x_arr=x_arr, y_arr=y_arr,
                    circle_x=circle_x, circle_y=circle_y, rad=radius)
Example #53
0
    def prepare_sensors(sensor_locations, resolution=51):
        """
        Common method, to pre-process sensors before display (project them in 2D).
        """
        def sphere_fit(params):
            """Function to fit the sensor locations to a sphere"""
            return ((sensor_locations[:, 0] - params[1])**2 +
                    (sensor_locations[:, 1] - params[2])**2 +
                    (sensor_locations[:, 2] - params[3])**2 - params[0]**2)

        (radius, circle_x, circle_y,
         circle_z) = leastsq(sphere_fit, (1, 0, 0, 0))[0]
        # size of each square
        ssh = float(radius) / resolution  # half-size
        # Generate a grid and interpolate using the gridData module
        x_arr = numpy.arange(circle_x - radius, circle_x + radius,
                             ssh * 2.0) + ssh
        y_arr = numpy.arange(circle_y - radius, circle_y + radius,
                             ssh * 2.0) + ssh
        x_arr, y_arr = pylab.meshgrid(x_arr, y_arr)

        # project the sensor locations onto the sphere
        sproj = sensor_locations - numpy.array((circle_x, circle_y, circle_z))
        sproj = radius * sproj / numpy.c_[numpy.sqrt(
            numpy.sum(sproj**2, axis=1))]
        sproj += numpy.array((circle_x, circle_y, circle_z))
        return dict(sproj=sproj,
                    x_arr=x_arr,
                    y_arr=y_arr,
                    circle_x=circle_x,
                    circle_y=circle_y,
                    rad=radius)
Example #54
0
    def plot_solution(self, T, X, u):
        # The surface plot
        Xm, Tm = pylab.meshgrid(X, linspace(T, 0.0, u.shape[0]))
        fig_surface = pylab.figure()
        ax = ax3d.Axes3D(fig_surface)
        ax.plot_surface(Xm, Tm, u)
        ax.set_ylabel('Time $t$')
        ax.set_xlabel('Stock price $x$')
        ax.set_zlabel('Option value $f(t,x)$')

        # The color temperature plot
        fig_color = pylab.figure()
        ax = pylab.gca()
        ax.set_xlabel('Time $t$')
        ax.set_ylabel('Stock price $x$')
        ax.imshow(u.T,
                  interpolation='bilinear',
                  origin='lower',
                  cmap=matplot.cm.hot,
                  aspect='auto',
                  extent=(T, 0.0, X[0], X[-1]))

        # Plot of price function at time 0
        fig_zero = pylab.figure()
        pylab.plot(X, u[m - 1, :])
        ax = pylab.gca()
        ax.set_xlabel('Stock price $x$')
        ax.set_ylabel('Option value $f(0,x)$')

        return fig_surface, fig_color, fig_zero
Example #55
0
    def vecPlot2(self, row, col, r_m, mWx, mWy, data1, data2, dmr, frmSize, winSize):
        pl.clf()
        pl.ion()
        pWx = []
        l = dmr - row - col
        for f in range(l):
            pWx.append(mWx[row + f, col + f, :, 0])
        pWx = np.array(pWx)

        sqWx = np.sqrt(pWx * pWx)
        print sqWx
        r, c = sqWx.shape
        x = pl.arange(c + 1)
        y = pl.arange(r + 1)
        X, Y = pl.meshgrid(x, y)

        pl.subplot2grid((1, 2), (0, 0))
        pl.pcolor(X, Y, sqWx, vmin=0, vmax=1)
        pl.xlim(0, c)
        pl.ylim(0, r)
        pl.colorbar()
        pl.title("user_1 (t:" + str(row) + ")")
        pl.gray()

        pWy = []
        l = dmr - row - col
        for f in range(l):
            pWy.append(mWy[row + f, col + f, :, 0])
        pWy = np.array(pWy)

        sqWy = np.sqrt(pWy * pWy)
        print sqWy
        r, c = sqWy.shape
        x = pl.arange(c + 1)
        y = pl.arange(r + 1)
        X, Y = pl.meshgrid(x, y)

        pl.subplot2grid((1, 2), (0, 1))
        pl.pcolor(X, Y, sqWy, vmin=0, vmax=1)
        pl.xlim(0, c)
        pl.ylim(0, r)
        pl.colorbar()
        pl.title("user_2 (t:" + str(col) + ")")
        pl.gray()

        pl.tight_layout()
        pl.draw()
Example #56
0
        def gen_ssmodel(self):

		"""
		generates full neural model

		Attributes:
		----------
		K: matrix
			matrix of connectivity kernel evaluated over the spatial domain of the kernel

		Sigma_e: matrix
			field disturbance covariance matrix
		Sigma_e_c: matrix
			cholesky decomposiotion of field disturbance covariance matrix
		Sigma_varepsilon_c: matrix
			cholesky decomposiotion of observation noise covariance matrix
		C: matrix
			matrix of sensors evaluated at each spatial location, it's not the same as C in the IDE model	

		"""
		print "generating full neural model"

		#Generate field meshgrid
                simulation_field_space_x,simulation_field_space_y=pb.meshgrid(self.simulation_space_x_y,self.simulation_space_x_y)


                K=0
                for i in range(len(self.kernel.Psi)):
                        K+=self.kernel.weights[i]*self.kernel.Psi[i](simulation_field_space_x,simulation_field_space_y)
        
                self.K=K


		#calculate field disturbance covariance matrix and its Cholesky decomposition

                gamma_space=pb.array(zip(simulation_field_space_x.flatten(),simulation_field_space_y.flatten()))

                N1,D1 = gamma_space.shape
                diff = gamma_space.reshape(N1,1,D1) - gamma_space.reshape(1,N1,D1)
                Sigma_e_temp=self.gamma_weight*np.exp(-np.sum(np.square(diff),-1)*(1./self.gamma.width))
                self.Sigma_e=Sigma_e_temp

                if hasattr(self,'Sigma_e_c'):
                        pass
                else:
                        self.Sigma_e_c=sp.linalg.cholesky(self.Sigma_e,lower=1)    

        #calculate Cholesky decomposition of observation noise covariance matrix
                Sigma_varepsilon_c=sp.linalg.cholesky(self.Sigma_varepsilon,lower=1)
                self.Sigma_varepsilon_c=Sigma_varepsilon_c

        #Calculate sensors at each spatial locations, it's not the same as C in the IDE model	
                t0=time.time()

                sensor_space=self.obs_locns
                N2,D2 = sensor_space.shape
                diff = sensor_space.reshape(N2,1,D2) - gamma_space.reshape(1,N1,D1)
                C=np.exp(-np.sum(np.square(diff),-1)*(1./self.sensor_kernel.width))
                self.C=C
Example #57
0
 def surface(self) :
     x = pl.arange(-self.dimension[0],self.dimension[0]+1e-8,self.dimension[0]/5)
     y = pl.arange(-self.dimension[1],self.dimension[1]+1e-8,self.dimension[1]/5)
     xx,yy = pl.meshgrid(x,y)
     cv = self.placement.location+self.placement.orientation*self.radcurv        
     zz = -pl.sign(self.radcurv)*pl.sqrt(self.radcurv**2-(xx-cv[0])**2-(yy-cv[1])**2)+cv[2]
     
     return [xx,yy,zz]