Пример #1
0
 def getMesh(self, ori, plan):  # complete mesh for given plane
     if self.zb == None: self.makeZblock()
     grd = self.getFullGrid()
     dx1 = grd['dx']
     dy1 = grd['dy']
     #print 'aq mesh',grd
     xv = zeros((grd['nx'] + 1))
     xv[0] = grd['x0']
     xv[1:] = grd['x0'] + cumsum(dx1)
     yv = zeros((grd['ny'] + 1))
     yv[0] = grd['y0']
     yv[1:] = grd['y0'] + cumsum(dy1)
     nlay, nx, ny = shape(self.zb)
     if self.getDim() in ['Xsection', 'Radial']: return meshgrid(xv, yv)
     if ori == 'Z': return meshgrid(xv, yv)
     elif ori == 'X':
         a = yv * ones((nlay, 1))
         b = self.zb[:, :, plan]
         c = ones((nlay, len(yv)))
     elif ori == 'Y':
         a = xv * ones((nlay, 1))
         b = self.zb[:, plan, :]
         c = ones((nlay, len(xv)))
     c[:, 1:-1] = b[:, 1:] / 2 + b[:, :-1] / 2
     c[:, 0] = b[:, 0]
     c[:, -1] = b[:, -1]
     return a, c
Пример #2
0
 def getMesh(self, ori, plan):  # complete mesh for given plane
     if self.zb == None:
         self.makeZblock()
     grd = self.getFullGrid()
     dx1 = grd["dx"]
     dy1 = grd["dy"]
     # print 'aq mesh',grd
     xv = zeros((grd["nx"] + 1))
     xv[0] = grd["x0"]
     xv[1:] = grd["x0"] + cumsum(dx1)
     yv = zeros((grd["ny"] + 1))
     yv[0] = grd["y0"]
     yv[1:] = grd["y0"] + cumsum(dy1)
     nlay, nx, ny = shape(self.zb)
     if self.getDim() in ["Xsection", "Radial"]:
         return meshgrid(xv, yv)
     if ori == "Z":
         return meshgrid(xv, yv)
     elif ori == "X":
         a = yv * ones((nlay, 1))
         b = self.zb[:, :, plan]
         c = ones((nlay, len(yv)))
     elif ori == "Y":
         a = xv * ones((nlay, 1))
         b = self.zb[:, plan, :]
         c = ones((nlay, len(xv)))
     c[:, 1:-1] = b[:, 1:] / 2 + b[:, :-1] / 2
     c[:, 0] = b[:, 0]
     c[:, -1] = b[:, -1]
     return a, c
Пример #3
0
def display_toroid(u0,
                   s0,
                   s1,
                   ds,
                   u_val=1,
                   v_val=None,
                   a=1,
                   solver=None,
                   show=False):
    C = toroid(u_val, v_val, a)  # Find the Christoffel tensor for toroid
    X = solve(C, u0, s0, s1, ds, solver)

    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    from math import pi
    if v_val is None:
        u = u_val  # toroids
        v, w = plt.meshgrid(np.linspace(-pi, pi, 250),
                            np.linspace(0, 2 * pi, 250))
    else:
        v = v_val  # spherical bowls
        u, w = plt.meshgrid(np.linspace(0, 2, 250),
                            np.linspace(0, 2 * pi, 250))

    x = (a * np.sinh(u) * np.cos(w)) / (np.cosh(u) - np.cos(v))
    y = (a * np.sinh(u) * np.sin(w)) / (np.cosh(u) - np.cos(v))
    z = (a * np.sin(v)) / (np.cosh(u) - np.cos(v))

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=90., azim=0)
    # use transparent colormap
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = -.5 * np.ones(theCM.N)
    theCM._lut[:-3, -1] = alphas
    ax.plot_surface(x, y, z, linewidth=0, cmap=theCM)
    plt.hold('on')

    # plot the parametrized data on to the toroid
    if v_val is None:
        w, v = X[:, 0], X[:, 2]
    else:
        w, u = X[:, 0], X[:, 2]
    x = (a * np.sinh(u) * np.cos(w)) / (np.cosh(u) - np.cos(v))
    y = (a * np.sinh(u) * np.sin(w)) / (np.cosh(u) - np.cos(v))
    z = (a * np.sin(v)) / (np.cosh(u) - np.cos(v))

    s1_ = s1 / pi
    ax.plot(x, y, z, '--r')
    fig.suptitle('$s\in[%.1f\pi \, , \,%2.1f\pi]$' % (s0, s1_))
    if show == True:
        plt.show()
    return X, plt
Пример #4
0
def display_sphere_with_geodesic(u0, s0, s1, ds):
    C = Christoffel2nd_sphere()
    X = solve(C, u0, s0, s1, ds)
    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    N = X[:, 0].shape[0]
    u, v = plt.meshgrid(np.linspace(0, 2 * np.pi, N),
                        np.linspace(0, 2 * np.pi, N))
    x = np.cos(u) * np.cos(v)
    y = np.sin(u) * np.cos(v)
    z = np.sin(v)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=50, azim=-120)
    # use transparent colormap
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = -.5 * np.ones(theCM.N)
    theCM._lut[:-3, -1] = alphas
    ax.plot_surface(x, y, z, linewidth=0, cmap=theCM)
    plt.hold('on')

    # plot the parametrized data on to the sphere
    u, v = X[:, 0], X[:, 2]
    x = np.cos(u) * np.cos(v)
    y = np.sin(u) * np.cos(v)
    z = np.sin(v)

    ax.plot(x, y, z, '--r')
    from math import pi
    s1_ = s1 / pi
    fig.suptitle('$s\in[%.1f\, , \,%2.1f\pi]$' % (s0, s1_))
    plt.show()
Пример #5
0
def plot_hyperplane(X, Y, model, K, plot_id, d = 500):
    I0 = np.where(Y==-1)[0]
    I1 = np.where(Y==1)[0]

    plt.subplot(plot_id)

    plt.plot(X[I1, 0], X[I1, 1], 'og')
    plt.plot(X[I0, 0], X[I0, 1], 'xb')

    min_val = np.min(X, 0)
    max_val = np.max(X, 0)

    clf = model()
    clf.train(X, Y, K)

    x0_plot = np.linspace(min_val[0, 0], max_val[0, 0], d)
    x1_plot = np.linspace(min_val[0, 1], max_val[0, 1], d)

    [x0, x1] = plt.meshgrid(x0_plot, x1_plot);

    Y_all = np.matrix(np.zeros([d, d]))

    for i in range(d):
        X_all = np.matrix(np.zeros([d, 2]))
        X_all[:, 0] = np.matrix(x0[:, i]).T
        X_all[:, 1] = np.matrix(x1[:, i]).T
        Y_all[:, i] = clf.predict(X_all)

    plt.contour(np.array(x0), np.array(x1), np.array(Y_all), levels = [0.0], colors = 'red')
Пример #6
0
 def getMeshCentre(self, ori, plan):  # mesh au milieu de la grille
     if self.zb == None: self.makeZblock()
     grd = self.getFullGrid()
     dx1 = grd['dx']
     dy1 = grd['dy']
     xv = grd['x0'] + cumsum(dx1) - dx1 / 2.
     yv = grd['y0'] + cumsum(dy1) - dy1 / 2.
     nlay, nx, ny = shape(self.zb)
     if self.getDim() in ['Xsection', 'Radial']: return meshgrid(xv, yv)
     if ori == 'Z': return meshgrid(xv, yv)
     elif ori == 'X':
         z = self.zb[1:, :, plan] / 2 + self.zb[:-1, :, plan] / 2
         return yv * ones((nlay - 1, 1)), z
     elif ori == 'Y':
         z = self.zb[1:, plan, :] / 2 + self.zb[:-1, plan, :] / 2
         return xv * ones((nlay - 1, 1)), z
Пример #7
0
def plot_hyperplane(X, Y, model, K, plot_id, d=500):
    I0 = np.where(Y == -1)[0]
    I1 = np.where(Y == 1)[0]

    plt.subplot(plot_id)

    plt.plot(X[I1, 0], X[I1, 1], 'og')
    plt.plot(X[I0, 0], X[I0, 1], 'xb')

    min_val = np.min(X, 0)
    max_val = np.max(X, 0)

    clf = model()
    clf.train(X, Y, K)

    x0_plot = np.linspace(min_val[0, 0], max_val[0, 0], d)
    x1_plot = np.linspace(min_val[0, 1], max_val[0, 1], d)

    [x0, x1] = plt.meshgrid(x0_plot, x1_plot)

    Y_all = np.matrix(np.zeros([d, d]))

    for i in range(d):
        X_all = np.matrix(np.zeros([d, 2]))
        X_all[:, 0] = np.matrix(x0[:, i]).T
        X_all[:, 1] = np.matrix(x1[:, i]).T
        Y_all[:, i] = clf.predict(X_all)

    plt.contour(np.array(x0),
                np.array(x1),
                np.array(Y_all),
                levels=[0.0],
                colors='red')
Пример #8
0
    def plotModel2D(self,X=[],Y=[],xLabel="",yLabel="",title="",fName=""):
        #fig = plt.figure(figsize=(6,4),dpi=100)
        plt.close()
        
        # 真値のプロット(クラスごとにマーカーを変更)
        plt.plot(X[Y[:,0]==0,0],X[Y[:,0]==0,1],'cx',markersize=14,label="ラベル0")
        plt.plot(X[Y[:,0]==1,0],X[Y[:,0]==1,1],'m.',markersize=14,label="ラベル1")

        # 予測値のメッシュの計算
        X1,X2 = plt.meshgrid(plt.linspace(np.min(X[:,0]),np.max(X[:,0]),50),plt.linspace(np.min(X[:,1]),np.max(X[:,1]),50))
        Xmesh = np.hstack([np.reshape(X1,[-1,1]),np.reshape(X2,[-1,1])])
        Pmesh,_,_ = self.predict(Xmesh)
        Pmesh = np.reshape(Pmesh,X1.shape)

        # 予測値のプロット
        CS = plt.contourf(X1,X2,Pmesh,linewidths=2,cmap="bwr",alpha=0.3,vmin=0,vmax=1)

        # カラーバー
        CB = plt.colorbar(CS)
        CB.ax.tick_params(labelsize=14)

        # 各軸の範囲とラベルの設定
        plt.xlim([np.min(X[:,0]),np.max(X[:,0])])
        plt.ylim([np.min(X[:,1]),np.max(X[:,1])])
        plt.title(title,fontsize=14)
        plt.xlabel(xLabel,fontsize=14)
        plt.ylabel(yLabel,fontsize=14)
        plt.legend()

        # グラフの表示またはファイルへの保存
        if len(fName):
            plt.savefig(fName)
        else:
            plt.show()
Пример #9
0
def display_toroid(u0,s0,s1,ds,u_val=1,v_val=None,a=1,solver=None,show=False):
    C = toroid(u_val,v_val,a) # Find the Christoffel tensor for toroid
    X = solve(C,u0,s0,s1,ds,solver)
    
    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    from math import pi
    if v_val is None:
        u = u_val # toroids
        v,w = plt.meshgrid(np.linspace(-pi,pi,250),np.linspace(0,2*pi,250))
    else:
        v = v_val # spherical bowls
        u,w = plt.meshgrid(np.linspace(0,2,250),np.linspace(0,2*pi,250))

    x = (a*np.sinh(u)*np.cos(w))/(np.cosh(u) - np.cos(v))
    y = (a*np.sinh(u)*np.sin(w))/(np.cosh(u) - np.cos(v))  
    z = (a*np.sin(v))/(np.cosh(u) - np.cos(v))

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=90., azim=0)
    # use transparent colormap
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = -.5*np.ones(theCM.N)
    theCM._lut[:-3,-1] = alphas
    ax.plot_surface(x,y,z,linewidth=0,cmap=theCM)
    plt.hold('on')

    # plot the parametrized data on to the toroid
    if v_val is None:
        w,v = X[:,0], X[:,2]
    else:
        w,u = X[:,0], X[:,2]
    x = (a*np.sinh(u)*np.cos(w))/(np.cosh(u) - np.cos(v))
    y = (a*np.sinh(u)*np.sin(w))/(np.cosh(u) - np.cos(v))  
    z = (a*np.sin(v))/(np.cosh(u) - np.cos(v))

    s1_ = s1/pi
    ax.plot(x,y,z,'--r')
    fig.suptitle('$s\in[%.1f\pi \, , \,%2.1f\pi]$'%(s0,s1_))
    if show == True:
        plt.show()
    return X,plt
Пример #10
0
    def draw(self):
        x = np.arange(0, self.h_x, self.del_x)
        y = np.arange(0, self.h_y, self.del_y)
        X, Y = plt.meshgrid(x, y)
        Z = self.map

        plt.pcolor(X, Y, Z)
        plt.colorbar()
        plt.show()
Пример #11
0
 def getMeshCentre(self, ori, plan):  # mesh au milieu de la grille
     if self.zb == None:
         self.makeZblock()
     grd = self.getFullGrid()
     dx1 = grd["dx"]
     dy1 = grd["dy"]
     xv = grd["x0"] + cumsum(dx1) - dx1 / 2.0
     yv = grd["y0"] + cumsum(dy1) - dy1 / 2.0
     nlay, nx, ny = shape(self.zb)
     if self.getDim() in ["Xsection", "Radial"]:
         return meshgrid(xv, yv)
     if ori == "Z":
         return meshgrid(xv, yv)
     elif ori == "X":
         z = self.zb[1:, :, plan] / 2 + self.zb[:-1, :, plan] / 2
         return yv * ones((nlay - 1, 1)), z
     elif ori == "Y":
         z = self.zb[1:, plan, :] / 2 + self.zb[:-1, plan, :] / 2
         return xv * ones((nlay - 1, 1)), z
Пример #12
0
    def draw_fit(self):
        Ri = rotmat(self.grid_angle)
        X, Y = lab.meshgrid(range(-50, 50), range(-50, 50))
        X, Y = X * self.grid_spacing + self.grid_orig[0], Y * self.grid_spacing + self.grid_orig[1]
        inferred_grid_pts = np.hstack([np.reshape(X, (-1,1)), np.reshape(Y, (-1,1))])
        inferred_grid_pts = [Ri * np.reshape(p,(-1,1)) for p in inferred_grid_pts]

        with_grid = self.img.copy()
        for p in inferred_grid_pts:
            cv2.circle(with_grid, tuple(p), 4, 200, 4)
        show(with_grid)
Пример #13
0
def convert_depth_to_uvd(depth):
    v, u = pylab.meshgrid(range(0, depth.shape[0], 1),
                          range(0, depth.shape[1], 1),
                          indexing='ij')
    v = np.asarray(v, 'uint16')[:, :, np.newaxis]
    u = np.asarray(u, 'uint16')[:, :, np.newaxis]
    depth = depth[:, :, np.newaxis]
    uvd = np.concatenate((u, v, depth), axis=2)

    # print v.shape,u.shape,uvd.shape
    return uvd
Пример #14
0
 def getEpais(self):
     if self.zb == None: self.makeZblock()
     ep = self.zb[:-1, :, :] - self.zb[1:, :, :]
     if self.getDim() in ['Xsection', 'Radial']:
         grd = self.getFullGrid()
         dx, dy = grd['dx'], grd['dy']
         a, ep = meshgrid(ones((len(dx))), dy[::-1])
         ep = reshape(ep, (len(dy), 1, len(dx)))
     if self.getTypeAq() == 'libre':
         hd = self.model.Ecoulement.getMfHead(0)
         ep[0, :, :] = hd - self.zb[1, :, :]
     return ep
Пример #15
0
 def getEpais(self):
     if self.zb == None:
         self.makeZblock()
     ep = self.zb[:-1, :, :] - self.zb[1:, :, :]
     if self.getDim() in ["Xsection", "Radial"]:
         grd = self.getFullGrid()
         dx, dy = grd["dx"], grd["dy"]
         a, ep = meshgrid(ones((len(dx))), dy[::-1])
         ep = reshape(ep, (len(dy), 1, len(dx)))
     if self.getTypeAq() == "libre":
         hd = self.model.Ecoulement.getMfHead(0)
         ep[0, :, :] = hd - self.zb[1, :, :]
     return ep
Пример #16
0
    def draw2(self):
        x = np.arange(0, self.h_x + 1, self.del_x)
        y = np.arange(0, self.h_y + 1, self.del_y)
        X, Y = plt.meshgrid(x, y)
        Z = self.u.reshape([self.x_div, self.y_div])

        plt.xlabel("x")
        plt.ylabel("y")
        # plt.xlim([0, self.h_x])
        # plt.ylim([0, self.h_y])

        plt.pcolor(X, Y, Z.T)
        plt.colorbar()
        plt.show()
Пример #17
0
    def draw3D2(self):
        x = np.arange(0, self.h_x, self.del_x)
        y = np.arange(0, self.h_y, self.del_y)
        X, Y = plt.meshgrid(x, y)
        Z = self.u.reshape([self.x_div, self.y_div])

        fig = plt.figure()
        ax = Axes3D(fig)
        ax.set_xlabel('x')
        ax.set_ylabel('y')

        ax.plot_wireframe(X, Y, Z)

        plt.show()
Пример #18
0
def histogram2d(x, y, bins=10, range=None, normed=False, weights=None,
                log = False,
                filename = None,
                **formating):
    
    hist, x, y = numpy.histogram2d(x, y, bins, range, normed, weights)

    if log is True:
        hist = numpy.log(hist)
    
    X, Y = pylab.meshgrid(x,y)
    pylab.pcolor(X, Y,hist.transpose())
    pylab.colorbar()
    doFormating(**formating)
    pylab.show()
    if filename is not None:
        pylab.savefig(filename)
        pylab.clf()
Пример #19
0
def histogram2d(x, y, bins=10, range=None, normed=False, weights=None,
                log = False,
                filename = None,
                **formating):
    
    hist, x, y = numpy.histogram2d(x, y, bins, range, normed, weights)

    if log is True:
        hist = numpy.log(hist)
    
    X, Y = pylab.meshgrid(x,y)
    pylab.pcolor(X, Y,hist.transpose())
    pylab.colorbar()
    doFormating(**formating)
    pylab.show()
    if filename is not None:
        pylab.savefig(filename)
        pylab.clf()
Пример #20
0
def display_mobius_strip(u0, s0, s1, ds, solver=None, show=False):
    C = mobius_strip()  # Find the Christoffel tensor for mobius strip
    X = solve(C, u0, s0, s1, ds, solver)

    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    u, v = plt.meshgrid(np.linspace(-2 * np.pi, np.pi, 250),
                        np.linspace(-np.pi, np.pi, 250))
    x = (1 + np.cos(u / 2.) * v / 2.) * np.cos(u)
    y = (1 + np.cos(u / 2.) * v / 2.) * np.sin(u)
    z = np.sin(u / 2.) * v / 2.

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=10, azim=81)
    # use transparent colormap
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = -.5 * np.ones(theCM.N)
    theCM._lut[:-3, -1] = alphas
    ax.plot_surface(x, y, z, linewidth=0, cmap=theCM)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.hold('on')

    # plot the parametrized data on to the catenoid
    u, v = X[:, 0], X[:, 2]
    x = (1 + np.cos(u / 2.) * v / 2.) * np.cos(u)
    y = (1 + np.cos(u / 2.) * v / 2.) * np.sin(u)
    z = np.sin(u / 2.) * v / 2.

    ax.plot(x, y, z, '--r')
    s0_ = s0 / np.pi
    s1_ = s1 / np.pi
    fig.suptitle(
        "$s\in[%1.f,%1.f\pi]$ , $u = %.1f$ , $u' = %.1f$, $v = %.1f$ , $v' = %.1f$"
        % (s0, s1_, u0[0], u0[1], u0[2], u0[3]))
    if show == True:
        plt.show()
    return X, plt
Пример #21
0
def display_torus(u0, s0, s1, ds, a=1, c=2, solver=None, show=False):
    C = torus(a, c)  # Find the Christoffel tensor for the torus
    X = solve(C, u0, s0, s1, ds, solver)

    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    N = X[:, 0].shape[0]
    u, v = plt.meshgrid(np.linspace(0, 2 * np.pi, 250),
                        np.linspace(0, 2 * np.pi, 250))
    x = (c + a * np.cos(v)) * np.cos(u)
    y = (c + a * np.cos(v)) * np.sin(u)
    z = np.sin(v)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=-60, azim=100)
    # use transparent colormap -> negative
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = 2 * np.ones(theCM.N)
    theCM._lut[:-3, -1] = alphas
    ax.plot_surface(x, y, z, linewidth=0, cmap=theCM)
    plt.hold('on')

    # plot the parametrized data on to the torus
    u, v = X[:, 0], X[:, 2]
    x = (c + a * np.cos(v)) * np.cos(u)
    y = (c + a * np.cos(v)) * np.sin(u)
    z = np.sin(v)

    ax.plot(x, y, z, '--r')
    s1_ = s1 / pi
    fig.suptitle(
        "$s\in[%1.f,%1.f\pi]$ , $u = %.1f$ , $u' = %.1f$, $v = %.1f$ , $v' = %.1f$"
        % (s0, s1_, u0[0], u0[1], u0[2], u0[3]))
    if show == True:
        plt.show()
    return X, plt
Пример #22
0
def display_mobius_strip(u0,s0,s1,ds,solver=None,show=False):
    C = mobius_strip() # Find the Christoffel tensor for mobius strip
    X = solve(C,u0,s0,s1,ds,solver)

    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    u,v = plt.meshgrid(np.linspace(-2*np.pi,np.pi,250),np.linspace(-np.pi,np.pi,250))
    x = (1 + np.cos(u/2.)*v/2.)*np.cos(u)
    y = (1 + np.cos(u/2.)*v/2.)*np.sin(u)
    z = np.sin(u/2.)*v/2.

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=10, azim=81)
    # use transparent colormap
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = -.5*np.ones(theCM.N)
    theCM._lut[:-3,-1] = alphas
    ax.plot_surface(x,y,z,linewidth=0,cmap=theCM)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.hold('on')

    # plot the parametrized data on to the catenoid
    u,v = X[:,0], X[:,2]
    x = (1 + np.cos(u/2.)*v/2.)*np.cos(u)
    y = (1 + np.cos(u/2.)*v/2.)*np.sin(u)
    z = np.sin(u/2.)*v/2.

    ax.plot(x,y,z,'--r')
    s0_ = s0/np.pi
    s1_ = s1/np.pi
    fig.suptitle("$s\in[%1.f,%1.f\pi]$ , $u = %.1f$ , $u' = %.1f$, $v = %.1f$ , $v' = %.1f$"%(s0,s1_,u0[0],u0[1],u0[2],u0[3]))
    if show == True:
        plt.show()
    return X,plt
Пример #23
0
def display_catenoid(u0, s0, s1, ds, solver=None, show=False):
    C = catenoid()  # Find the Christoffel tensor for cylindrical catenoid
    X = solve(C, u0, s0, s1, ds, solver)

    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    N = X[:, 0].shape[0]
    u, v = plt.meshgrid(np.linspace(-np.pi, np.pi, 150),
                        np.linspace(-np.pi, np.pi, 150))
    x = np.cos(u) - v * np.sin(u)
    y = np.sin(u) + v * np.cos(u)
    z = v

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=20, azim=-163)
    # use transparent colormap
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = -.5 * np.ones(theCM.N)
    theCM._lut[:-3, -1] = alphas
    ax.plot_surface(x, y, z, linewidth=0, cmap=theCM)
    plt.hold('on')

    # plot the parametrized data on to the catenoid
    u, v = X[:, 0], X[:, 2]
    x = np.cos(u) - v * np.sin(u)
    y = np.sin(u) + v * np.cos(u)
    z = v

    ax.plot(x, y, z, '--r')
    s0_ = s0 / np.pi
    s1_ = s1 / np.pi
    fig.suptitle("$s\in[%.1f\pi,%.1f\pi]$ , $u' = %.1f$ , $v' = %.2f$" %
                 (s0_, s1_, u0[1], u0[3]))
    if show == True:
        plt.show()
    return X, plt
Пример #24
0
def display_egg_carton(u0, s0, s1, ds, solver=None, show=False):
    C = egg_carton()  # Find the Christoffel tensor for egg carton surface
    X = solve(C, u0, s0, s1, ds, solver)

    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    from math import pi
    N = X[:, 0].shape[0]
    u, v = plt.meshgrid(np.linspace(s0, s1, N), np.linspace(s0, s1, N))
    x = u
    y = v
    z = np.sin(u) * np.cos(v)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=90., azim=0)
    # use transparent colormap
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = -.5 * np.ones(theCM.N)
    theCM._lut[:-3, -1] = alphas
    ax.plot_surface(x, y, z, linewidth=0, cmap=theCM)
    plt.hold('on')

    # plot the parametrized data on to the egg carton
    u, v = X[:, 0], X[:, 2]
    x = u
    y = v
    z = np.sin(u) * np.cos(v)

    s0_ = s0 / pi
    s1_ = s1 / pi
    ax.plot(x, y, z, '--r')
    fig.suptitle('$s\in[%.1f\pi \, , \,%2.1f\pi]$' % (s0_, s1_))
    if show == True:
        plt.show()
    return X, plt
Пример #25
0
def display_sphere(u0, s0, s1, ds, solver=None, metric=None, show=False):
    if metric == 'flat':
        C = flat_sphere()
        if u0[0] == 0 or u0[2] == 0:
            print 'Division by zero may occur for provided values of u(s0) and v(s0)'
    else:
        C = sphere()
    X = solve(C, u0, s0, s1, ds, solver)
    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    u, v = plt.meshgrid(np.linspace(0, 2 * np.pi, 250),
                        np.linspace(0, 2 * np.pi, 250))
    x = np.cos(u) * np.cos(v)
    y = np.sin(u) * np.cos(v)
    z = np.sin(v)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    if metric == 'flat':
        ax.view_init(elev=90., azim=0)
    else:
        ax.view_init(elev=0., azim=13)
    ax.plot_surface(x, y, z, linewidth=0, cmap='Pastel1')
    plt.hold('on')
    # plot the parametrized data on to the sphere
    u, v = X[:, 0], X[:, 2]
    x = np.cos(u) * np.cos(v)
    y = np.sin(u) * np.cos(v)
    z = np.sin(v)

    ax.plot(x, y, z, '--r')
    from math import pi
    s1_ = s1 / pi
    fig.suptitle("$s\in[%1.f,%1.f\pi]$ , $u' = %.1f$ , $v' = %.1f$" %
                 (s0, s1_, u0[1], u0[3]))
    if show == True:
        plt.show()
    return X, plt
Пример #26
0
def display_egg_carton(u0,s0,s1,ds,solver=None,show=False):
    C = egg_carton() # Find the Christoffel tensor for egg carton surface
    X = solve(C,u0,s0,s1,ds,solver)

    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    from math import pi
    N = X[:,0].shape[0]
    u,v = plt.meshgrid(np.linspace(s0,s1,N),np.linspace(s0,s1,N))
    x = u
    y = v
    z = np.sin(u)*np.cos(v)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=90., azim=0)
    # use transparent colormap
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = -.5*np.ones(theCM.N)
    theCM._lut[:-3,-1] = alphas
    ax.plot_surface(x,y,z,linewidth=0,cmap=theCM)
    plt.hold('on')

    # plot the parametrized data on to the egg carton
    u,v = X[:,0], X[:,2]
    x = u
    y = v
    z = np.sin(u)*np.cos(v)

    s0_ = s0/pi
    s1_ = s1/pi
    ax.plot(x,y,z,'--r')
    fig.suptitle('$s\in[%.1f\pi \, , \,%2.1f\pi]$'%(s0_,s1_))
    if show == True:
        plt.show()
    return X,plt
Пример #27
0
def display_catenoid(u0,s0,s1,ds,solver=None,show=False):
    C = catenoid() # Find the Christoffel tensor for cylindrical catenoid
    X = solve(C,u0,s0,s1,ds,solver)

    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    N = X[:,0].shape[0]
    u,v = plt.meshgrid(np.linspace(-np.pi,np.pi,150),np.linspace(-np.pi,np.pi,150))
    x = np.cos(u) - v*np.sin(u)
    y = np.sin(u) + v*np.cos(u)
    z = v

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=20, azim=-163)
    # use transparent colormap
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = -.5*np.ones(theCM.N)
    theCM._lut[:-3,-1] = alphas
    ax.plot_surface(x,y,z,linewidth=0,cmap=theCM)
    plt.hold('on')

    # plot the parametrized data on to the catenoid
    u,v = X[:,0], X[:,2]
    x = np.cos(u) - v*np.sin(u)
    y = np.sin(u) + v*np.cos(u)
    z = v

    ax.plot(x,y,z,'--r')
    s0_ = s0/np.pi
    s1_ = s1/np.pi
    fig.suptitle("$s\in[%.1f\pi,%.1f\pi]$ , $u' = %.1f$ , $v' = %.2f$"%(s0_,s1_,u0[1],u0[3]))
    if show == True:
        plt.show()
    return X,plt
Пример #28
0
def display_sphere(u0,s0,s1,ds,solver=None,metric=None,show=False):
    if metric == 'flat':    
        C = flat_sphere()
        if u0[0] == 0 or u0[2] == 0:
            print 'Division by zero may occur for provided values of u(s0) and v(s0)'
    else:
        C = sphere()
    X = solve(C,u0,s0,s1,ds,solver)
    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    u,v = plt.meshgrid(np.linspace(0,2*np.pi,250),np.linspace(0,2*np.pi,250))
    x = np.cos(u)*np.cos(v)
    y = np.sin(u)*np.cos(v)
    z = np.sin(v)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    if metric == 'flat':
        ax.view_init(elev=90., azim=0)
    else:
        ax.view_init(elev=0., azim=13)
    ax.plot_surface(x,y,z,linewidth=0,cmap='Pastel1')
    plt.hold('on')
    # plot the parametrized data on to the sphere
    u,v = X[:,0], X[:,2]
    x = np.cos(u)*np.cos(v)
    y = np.sin(u)*np.cos(v)
    z = np.sin(v)

    ax.plot(x,y,z,'--r')
    from math import pi
    s1_ = s1/pi
    fig.suptitle("$s\in[%1.f,%1.f\pi]$ , $u' = %.1f$ , $v' = %.1f$"%(s0,s1_,u0[1],u0[3]))
    if show == True:
        plt.show()
    return X,plt
Пример #29
0
def display_torus(u0,s0,s1,ds,a=1,c=2,solver=None,show=False):
    C = torus(a,c) # Find the Christoffel tensor for the torus
    X = solve(C,u0,s0,s1,ds,solver)

    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    N = X[:,0].shape[0]
    u,v = plt.meshgrid(np.linspace(0,2*np.pi,250),np.linspace(0,2*np.pi,250))
    x = (c + a*np.cos(v))*np.cos(u)
    y = (c + a*np.cos(v))*np.sin(u)
    z = np.sin(v)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=-60, azim=100)
    # use transparent colormap -> negative
    import matplotlib.cm as cm
    theCM = cm.get_cmap()
    theCM._init()
    alphas = 2*np.ones(theCM.N)
    theCM._lut[:-3,-1] = alphas
    ax.plot_surface(x,y,z,linewidth=0,cmap=theCM)
    plt.hold('on')

    # plot the parametrized data on to the torus
    u,v = X[:,0], X[:,2]
    x = (c + a*np.cos(v))*np.cos(u)
    y = (c + a*np.cos(v))*np.sin(u)
    z = np.sin(v)

    ax.plot(x,y,z,'--r')
    s1_ = s1/pi
    fig.suptitle("$s\in[%1.f,%1.f\pi]$ , $u = %.1f$ , $u' = %.1f$, $v = %.1f$ , $v' = %.1f$"%(s0,s1_,u0[0],u0[1],u0[2],u0[3]))
    if show == True:
        plt.show() 
    return X,plt
Пример #30
0
def plot(V, title, save_name, elev=20., azim=30.):
    #Get X,Y range
    NXmax, NYmax = V.shape
    x = range(0, NXmax-1, 1)
    y = range(0, NYmax-1, 1)
    X, Y = p.meshgrid(x,y)#Make grid
    def functz(V):#Make Z for plotting
        z = V[X,Y]
        return z
    Z = functz(V)
    fig = p.figure()#Make new fig
    ax = Axes3D(fig)
    #Plot fewer lines
    xstride, ystride = floor(max(x)/20), floor(max(y)/20)
    ax.plot_wireframe(X, Y, Z, rstride=xstride, \
        cstride=ystride, color = 'r')
    ax.set_xlabel('X'); ax.set_ylabel('Y')
    ax.set_zlabel('Potential, V(x,y)')
    ax.set_xlim(0,max(x)); ax.set_ylim(0,max(y))
    ax.set_title(title)
    ax.contourf(X,Y,Z,11,stride=25,offset=min(Z))
    ax.view_init(elev=elev, azim=azim)
    p.savefig('figures/%s.png'%save_name,bbox_inches='tight')
    print("Finished %s (%s.png)" % (title, save_name))
Пример #31
0
def plotSQE(sqe,viewDirectory,filename,title="S(Q,E)",lower=False,\
                                                      upper=False,TextSize=16):

  pylab.clf()
  pylab.axes( (0.15, 0.1, 0.8, 0.8 ) )
  
  if upper:
    for q in range(len(sqe.q)):
      for e in range(len(sqe.e)):
        if sqe.sqe[q,e] > upper:
          sqe.sqe[q,e] = upper
  if lower:
    for q in range(len(sqe.q)):
      for e in range(len(sqe.e)):
        if sqe.sqe[q,e] < lower:
          sqe.sqe[q,e] = lower
  myfile = os.path.join(viewDirectory,filename)

  
  x = sqe.q; y = sqe.e; z = numpy.transpose(sqe.sqe)
  X,Y = pylab.meshgrid(x,y)
  image = pylab.pcolor( X,Y, z, shading="flat")

  ylabel = "E [meV]"
  xlabel = "Q [1/Angstroms]"

  pylab.xlim( x[0], x[-1] )
  pylab.ylim( y[0], y[-1] )
  
  pylab.xlabel( xlabel )
  pylab.ylabel( ylabel )
  pylab.title( title )
  pylab.colorbar()

  pylab.savefig( myfile )
  return
Пример #32
0
    T = np.column_stack([np.ones(x.size), x.reshape(x.size), y.reshape(y.size)])
    T = feature_extend(T)
    return predict_log_reg(T, theta).reshape(x.shape)


if __name__ == "__main__":
    data = Orange.data.Table("data/data-quad.tab")
    X, y, _ = data.to_numpy()
    m = X.shape[0]
    n = X.shape[1]
    X = np.column_stack([np.ones(m), X])
    X = feature_extend(X)
    
    theta, j_hist = batch_log_reg(X, y, alpha=0.1, theta=np.zeros(X.shape[1]), max_iterations=10000)
    print "Grad desc:", theta
    
    plt.close()
    grid = 30
    x1 = np.linspace(min(X[:,1]), max(X[:,1]), grid)
    x2 = np.linspace(min(X[:,2]), max(X[:,2]), grid)
    X1, X2 = meshgrid(x1, x2)
    
    Z = test_mesh(X1, X2, theta)
    plt.pcolor(X1, X2, Z) # plt.cm.gray
    
    plt.scatter(X[:,1], X[:,2], c=["y" if yi else "b" for yi in y])
    plt.xlabel("x1")
    plt.ylabel("x2")
    plt.title("Logistic regression with non-linear decision boundary")
    plt.savefig("0.pdf")
Пример #33
0
from numpy import ma
import os

# ----------------------------------------
# Extraindo as variaveis da saida do Hycom
# Grade 1/24°
print('------------------------------')
print(' Extraindo variáveis do HYCOM ')
print('------------------------------')

DIR = '/mnt/nfs/dpns32/data1/operador/previsao/hycom_2_2/hycom2netcdf/Ncdf/'
nc_f=DIR+'HYCOM_1_24_'+datai+'_'+dataf+'.nc'
nc_fid=Dataset(nc_f, 'r')
lat=nc_fid.variables['Latitude'][:]
lon=nc_fid.variables['Longitude'][:]
lons,lats=plab.meshgrid(lon,lat)
lat_s=float(lat_sul)
lat_n=float(lat_norte)
lat_media=-((-lat_s)+(-lat_n))/2
lat_media=str(lat_media)
u=nc_fid.variables['u_velocity'][:]
v=nc_fid.variables['v_velocity'][:]
u=np.squeeze(u);v=np.squeeze(v)
u0=np.copy(u); v0=np.copy(v)  

# Criando arrays de datas e prog para as figuras
tit_horas=['00','03','06','09','12','15','18','21']
titfig=[]
for ttt in range(0,numdays,1):
   aux=date_list[ttt]
   dt=aux.strftime('%Y%m%d')
Пример #34
0
def imageMap(lons, lats, vals, vmin=None, vmax=None, 
             imageWidth=None, imageHeight=None, outFile=None,
             projection='cyl', cmap=M.cm.jet, makeFigure=False,
             borders=[0., -90., 360., 90.], autoBorders=True, borderSlop=10.,
             meridians=[0, 360, 60], parallels=[-60, 90, 30],
             **options
             ):
    lons = normalizeLons(lons)
    if vmin == 'auto': vmin = None
    if vmax == 'auto': vmax = None
    if imageWidth is not None: makeFigure = True
    if projection is None or projection == '': projection = 'cyl'
    if cmap is None or cmap == '': cmap = M.cm.jet
    if isinstance(cmap, bytes) and cmap != '':
        try:
            cmap = eval('M.cm.' + cmap)
        except:
            cmap = M.cm.jet

#    ensureItems(options, {'xlabel': 'Longitude (deg)', 'ylabel': 'Latitude (deg)', \
    ensureItems(options, { \
                     'title': 'An Image Map', 'dpi': 100,
                     'imageWidth': imageWidth or 1024, 'imageHeight': imageHeight or 768})
    if autoBorders:
        borders = [min(lons), min(lats), max(lons), max(lats)]
        borders = roundBorders(borders, borderSlop)

    m = Basemap(borders[0], borders[1], borders[2], borders[3], \
                projection=projection, lon_0=N.average([lons[0], lons[-1]]))

    if makeFigure:
        dpi = float(options['dpi'])
        width = float(imageWidth) / dpi
        if imageHeight is None:
            height = width * m.aspect
        else:
            height = float(imageHeight) / dpi
        f = M.figure(figsize=(width,height)).add_axes([0.1,0.1,0.8,0.8], frameon=True)

    if vmin is not None or vmax is not None: 
        if vmin is None:
            vmin = min(vals)
        else:
            vmin = float(vmin)
        if vmax is None:
            vmax = max(vals)
        else:
            vmax = float(vmax)
        vrange = (vmax - vmin) / 255.
        levels = N.arange(vmin, vmax, vrange/30.)
    else:
        levels = 30

    x, y = m(*M.meshgrid(lons,lats))
    c = m.contourf(x, y, vals, levels, cmap=cmap, colors=None)

    m.drawcoastlines()
    m.drawmeridians(list(range(meridians[0], meridians[1], meridians[2])), labels=[0,0,0,1])
    m.drawparallels(list(range(parallels[0], parallels[1], parallels[2])), labels=[1,1,1,1])
    M.colorbar(c)
    evalKeywordCmds(options)
    if outFile:
        M.savefig(outFile, **validCmdOptions(options, 'savefig'))
Пример #35
0
def display_multiple_geodesics(u0,s0,s1,ds,surface,with_object=True):
    import matplotlib.pylab as plt
    from mpl_toolkits.mplot3d import Axes3D
    def solve_multiple(C,u0,s0,s1,ds,s):
        from sympy.abc import u,v
        print 'Running solver...'
        return sc.odeint(f,u0,s,args=(C,u,v))
    
    def display_multiple_catenoid(u0,s0,s1,ds,C,s):
        X = solve_multiple(C,u0,s0,s1,ds,s)
        plt.hold('on')
        # plot the parametrized data on to the catenoid
        u,v = X[:,0], X[:,2]
        x = np.cos(u) - v*np.sin(u)
        y = np.sin(u) + v*np.cos(u)
        z = v
        ax.plot(x,y,z,'--r')
        return plt

    def display_multiple_egg_carton(u0,s0,s1,ds,C,s):
        X = solve_multiple(C,u0,s0,s1,ds,s)
        plt.hold('on')
        # plot the parametrized data on to the egg carton
        u,v = X[:,0], X[:,2]
        x = u
        y = v
        z = np.sin(u)*np.cos(v)
        ax.plot(x,y,z,'--r')
        return plt

    def display_multiple_sphere(u0,s0,s1,ds,C,s):
        X = solve_multiple(C,u0,s0,s1,ds,s)
        plt.hold('on')
        # plot the parametrized data on to the sphere
        u,v = X[:,0], X[:,2]
        x = np.cos(u)*np.cos(v)
        y = np.sin(u)*np.cos(v)
        z = np.sin(v)
        ax.plot(x,y,z,'--r')
        return plt

    def display_multiple_torus(u0,s0,s1,ds,C,s):
        X = solve_multiple(C,u0,s0,s1,ds,s)
        plt.hold('on')
        # plot the parametrized data on to the sphere
        u,v = X[:,0], X[:,2]
        x = (2 + 1*np.cos(v))*np.cos(u)
        y = (2 + 1*np.cos(v))*np.sin(u)
        z = np.sin(v)
        ax.plot(x,y,z,'--r')
        return plt

    u0_range = np.arange(s0,s1+ds,ds)
    N = u0_range.shape[0]
        
    fig = plt.figure()
    if surface == 'catenoid':
        if with_object:
            u,v = plt.meshgrid(np.linspace(-np.pi,np.pi,150),np.linspace(-np.pi,np.pi,150))
            x = np.cos(u) - v*np.sin(u)
            y = np.sin(u) + v*np.cos(u)
            z = v
        C = catenoid()
    elif surface == 'egg_carton':
        if with_object:
            u,v = plt.meshgrid(np.linspace(-4,4,250),np.linspace(-4,4,250))
            x = u
            y = v
            z = np.sin(u)*np.cos(v)
        C = egg_carton()
    elif surface == 'sphere':
        if with_object:
            u,v = plt.meshgrid(np.linspace(0,2*np.pi,250),np.linspace(0,2*np.pi,250))
            x = np.cos(u)*np.cos(v)
            y = np.sin(u)*np.cos(v)
            z = np.sin(v)
        C = sphere()
    elif surface == 'torus':
        if with_object:
            u,v = plt.meshgrid(np.linspace(0,2*np.pi,150),np.linspace(0,2*np.pi,150))
            x = (2 + 1*np.cos(v))*np.cos(u)
            y = (2 + 1*np.cos(v))*np.sin(u)
            z = np.sin(v)
        C = torus()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(azim=65, elev=67)
    if with_object:
        theCM = 'Pastel1'
        ax.plot_surface(x,y,z,linewidth=0,cmap=theCM)
    plt.hold('on')

    if surface == 'catenoid':
        for u_val in u0_range:
            u0[3] = u_val
            plt = display_multiple_catenoid(u0,s0,s1,ds,C,u0_range)
    elif surface == 'egg_carton':
        for u_val in u0_range:
            u0[0] = u_val
            plt = display_multiple_egg_carton(u0,s0,s1,ds,C,u0_range)
    elif surface == 'sphere':
        for u_val in u0_range:
            u0[0] = u_val
            plt = display_multiple_sphere(u0,s0,s1,ds,C,u0_range)
    elif surface == 'torus':
        for u_val in u0_range:
            u0[0] = u_val # alternate v0 values
            plt = display_multiple_torus(u0,s0,s1,ds,C,u0_range)
            

    from math import pi
    s0_ = s0#/pi
    s1_ = s1/pi
    fig.suptitle("$s\in[%1.f,%1.f\pi]$ , $u' = %.1f$ , $v = %.1f$ , $v' = %.1f$"%(s0_,s1_,u0[1],u0[2],u0[3]))
    plt.show()
def sub_lba_dist(lists_action, lists_cmd, options):

    # Local Variables: plot_fontsize, lists_action, i, idx_write, save_figure, lba_size_set, stat_record, idx_read, section_name, X, y, x, plot_figure, lba_stat_array, options, Y, lists_cmd
    # Function calls: subplot, plot, lba_size_dist, set, gcf, figure, title, zlabel, isfield, findall, mesh, sub_lba_dist, colorbar, meshgrid, xlabel, ylabel, generate_ppt, saveas, isempty, find
    #% stat_record=sub_lba_dist(lists_action,lists_cmd,options)
    #% --> calcuate the size distribution
    #% inputs
    #%   lists_action: n samples x 2 array for arrival time and completion time;
    #%   lists_cmd: n samples x 3 for LBA, size, flags ( (0 write, 1 read))
    #%   access_type: 0 write, 1 read, 2 all
    #%   options: control parameters
    #%       lba_size_set: how many LBA range sets
    #%
    #% outputs
    #%   lba_stat_array: cells structure; LBA statistics for write/read/all
    #%
    #% contact [email protected] for questions

    if hasattr(options, 'plot_fontsize'):
        plot_fontsize = options.plot_fontsize
    else:
        plot_fontsize = 10

    if hasattr(options, 'save_figure'):
        save_figure = options.save_figure
    else:
        save_figure = 1

    if hasattr(options, 'plot_figure'):
        plot_figure = options.plot_figure
    else:
        plot_figure = 1

    if hasattr(options, 'lba_size_set'):
        lba_size_set = options.lba_size_set
    else:
        options.lba_size_set = 50

    plot_figure = options.plot_figure

    #%5: LBA vs time;
    if plot_figure == 1:
        idx_read = np.nonzero((lists_cmd[:, 2] == 1))
        idx_write = np.nonzero((lists_cmd[:, 2] == 0))
        plt.figure
        plt.subplot(2., 1., 1.)
        plt.plot(lists_action[(idx_read), 0],
                 lists_cmd[(idx_read), 0],
                 'r*',
                 markersize=1)
        plt.ylabel('LBA')
        plt.title('read')
        plt.subplot(2., 1., 2.)
        plt.plot(lists_action[(idx_write), 0],
                 lists_cmd[(idx_write), 0],
                 'b+',
                 markersize=1)
        plt.ylabel('LBA')
        plt.xlabel('time (s)')
        plt.title('write')
        plt.savefig('lba_all.eps')
        plt.savefig('lba_all.jpg')

    lba_stat_array = []
    for i in np.arange(3):

        print(i)
        stat_record = lba_size_dist2(lists_cmd, i, options)

        if plot_figure == 1:
            x = np.arange(1, 1025)
            y = stat_record.lba_size_idx
            if len(y) <= 1:
                continue
            fig = plt.figure()
            ax = Axes3D(fig)
            [X, Y] = plt.meshgrid(x, y)
            ax.plot_surface(X, Y, (stat_record.lba_size_dist))
            plt.set_cmap('hot')

            ax.set_ylabel('LBA Range')
            ax.set_xlabel('Request size')
            ax.set_zlabel('Frequency')

            if i == 0.:
                ax.set_title('LBA & Size Disribution - Write ')
            elif i == 1.:
                ax.set_title('LBA & Size Disribution - Read ')

            else:
                ax.set_title('LBA & Size Disribution - Combined ')

            # set((plt.gcf, '-property', 'FontSize'), 'FontSize', plot_fontsize)
            # plt.grid()
            if i == 1:
                plt.savefig('lba_size_freq_read.eps', format="eps")
                plt.savefig('lba_size_freq_read.jpg')
            elif i == 0:
                plt.savefig('lba_size_freq_write.eps', format="eps")
                plt.savefig('lba_size_freq_write.jpg')

            else:
                plt.savefig('lba_size_freq_com.eps', format="eps")
                plt.savefig('lba_size_freq_com.jpg')

            plt.show()

        lba_stat_array.append(stat_record)

#    if options.export_report:
#        options.section_name = 'LBA Distribution'
#        generate_ppt(options)

    return lba_stat_array
Пример #37
0
def visualize(self):
    if self.log == 1:
        f = open('calc.log','w')
        f.close()
        configure_output("calc.log")
    x_1 = float(self.coor1_x.GetValue())
    y_1 = float(self.coor1_y.GetValue())
    z_1 = float(self.coor1_z.GetValue())
    x_2 = float(self.coor2_x.GetValue())
    y_2 = float(self.coor2_y.GetValue())
    z_2 = float(self.coor2_z.GetValue())
    z_pos = float(self.z_pos.GetValue())
    mol = Molecule('h2',[(self.atom_no_1,(y_1,x_1,z_1)),
                          (self.atom_no_2,(y_2,x_2,z_2))],
                   units='Angstrom')
    bf_name = self.Bf_box.GetValue()
    
        #Why?
    if bf_name == "sto-3g":
        bf_name = "sto-3g"
    elif bf_name == "6-31g":
        bf_name = "6-31g"
    elif bf_name == "3-21g":
        bf_name = "3-21g"
    elif bf_name == "6-31g**":
        bf_name = "6-31g**"
    elif bf_name == "6-31g**++":
        bf_name = "6-31g**++"
    elif bf_name == "6-311g**":
        bf_name = "6-311g**"
    elif bf_name == "6-311g++(2d,2p)":
        bf_name = "6-311g++(2d,2p)"
    elif bf_name == "6-311g++(3d,3p)":
        bf_name = "6-311g++(3d,3p)"
    elif bf_name == "6-311g++(3df,3pd)":
        bf_name = "6-311g++(3df,3pd)"
    elif bf_name == "sto-6g":
        bf_name = "sto-6g"
    elif bf_name == "lacvp":
        bf_name = "lacvp"
    elif bf_name == "cc-pvdz":
        bf_name = "cc-pvdz"
    elif bf_name == "cc-pvtz":
        bf_name = "cc-pvtz"
    elif bf_name == "dzvp":
        bf_name = "dzvp"
        
    en,orbe,orbs = rhf(mol,basis_data=bf_name)
    self.console_box.SetValue('energy=%f' % en)

    bfs = getbasis(mol,bf_name)

    delta = 0.1
    c_range = 5.0
#setting for visualize
    x = np.arange(-1*c_range,c_range,delta)
    y = np.arange(-1*c_range,c_range,delta)
    X,Y = p.meshgrid(x,y)
    Z = np.zeros((len(X),len(Y)))
    Z_2 = np.zeros((len(X),len(Y)))
    
#print C matrix
#print "C=",orbs

    #bounding = self.orb_bound_box.GetValue()
        
#calculate wave function
    for k,bf in enumerate(bfs.bfs):
        for i,x1 in enumerate(x):
            for j,y1 in enumerate(y):
            #calculate wave function
            #basic function multiply
                #if bounding == "boundary":
                Z[i,j] += bf.amp(x1,y1,z_pos) * orbs[k,0]
                #else:
                #    Z[i,j] += bf.amp(x1,y1,z_pos) * orbs[k,1]

    if self.log == 1:
        with open('calc.log','a') as f_handle:
            f_handle.write("\norbs is\n")
            np.savetxt(f_handle,orbs)
            f_handle.write("\norbe is\n")
            np.savetxt(f_handle,orbe)
                    
#####  visualize #####
    fig = p.figure()
    ax = Axes3D(fig)
    #ax.plot_surface(X,Y,Z)
    ax.plot_wireframe(X,Y,Z,color = 'b')
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    p.show()
        print('Esperando o ww3 terminar em alguma máquina')
        time.sleep(60)

# ---------------------
# Definindo Diretorios
savedir = '/home/operador/ondogramas/ww3_418/ww3' + mod + '/ww3ant' + str(
    cyc) + '/'
savedir2 = '/home/operador/grads/produtos_operantar/' + str(cyc) + 'hmg/'

# ----------------------------------------
# Extraindo as variaveis da saida do WW3
nc_fid = Dataset(nc_f, 'r')
lat = nc_fid.variables['latitude'][:]
lon = nc_fid.variables['longitude'][:]
lon = lon - 360
lon_grid, lat_grid = plab.meshgrid(lon, lat)
grid = pr.geometry.GridDefinition(lats=lat_grid, lons=lon_grid)
hs = nc_fid.variables['hs'][:]
dire = nc_fid.variables['dir'][:]
dp = nc_fid.variables['dp'][:]
u_wnd = nc_fid.variables['uwnd'][:]
v_wnd = nc_fid.variables['vwnd'][:]
prg = np.size(u_wnd)
freqpeak = nc_fid.variables['fp'][:]  #wave peak frequency
perpeak = 1 / freqpeak

# Pontos Derrota Ilhas Órcades:
lat_pd = [-62.50, -62.167, -61.833, -61.50, -61.167, -60.833, -60.50]
lon_pd = [-58.00, -56.00, -54.00, -52.00, -50.00, -48.00, -46.00]

swath = pr.geometry.SwathDefinition(lons=lon_pd, lats=lat_pd)
Пример #39
0
def jointplot(X,Y,xlabel=None,ylabel=None,binsim=40,binsh=20,contour=True):
	"""
Plots the joint distribution of posteriors for X1 and X2, including the 1D
histograms showing the median and standard deviations.

The work that went in creating this nice method is shown, step by step, in 
the ipython notebook "error contours.ipynb". Sources of inspiration:

- http://python4mpia.github.io/intro/quick-tour.html
- http://stackoverflow.com/questions/12301071/multidimensional-confidence-intervals

Usage:

>>> jointplot(M.rtr.trace(),M.mdot.trace(),xlabel='$\log \ r_{\\rm tr}$', ylabel='$\log \ \dot{m}$')

gives the following plot.

.. figure:: ../figures/jointplot.png
   :scale: 100 %
   :alt: Two-dimensional kernel density distribution.

   Two-dimensional kernel density distribution, along with one-dimensional histograms of each distribution.
	"""
	import scipy.stats

	# Generates 2D histogram for image
	histt, xt, yt = numpy.histogram2d(X, Y, bins=[binsim,binsim], normed=False)
	histt = numpy.transpose(histt)  # Beware: numpy switches axes, so switch back.

	# assigns correct proportions to subplots
	fig=pylab.figure()
	gs = pylab.GridSpec(2, 2, width_ratios=[3,1], height_ratios=[1,3], wspace=0.001, hspace=0.001)
	con=pylab.subplot(gs[2])
	histx=pylab.subplot(gs[0], sharex=con)
	histy=pylab.subplot(gs[3], sharey=con)
		
	# Image
	con.imshow(histt,extent=[xt[0],xt[-1], yt[0],yt[-1]],origin='lower',cmap=pylab.cm.gray_r,aspect='auto')

	# Overplot with error contours 1,2 sigma
	if contour==True:
		pdf = scipy.stats.gaussian_kde([X, Y])
		x,y = pylab.meshgrid(xt,yt)
		z = numpy.array(pdf.evaluate([x.flatten(),y.flatten()])).reshape(x.shape)
		# the [61,15] values were obtained by trial and error until the joint confidence 
		# contours matched the confidence intervals from the individual X,Y
		s=scipy.stats.scoreatpercentile(pdf(pdf.resample(1000)), [61,15])
		cs=con.contour(x,y,z, levels=s, extent=[x[0],x[-1], y[0],y[-1]], linestyles=['-','-','-'], colors=['black','blue'])
		# use dictionary in order to assign your own labels to the contours.
		#fmtdict = {s[0]:r'$1\sigma$',s[1]:r'$2\sigma$'}
		#con.clabel(cs, fmt=fmtdict, inline=True, fontsize=20)
		if xlabel!=None: con.set_xlabel(xlabel)
		if ylabel!=None: con.set_ylabel(ylabel)

	# X-axis histogram
	histx.hist(X, binsh, histtype='stepfilled',facecolor='lightblue')
	pylab.setp(histx.get_xticklabels(), visible=False)	# no X label
	pylab.setp(histx.get_yticklabels(), visible=False)	# no Y label
	# Vertical lines with median and 1sigma confidence
	yax=histx.set_ylim()
	histx.plot([numpy.median(X),numpy.median(X)],[yax[0],yax[1]],'k-',linewidth=2) # median
	xsd=scipy.stats.scoreatpercentile(X, [15.87,84.13])
	histx.plot([xsd[0],xsd[0]],[yax[0],yax[1]],'k--') # -1sd
	histx.plot([xsd[-1],xsd[-1]],[yax[0],yax[1]],'k--') # +1sd

	# Y-axis histogram
	histy.hist(Y, binsh, histtype='stepfilled', orientation='horizontal',facecolor='lightyellow')
	pylab.setp(histy.get_yticklabels(), visible=False)	# no Y label
	pylab.setp(histy.get_xticklabels(), visible=False)	# no X label
	# Vertical lines with median and 1sigma confidence
	xax=histy.set_xlim()
	histy.plot([xax[0],xax[1]],[numpy.median(Y),numpy.median(Y)],'k-',linewidth=2) # median
	ysd=scipy.stats.scoreatpercentile(Y, [15.87,84.13])
	histy.plot([xax[0],xax[1]],[ysd[0],ysd[0]],'k--') # -1sd
	histy.plot([xax[0],xax[1]],[ysd[-1],ysd[-1]],'k--') # +1sd
Пример #40
0
#Synaptic parameters, corresponding to a NetCon synapse built into NEURON
synapseParameters = {
    'idx' : 0,               # insert synapse on index "0", the soma
    'e' : 0.,                # reversal potential of synapse
    'syntype' : 'Exp2Syn',   # conductance based double-exponential synapse
    'tau1' : 1.0,            # Time constant, rise
    'tau2' : 1.0,            # Time constant, decay
    'weight' : 0.05,         # Synaptic weight
    'record_current' : True, # Will enable synapse current recording
}

#Generate the grid in xz-plane over which we calculate local field potentials
x = pl.linspace(-50, 50, 11)
z = pl.linspace(-50, 50, 11)
X, Z = pl.meshgrid(x, z)
y = pl.zeros(X.size)

#define parameters for extracellular recording electrode, using optional method
electrodeParameters = {
    'sigma' : 0.3,              # extracellular conductivity
    'x' : X.reshape(-1),        # x,y,z-coordinates of contact points
    'y' : y,
    'z' : Z.reshape(-1),
    'method' : 'som_as_point',  #treat soma segment as sphere source
}

################################################################################
# Main simulation procedure, setting up extracellular electrode, cell, synapse
################################################################################
Пример #41
0
def plot_chi2(model, data, fit_result=None, limits=None,
              disregard_correlation=False,
              npoints=(100, 100), stddev_max=3, fmt='%d',
              linewidth=2):
    """Plot chi**2 contours and linear fit approxiation

    Note that chi**2 is related to likelihood in the following way:
    L = exp(-(1/2)*chi**2)
    This means that log(L) and chi**2 are identical up to a factor (-2).
    """
    import matplotlib.pylab as plt
    # Unpack model and fit result
    f, p, c = model
    # popt, pcov

    if disregard_correlation:
        fit_result[1] = set_off_diagonal_to_zero(fit_result[1])

    # If no limits are given, compute a good choice from fit_result

    # Set up a grid of points in parameter space
    p1_lim = limits[0]
    p2_lim = limits[1]
    p1 = np.linspace(p1_lim[0], p1_lim[1], npoints[0])
    p2 = np.linspace(p2_lim[0], p2_lim[1], npoints[1])
    P1, P2 = plt.meshgrid(p1, p2)

    # Compute chi**2 (called chi2) for each grid point
    # Looping can probably be avoided, but I don't know how.
    x2 = np.empty_like(P1)  # real chi**2
    x2lin = np.empty_like(P1)  # linear chi**2 approximation
    for i1 in range(p1.size):
        for i2 in range(p2.size):
            # Note the weird numpy indexing order.
            # i2,i1 seems wrong, but is correct:
            # TODO: implement
            pass
            # x2   [i2, i1] = chi2    ((p1[i1], p2[i2]), c, f, data)
            # x2lin[i2, i1] = chi2_lin((p1[i1], p2[i2]), fit_result)

    # Set the most likely point to chi**2 = 0
    x2 -= x2.min()

    # Use sqrt scale
    # x2 = np.sqrt(x2)
    # x2lin = np.sqrt(x2lin)

    # Plot likelihood as color landscape
    x2_image = plt.pcolor(P1, P2, x2, vmin=0,
                          vmax=stddev_max ** 2, cmap='gray')
    plt.colorbar()
    # Add marker at the minimum
    plt.plot(fit_result[0][0], fit_result[0][1],
            marker='*', markersize=12, color='r')

    # Add contour of real likelihood
    contour_levels = np.arange(1, stddev_max + 1) ** 2
    x2_cont = plt.contour(P1, P2, x2, contour_levels,
                         colors='r', linewidths=linewidth)
    plt.clabel(x2_cont, inline=1, fontsize=10,
               linewidths=linewidth, fmt=fmt)

    # Overplot linear approximation as contours
    x2lin_cont = plt.contour(P1, P2, x2lin, contour_levels,
                             colors='b', linewidths=linewidth)
    plt.clabel(x2lin_cont, inline=1, fontsize=10,
               linewidths=linewidth, fmt=fmt)

    # Add colorbar and labels
    # axcb = plt.colorbar()
    # axcb.set_label(r'$\chi^2$', size=15)
    plt.xlabel('Parameter P1')
    plt.ylabel('Parameter P2')
    plt.axis(p1_lim + p2_lim)
Пример #42
0
    def show(
        self,
        typ="s1",
        k=0,
        N=-1,
        M=-1,
        kmax=1000,
        seuildb=50,
        titre="SHC",
        xl=True,
        yl=True,
        fontsize=14,
        dB=True,
        cmap=plt.cm.hot_r,
        anim=True,
    ):
        """ show coeff

        Parameters
        ----------
        typ :  string 
            default ('s1')
            's1'  shape 1  (Nf , N , M )
            's2'  shape 2  (Nf , N*M   )
            's3'  shape 3  (Nf , K )  T ( K x 2 )

        k  : integer 
            frequency index default 0

        N, M = maximal value for degree, mode respectively
        (not to be defined if 's2' or 's3')

        """

        fa = np.linspace(self.fmin, self.fmax, self.Nf)
        if typ == "s1":
            if N == -1:
                N = self.N1
            if M == -1:
                M = self.M1
            Mg, Ng = plt.meshgrid(np.arange(M), np.arange(N))
            if anim:
                fig = plt.gcf()
                ax = fig.gca()
                v = np.abs(self.s1[k, 0:N, 0:M])
                if dB:
                    v = 20 * np.log10(v)
                p = plt.scatter(Mg, Ng, c=v, s=30, cmap=cmap, linewidth=0, vmin=-seuildb, vmax=0)
                plt.colorbar()
                plt.draw()
            else:
                v = np.abs(self.s1[k, 0:N, 0:M])
                if dB:
                    vdB = 20 * np.log10(v + 1e-15)
                    plt.scatter(Mg, Ng, c=vdB, s=30, cmap=cmap, linewidth=0, vmin=-seuildb, vmax=0)
                    plt.title(titre)
                    plt.colorbar()
                else:
                    plt.scatter(Mg, Ng, c=v, s=30, cmap=cmap, linewidth=0)
                    plt.title(titre)
                    plt.colorbar()

                if xl:
                    plt.xlabel("m", fontsize=fontsize)
                if yl:
                    plt.ylabel("n", fontsize=fontsize)

        if typ == "s2":
            if np.shape(self.s2)[1] <= 1:
                plt.plot(fa, 10 * np.log10(abs(self.s2[:, 0])))
            else:
                K = np.shape(self.s2)[1]

            kmax = min(kmax, K)
            db = 20 * np.log10(abs(self.s2[:, 0:kmax] + 1e-15))
            col = 1 - (db > -seuildb) * (db + seuildb) / seuildb
            #
            # gray
            #
            # pcolor(np.arange(K+1)[0:kmax],self.fa,col,cmap=cm.gray_r,vmin=0.0,vmax=1.0)
            #
            # color
            #
            plt.pcolor(np.arange(K + 1)[0:kmax], fa, col, cmap=plt.cm.hot, vmin=0.0, vmax=1.0)
            if xl:
                plt.xlabel("index", fontsize=fontsize)
            if yl:
                plt.ylabel("Frequency (GHz)", fontsize=fontsize)

        if typ == "s3":
            if np.shape(self.s3)[1] <= 1:
                plt.plot(fa, 10 * np.log10(abs(self.s3[:, 0])))
            else:
                K = np.shape(self.s3)[1]

            kmax = min(kmax, K)
            db = 20 * np.log10(abs(self.s3[:, 0:kmax] + 1e-15))
            col = 1 - (db > -seuildb) * (db + seuildb) / seuildb
            plt.pcolor(np.arange(K + 1)[0:kmax], fa, col, cmap=plt.cm.hot, vmin=0.0, vmax=1.0)
            if xl:
                plt.xlabel("index", fontsize=fontsize)
            if yl:
                plt.ylabel("Frequency (GHz)", fontsize=fontsize)

                # echelle=[str(0), str(-10), str(-20), str(-30), str(-40), str(-50)]
        if (typ == "s2") | (typ == "s3"):

            echelle = [
                str(0),
                str(-seuildb + 40),
                str(-seuildb + 30),
                str(-seuildb + 20),
                str(-seuildb + 10),
                str(-seuildb),
            ]
            cbar = plt.colorbar(ticks=[0, 0.2, 0.4, 0.6, 0.8, 1])
            cbar.ax.set_yticklabels(echelle)
            cbar.ax.set_ylim(1, 0)
            for t in cbar.ax.get_yticklabels():
                t.set_fontsize(fontsize)
            plt.xticks(fontsize=fontsize)
            plt.yticks(fontsize=fontsize)
            plt.title(titre, fontsize=fontsize + 2)
Пример #43
0
    x0 = -0.5
    for j in range(0,100):
        x = x0+j*0.01
        eps = 0.006
        if (y <= sq3*(x+0.25) and x<0.) or (y<-sq3*(x-0.25) and x >= 0):
            grid[i,j] =  0
        else: if(y <= sq3/4. + 0.01): V[i,j] = 0.0 # Triangle tip 
for iter in range(1,Niter):                          # Iterate
     if(iter%50 == 0): print('Working, iteration', iter, 'out of', Niter)
     contour() # keep one side at 1000V
     for i in range(1, Nmax-2):                                                
        for j in range(1,Nmax-2):
            if grid[i,j]==0.: # interior points
                V[i,j] = 0.25*(V[i+1,j]+V[i-1,j]+V[i,j+1]+V[i,j-1])  
x = range(0, Nmax-1, 2)
y = range(0, Nmax, 2)                  # Plot every other point                        
X, Y = p.meshgrid(x,y)    

def functz(V):                        # Function returns V(x, y)
    z = V[X,Y]                        
    return z

Z = functz(V)
fig = p.figure()                                 # Create figure
ax = Axes3D(fig)                                     # Plot axes
ax.plot_wireframe(X, Y, Z, color = 'r')          # Red wireframe
ax.set_title('Potential within Triangle (Rotatable)')
ax.set_xlabel('X')                                  # Label axes
ax.set_ylabel('Y')
ax.set_zlabel('Potential')
p.show()                                              # Display fig 
Пример #44
0
            for i in range(1, N - 1):
                u[i][j][2] = 2. * u[i][j][1] - u[i][j][0] + ratio * (
                    u[i + 1][j][1] + u[i - 1][j][1] + u[i][j + 1][1] +
                    u[i][j - 1][1] - 4. * u[i][j][1])
        u[:][:][0] = u[:][:][1]  # Reset past
        u[:][:][1] = u[:][:][2]  # Reset present
        for j in range(0, N):
            for i in range(0, N):
                v[i][j] = u[i][j][2]  # Convert to 2D for matplotlib
    return v


v = vibration(tim)
x1 = range(0, N)
y1 = range(0, N)
X, Y = p.meshgrid(x1, y1)


def functz(v):
    z = v[X, Y]
    return z


Z = functz(v)
fig = p.figure()
ax = Axes3D(fig)
ax.plot_wireframe(X, Y, Z, color='r')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('u(x,y)')
p.show()
Пример #45
0
    tt = time.time()
    analysis.run()

    print "Elapsed time: ", time.time()-tt, "seconds"

    raw_data = {}
    X = set()
    Y = set()
    for c in analysis.driver.recorders[0].get_iterator():
        raw_data[(c['paraboloid.x'],c['paraboloid.y'])] = c['paraboloid.f_xy']
        X.add(c['paraboloid.x'])
        Y.add(c['paraboloid.y'])

    X = sorted(list(X))
    Y = sorted(list(Y))

    xi, yi = p.meshgrid(X, Y)
    zi = []

    for x in X:
        row = []
        for y in Y:
            row.append(raw_data[(x, y)])
        zi.append(row)
    zi = array(zi)

    fig = p.figure()
    ax = p3.Axes3D(fig)
    ax.plot_surface(xi, yi, zi, rstride=1, cstride=1, cmap=cm.jet, linewidth=0)

    p.show()
Пример #46
0
    
# find probability of that acceleration actually occuring in a flying fly
def find_alpha (arr, n, bins):
    
    alpha = np.zeros(arr.shape)
    
    for i in range(arr.shape[0]):
        for j in range(arr.shape[1]):
            index = np.argmin( np.abs(bins - arr[i,j]) )
            a = n[index]
            alpha[i,j] = a
    
    
    return alpha
    
mesh_x,mesh_y = pylab.meshgrid( np.linspace(-.01,-.0001,300), np.linspace(.0001,.1,300) )
c = accel(mesh_x, mesh_y)







alpha = find_alpha(c, n, bins)
alpha = alpha - alpha.max()/2
alpha = np.sin(np.pi/2 * (alpha / alpha.max()) )

cm = colormap.ScalarMappable(cmap='gray')
rgb = cm.to_rgba(-1*np.exp(c))
rgba = rgb
Пример #47
0
       ['u', 'spl', 'dt', 'dx', 'fac', 'epsilon', 'j_start',
        'j_end', 'num_x', 't_steps_betw_plt'],
       type_converters=converters.blitz)

spl_ma = np.ma.array(spl, mask=np.isnan(spl), fill_value=0)
cmap = p.cm.ocean
cmap.set_bad(color='k',alpha=1)

#-- X coordinates
x = list(range(0, num_x, x_skip))

#-- Y coordinates
y = list(range(0, mt, t_steps_betw_plt))

#-- 2D grids with X and Y coordinates
X, Y = p.meshgrid(x, y)
def functz(spl):
    z = spl[X, Y] 
    return z

#s = surf(x, y, 20*spl)
#fig  = p.figure(1)                                         # create figure
#fig.clf()
#ax = Axes3D(fig)                                              # plot axes
#ax.plot_surface(X*dx*x_skip, Y*dt*t_steps_betw_plt, spl[X, Y],
#                cmap=p.cm.bone)#  color = 'r')                            # red wireframe
#ax.plot_surface(X*dx*x_skip, Y*dt*t_steps_betw_plt, spl[X, Y],
#                cmap=p.cm.bone)#  color = 'r')                            # red
#ax.set_xlabel('Positon')                                     # label axes
#ax.set_ylabel('Time')
#ax.set_zlabel('Disturbance')
Пример #48
0
def meshgrid_of(A):
    x = range(np.shape(A)[0])
    y = range(np.shape(A)[1])
    xx, yy = p.meshgrid(x, y)
    return xx, yy
Пример #49
0
    def show(self,
             typ='s1',
             k=0,
             N=-1,
             M=-1,
             kmax=1000,
             seuildb=50,
             titre='SHC',
             xl=True,
             yl=True,
             fontsize=14,
             dB=True,
             cmap=plt.cm.hot_r,
             anim=True):
        """ show coeff

        Parameters
        ----------
        typ :  string 
            default ('s1')
            's1'  shape 1  (Nf , N , M )
            's2'  shape 2  (Nf , N*M   )
            's3'  shape 3  (Nf , K )  T ( K x 2 )

        k  : integer 
            frequency index default 0

        N, M = maximal value for degree, mode respectively
        (not to be defined if 's2' or 's3')

        """

        fa = np.linspace(self.fmin, self.fmax, self.Nf)
        if typ == 's1':
            if N == -1:
                N = self.N1
            if M == -1:
                M = self.M1
            Mg, Ng = plt.meshgrid(np.arange(M), np.arange(N))
            if anim:
                fig = plt.gcf()
                ax = fig.gca()
                v = np.abs(self.s1[k, 0:N, 0:M])
                if dB:
                    v = 20 * np.log10(v)
                p = plt.scatter(Mg,
                                Ng,
                                c=v,
                                s=30,
                                cmap=cmap,
                                linewidth=0,
                                vmin=-seuildb,
                                vmax=0)
                plt.colorbar()
                plt.draw()
            else:
                v = np.abs(self.s1[k, 0:N, 0:M])
                if dB:
                    vdB = 20 * np.log10(v + 1e-15)
                    plt.scatter(Mg,
                                Ng,
                                c=vdB,
                                s=30,
                                cmap=cmap,
                                linewidth=0,
                                vmin=-seuildb,
                                vmax=0)
                    plt.title(titre)
                    plt.colorbar()
                else:
                    plt.scatter(Mg, Ng, c=v, s=30, cmap=cmap, linewidth=0)
                    plt.title(titre)
                    plt.colorbar()

                if xl:
                    plt.xlabel('m', fontsize=fontsize)
                if yl:
                    plt.ylabel('n', fontsize=fontsize)

        if typ == 's2':
            if np.shape(self.s2)[1] <= 1:
                plt.plot(fa, 10 * np.log10(abs(self.s2[:, 0])))
            else:
                K = np.shape(self.s2)[1]

            kmax = min(kmax, K)
            db = 20 * np.log10(abs(self.s2[:, 0:kmax] + 1e-15))
            col = 1 - (db > -seuildb) * (db + seuildb) / seuildb
            #
            #gray
            #
            #pcolor(np.arange(K+1)[0:kmax],self.fa,col,cmap=cm.gray_r,vmin=0.0,vmax=1.0)
            #
            #color
            #
            plt.pcolor(np.arange(K + 1)[0:kmax],
                       fa,
                       col,
                       cmap=plt.cm.hot,
                       vmin=0.0,
                       vmax=1.0)
            if xl:
                plt.xlabel('index', fontsize=fontsize)
            if yl:
                plt.ylabel('Frequency (GHz)', fontsize=fontsize)

        if typ == 's3':
            if np.shape(self.s3)[1] <= 1:
                plt.plot(fa, 10 * np.log10(abs(self.s3[:, 0])))
            else:
                K = np.shape(self.s3)[1]

            kmax = min(kmax, K)
            db = 20 * np.log10(abs(self.s3[:, 0:kmax] + 1e-15))
            col = 1 - (db > -seuildb) * (db + seuildb) / seuildb
            plt.pcolor(np.arange(K + 1)[0:kmax],
                       fa,
                       col,
                       cmap=plt.cm.hot,
                       vmin=0.0,
                       vmax=1.0)
            if xl:
                plt.xlabel('index', fontsize=fontsize)
            if yl:
                plt.ylabel('Frequency (GHz)', fontsize=fontsize)

                #echelle=[str(0), str(-10), str(-20), str(-30), str(-40), str(-50)]
        if (typ == 's2') | (typ == 's3'):

            echelle = [
                str(0),
                str(-seuildb + 40),
                str(-seuildb + 30),
                str(-seuildb + 20),
                str(-seuildb + 10),
                str(-seuildb)
            ]
            cbar = plt.colorbar(ticks=[0, 0.2, 0.4, 0.6, 0.8, 1])
            cbar.ax.set_yticklabels(echelle)
            cbar.ax.set_ylim(1, 0)
            for t in cbar.ax.get_yticklabels():
                t.set_fontsize(fontsize)
            plt.xticks(fontsize=fontsize)
            plt.yticks(fontsize=fontsize)
            plt.title(titre, fontsize=fontsize + 2)
Пример #50
0
import numpy as np
from scipy.stats import multivariate_normal as mvn
import matplotlib.pylab as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import LightSource
from matplotlib import cm

m = np.array([0, 0])
covs = [np.eye(2), np.array([[.5, -1.], [-1., 3]]), np.array([[2, 1], [1, 2]])]
#%%
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
xv, yv = plt.meshgrid(x, y)

zs = []
for c in covs:
    zs.append(
        mvn.pdf(np.c_[xv.flatten(), yv.flatten()], mean=m,
                cov=c).reshape(xv.shape))

#%%
#ls = LightSource(270, 45)

fig, axs = plt.subplots(1,
                        3,
                        subplot_kw=dict(projection='3d'),
                        figsize=(11, 3))
for ax, z, c in zip(axs, zs, covs):
    #    rgb = ls.shade(z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft')
    surf = ax.plot_surface(
        xv,
Пример #51
0
def jointplot(X,
              Y,
              xlabel=None,
              ylabel=None,
              binsim=40,
              binsh=20,
              contour=True):
    """
Plots the joint distribution of posteriors for X1 and X2, including the 1D
histograms showing the median and standard deviations.

The work that went in creating this nice method is shown, step by step, in 
the ipython notebook "error contours.ipynb". Sources of inspiration:

- http://python4mpia.github.io/intro/quick-tour.html
- http://stackoverflow.com/questions/12301071/multidimensional-confidence-intervals

Usage:

>>> jointplot(M.rtr.trace(),M.mdot.trace(),xlabel='$\log \ r_{\\rm tr}$', ylabel='$\log \ \dot{m}$')

gives the following plot.

.. figure:: ../figures/jointplot.png
   :scale: 100 %
   :alt: Two-dimensional kernel density distribution.

   Two-dimensional kernel density distribution, along with one-dimensional histograms of each distribution.
	"""
    import scipy.stats

    # Generates 2D histogram for image
    histt, xt, yt = numpy.histogram2d(X,
                                      Y,
                                      bins=[binsim, binsim],
                                      normed=False)
    histt = numpy.transpose(
        histt)  # Beware: numpy switches axes, so switch back.

    # assigns correct proportions to subplots
    fig = pylab.figure()
    gs = pylab.GridSpec(2,
                        2,
                        width_ratios=[3, 1],
                        height_ratios=[1, 3],
                        wspace=0.001,
                        hspace=0.001)
    con = pylab.subplot(gs[2])
    histx = pylab.subplot(gs[0], sharex=con)
    histy = pylab.subplot(gs[3], sharey=con)

    # Image
    con.imshow(histt,
               extent=[xt[0], xt[-1], yt[0], yt[-1]],
               origin='lower',
               cmap=pylab.cm.gray_r,
               aspect='auto')

    # Overplot with error contours 1,2 sigma
    if contour == True:
        pdf = scipy.stats.gaussian_kde([X, Y])
        x, y = pylab.meshgrid(xt, yt)
        z = numpy.array(pdf.evaluate([x.flatten(),
                                      y.flatten()])).reshape(x.shape)
        # the [61,15] values were obtained by trial and error until the joint confidence
        # contours matched the confidence intervals from the individual X,Y
        s = scipy.stats.scoreatpercentile(pdf(pdf.resample(1000)), [61, 15])
        cs = con.contour(x,
                         y,
                         z,
                         levels=s,
                         extent=[x[0], x[-1], y[0], y[-1]],
                         linestyles=['-', '-', '-'],
                         colors=['black', 'blue'])
        # use dictionary in order to assign your own labels to the contours.
        #fmtdict = {s[0]:r'$1\sigma$',s[1]:r'$2\sigma$'}
        #con.clabel(cs, fmt=fmtdict, inline=True, fontsize=20)
        if xlabel != None: con.set_xlabel(xlabel)
        if ylabel != None: con.set_ylabel(ylabel)

    # X-axis histogram
    histx.hist(X, binsh, histtype='stepfilled', facecolor='lightblue')
    pylab.setp(histx.get_xticklabels(), visible=False)  # no X label
    pylab.setp(histx.get_yticklabels(), visible=False)  # no Y label
    # Vertical lines with median and 1sigma confidence
    yax = histx.set_ylim()
    histx.plot([numpy.median(X), numpy.median(X)], [yax[0], yax[1]],
               'k-',
               linewidth=2)  # median
    xsd = scipy.stats.scoreatpercentile(X, [15.87, 84.13])
    histx.plot([xsd[0], xsd[0]], [yax[0], yax[1]], 'k--')  # -1sd
    histx.plot([xsd[-1], xsd[-1]], [yax[0], yax[1]], 'k--')  # +1sd

    # Y-axis histogram
    histy.hist(Y,
               binsh,
               histtype='stepfilled',
               orientation='horizontal',
               facecolor='lightyellow')
    pylab.setp(histy.get_yticklabels(), visible=False)  # no Y label
    pylab.setp(histy.get_xticklabels(), visible=False)  # no X label
    # Vertical lines with median and 1sigma confidence
    xax = histy.set_xlim()
    histy.plot([xax[0], xax[1]],
               [numpy.median(Y), numpy.median(Y)],
               'k-',
               linewidth=2)  # median
    ysd = scipy.stats.scoreatpercentile(Y, [15.87, 84.13])
    histy.plot([xax[0], xax[1]], [ysd[0], ysd[0]], 'k--')  # -1sd
    histy.plot([xax[0], xax[1]], [ysd[-1], ysd[-1]], 'k--')  # +1sd
        #     for j in range(y_edge2+1, 90):
        #         V[i,j] = 0.25*(V[i+1,j]+V[i-1,j]+V[i,j+1]+V[i,j-1])

    return V[i,j]

if __name__ == '__main__':

  print("Initializing")
  Nmax = 100; Niter = 70; V = zeros((Nmax+1, Nmax+1), float)
  max_range = 90 # Required: max_range < Nmax

  print("Working hard, wait for the figure while I count to 60")

  voltage(100, 100, 100, 100, 30, 60, 30, 60)
  finite_difference(V, 30, 60, 30, 60, max_range)

  x = range(0, max_range, 2);  y = range(0, max_range, 2)
  X, Y = plt.meshgrid(x,y)

  Z = functz(V)

  fig = plt.figure()
  ax = Axes3D(fig)
  ax.plot_wireframe(X, Y, Z, color='r')
  ax.contour(X, Y, Z, offset=0)
  ax.set_xlabel('X')
  ax.set_ylabel('Y')
  ax.set_zlabel('Potential')

  plt.show()
Пример #53
0
print("Espera mientras se construye la gráfica, cuenta hasta ...")

for k in range(0, Nmax - 1):
    V[k, 0] = 100.0

for iter in range(Niter):
    if iter % 10 == 0: print(iter)
    for i in range(1, Nmax - 2):
        for j in range(1, Nmax - 2):
            V[i, j] = 0.25 * (V[i + 1, j] + V[i - 1, j] + V[i, j + 1] +
                              V[i, j - 1])

x = range(0, Nmax - 1, 2)
y = range(0, 50, 2)

X, Y = plt.meshgrid(x, y)


def functz(V):
    z = V[X, Y]
    return z


Z = functz(V)
fig = plt.figure()
ax = Axes3D(fig)

#surf = ax.plot_wireframe(X, Y, Z)
surf = ax.plot_surface(X,
                       Y,
                       Z,
Пример #54
0
# Campo electrico de una particula puntual cargada
def Electric(r, rp, q):
    E = 1 / (4 * np.pi * eps0) * q * (r - rp) / np.linalg.norm(r - rp) ** 3
    return E


# Permitividad del vacio
eps0 = 8.85418e-12
# Resolucion de graficas
Nres = 25
# Coordenada X
Xarray = np.linspace(0, 10, Nres)
# Coordenada Y
Yarray = np.linspace(0, 10, Nres)
# Construccion de la cuadricula
X, Y = plt.meshgrid(Xarray, Yarray)

# CONSTRUCCION DE CAMPO E Y POTENCIAL PHI, PARTICULA 1
# Carga electrica
q1 = -1
# Posicion particula
rp1 = np.array([4, 4])
# Incializacion Potencial Electrico
phi1 = np.zeros((Nres, Nres))
# Incializacion Campo Electrico
E1x = np.ones((Nres, Nres))
E1y = np.ones((Nres, Nres))
# Calculo Potencial Electrico y Campo Electrico
for i in xrange(Nres):
    for j in xrange(Nres):
        r = np.array([Xarray[i], Yarray[j]])