Exemplo n.º 1
0
def main(gldel, glazm, ldel, lazm, tck_gfu, tck_gfv):

    # Extract Points from Interpolated Greens Functions
    gfu = interpolate.splev(ldel, tck_gfu, der=0)
    gfv = interpolate.splev(ldel, tck_gfv, der=0)

    # Determine Increments in Delta and Azimuth
    del_incs = np.multiply(ldel - gldel[0:-1], 2.)
    azm_incs = np.multiply(lazm - glazm, 2.)

    # Convert Angles to Radians
    del_incs_rad = np.multiply(del_incs, (pi / 180.))
    ldel_rad = np.multiply(ldel, (pi / 180.))
    azm_incs_rad = np.multiply(azm_incs, (pi / 180.))

    # Integrate the Greens Functions -- Delta Component
    # See Section 4.1 of Agnew (2012), SPOTL Manual
    intu = 4. * gfu * np.cos(ldel_rad / 2.) * np.sin(del_incs_rad / 4.)
    intv = 4. * gfv * np.cos(ldel_rad / 2.) * np.sin(del_incs_rad / 4.)

    # Integrate the Greens Functions -- Azimuthal Component
    intu = intu * azm_incs_rad[0]
    intv = intv * (2. * np.sin(azm_incs_rad[0] / 2.))

    # Create Full 1-D Arrays
    xv, yv = sc.meshgrid(intu, lazm)
    uint = xv.flatten()
    xv, yv = sc.meshgrid(intv, lazm)
    vint = xv.flatten()

    # Return Integrated Greens Functions
    return uint, vint
Exemplo n.º 2
0
def plot2(filein, Telim, Nelim, pts=101):

    plt.figure()
    out = adasread.xxdata_13(filein, 1, Telim, Nelim)
    print(out[13].shape)
    print(out[12].shape)
    print(out[14].shape)

    ne = scipy.array(out[13]).ravel()
    Te = scipy.array(out[12]).ravel()
    SXB = scipy.array(out[14][:, :, 0])

    temp = ne != 0
    temp2 = Te != 0

    xout2, yout2 = scipy.meshgrid(ne[temp], Te[temp2])
    SXB = SXB[temp2, :]
    SXB = SXB[:, temp]

    ne1 = scipy.linspace(ne[temp].min(), ne[temp].max(), pts)
    Te1 = scipy.linspace(Te[temp2].min(), Te[temp2].max(), pts)
    xout, yout = scipy.meshgrid(ne1, Te1)

    interp = scipy.interpolate.RectBivariateSpline(scipy.log(ne[temp]),
                                                   Te[temp2], SXB)

    zout = interp.ev(scipy.log(xout), yout)
    #xout,yout = scipy.meshgrid(ne[temp]*1e6,Te[temp2])
    #zout = SXB[temp2,:]
    #zout = zout[:,temp]

    plt.pcolor(xout * 1e6, yout, zout.T)
    plt.colorbar()
    plt.xlabel(r'electron density [$10^{20}$ m$^{-3}$]')
    plt.ylabel(r'electron temperature [eV]')
Exemplo n.º 3
0
def plot_stoch_value():
    #Compute Solution==========================================================
    sigma = .5
    mu = 4 * sigma
    K = 7
    Gamma, eps = discretenorm.discretenorm(K, mu, sigma)

    N = 100
    W = sp.linspace(0, 1, N)
    V = sp.zeros((N, K))

    u = lambda c: sp.sqrt(c)
    beta = 0.99

    X, Y = sp.meshgrid(W, W)
    Wdiff = Y - X
    index = Wdiff < 0
    Wdiff[index] = 0

    util_grid = u(Wdiff)

    util3 = sp.tile(util_grid[:, :, sp.newaxis], (1, 1, K))
    eps_grid = eps[sp.newaxis, sp.newaxis, :]
    eps_util = eps_grid * util3

    Gamma_grid = Gamma[sp.newaxis, :]

    delta = 1
    Vprime = V
    z = 0
    while (delta > 10**-9):
        z = z + 1
        V = Vprime
        gamV = Gamma_grid * V
        Expval = sp.sum(gamV, 1)
        Exp_grid = sp.tile(Expval[sp.newaxis, :, sp.newaxis], (N, 1, K))
        arg = eps_util + beta * Exp_grid
        arg[index] = -10 ^ 10
        Vprime = sp.amax(arg, 1)
        psi_ind = sp.argmax(arg, 1)
        psi = W[psi_ind]
        delta = sp.linalg.norm(Vprime - V)

    #============================================================
    #Plot 3D
    x = sp.arange(0, N)
    y = sp.arange(0, K)
    X, Y = sp.meshgrid(x, y)
    fig1 = plt.figure()
    ax1 = Axes3D(fig1)
    ax1.set_xlabel(r'$W$')
    ax1.set_ylabel(r'$\varepsilon$')
    ax1.set_zlabel(r'$V$')
    ax1.plot_surface(W[X], Y, sp.transpose(Vprime), cmap=cm.coolwarm)
    plt.savefig('stoch_value.pdf')
def plot_stoch_value():    
    #Compute Solution==========================================================
    sigma = .5
    mu = 4*sigma
    K = 7
    Gamma, eps = discretenorm.discretenorm(K,mu,sigma)
    
    N = 100
    W = sp.linspace(0,1,N)
    V = sp.zeros((N,K))
    
    u = lambda c: sp.sqrt(c)
    beta = 0.99
    
    X,Y= sp.meshgrid(W,W)
    Wdiff = Y-X
    index = Wdiff < 0
    Wdiff[index] = 0
    
    util_grid = u(Wdiff)
    
    util3 = sp.tile(util_grid[:,:,sp.newaxis],(1,1,K))
    eps_grid = eps[sp.newaxis,sp.newaxis,:]
    eps_util = eps_grid*util3
    
    Gamma_grid = Gamma[sp.newaxis,:]
    
    delta = 1
    Vprime = V
    z = 0
    while (delta > 10**-9):
        z= z+1
        V = Vprime
        gamV = Gamma_grid*V
        Expval = sp.sum(gamV,1)
        Exp_grid = sp.tile(Expval[sp.newaxis,:,sp.newaxis],(N,1,K))
        arg = eps_util+beta*Exp_grid
        arg[index] = -10^10
        Vprime = sp.amax(arg,1)
        psi_ind = sp.argmax(arg,1)
        psi = W[psi_ind]
        delta = sp.linalg.norm(Vprime - V)
    
    #============================================================    
    #Plot 3D    
    x=sp.arange(0,N)
    y=sp.arange(0,K)
    X,Y=sp.meshgrid(x,y)
    fig1 = plt.figure()
    ax1= Axes3D(fig1)
    ax1.set_xlabel(r'$W$')
    ax1.set_ylabel(r'$\varepsilon$')
    ax1.set_zlabel(r'$V$')
    ax1.plot_surface(W[X],Y,sp.transpose(Vprime), cmap=cm.coolwarm)
    plt.savefig('stoch_value.pdf')
Exemplo n.º 5
0
def two_point_correlation_bf(im, spacing=10):
    r"""
    Calculates the two-point correlation function using brute-force (see Notes)

    Parameters
    ----------
    im : ND-array
        The image of the void space on which the 2-point correlation is desired

    spacing : int
        The space between points on the regular grid that is used to generate
        the correlation (see Notes)

    Returns
    -------
    A tuple containing the x and y data for plotting the two-point correlation
    function, using the *args feature of matplotlib's plot function.  The x
    array is the distances between points and the y array is corresponding
    probabilities that points of a given distance both lie in the void space.

    The distance values are binned as follows:

        bins = range(start=0, stop=sp.amin(im.shape)/2, stride=spacing)

    Notes
    -----
    The brute-force approach means overlaying a grid of equally spaced points
    onto the image, calculating the distance between each and every pair of
    points, then counting the instances where both pairs lie in the void space.

    This approach uses a distance matrix so can consume memory very quickly for
    large 3D images and/or close spacing.
    """
    if im.ndim == 2:
        pts = sp.meshgrid(range(0, im.shape[0], spacing),
                          range(0, im.shape[1], spacing))
        crds = sp.vstack([pts[0].flatten(),
                          pts[1].flatten()]).T
    elif im.ndim == 3:
        pts = sp.meshgrid(range(0, im.shape[0], spacing),
                          range(0, im.shape[1], spacing),
                          range(0, im.shape[2], spacing))
        crds = sp.vstack([pts[0].flatten(),
                          pts[1].flatten(),
                          pts[2].flatten()]).T
    dmat = sptl.distance.cdist(XA=crds, XB=crds)
    hits = im[pts].flatten()
    dmat = dmat[hits, :]
    h1 = sp.histogram(dmat, bins=range(0, int(sp.amin(im.shape)/2), spacing))
    dmat = dmat[:, hits]
    h2 = sp.histogram(dmat, bins=h1[1])
    tpcf = namedtuple('two_point_correlation_function',
                      ('distance', 'probability'))
    return tpcf(h2[1][:-1], h2[0]/h1[0])
Exemplo n.º 6
0
def main(rlat, rlon, ldel, lazm, unit_area):

    # Determine Geographic Coordinates of Mesh Midpoints
    # e.g. www.movable-type.co.uk/scripts/latlong.html
    # e.g. www.geomidpoint.com/destination/calculation.html
    xv, yv = sc.meshgrid(ldel, lazm)
    ldelfull = xv.flatten()
    lazmfull = yv.flatten()
    rlatrad = rlat * (pi / 180.)
    rlonrad = rlon * (pi / 180.)
    ldelrad = np.multiply(ldelfull, (pi / 180.))
    lazmrad = np.multiply(lazmfull, (pi / 180.))
    ilat = np.arcsin(
        np.sin(rlatrad) * np.cos(ldelrad) +
        np.cos(rlatrad) * np.sin(ldelrad) * np.cos(lazmrad))
    ilon    = rlonrad + np.arctan2(np.sin(lazmrad)*np.sin(ldelrad)*np.cos(rlatrad), \
         np.cos(ldelrad) - np.sin(rlatrad)*np.sin(ilat))

    # Convert Back to Degrees
    ilat = np.multiply(ilat, (180. / pi))
    ilon = np.multiply(ilon, (180. / pi))

    # Determine Unit Areas for Each Cell
    xv, yv = sc.meshgrid(unit_area, lazm)
    iarea = xv.flatten()

    # Shift to Range 0-360
    # Test for Negative Values
    if any(ilon < 0.):
        flag1 = True
    else:
        flag1 = False
    while (flag1 == True):
        neglon_idx = np.where(ilon < 0.)
        ilon[neglon_idx] = ilon[neglon_idx] + 360.
        if any(ilon < 0.):
            flag1 = True
        else:
            flag1 = False
    # Test for Greater than 360
    if any(ilon > 360.):
        flag2 = True
    else:
        flag2 = False
    while (flag2 == True):
        lrglon_idx = np.where(ilon > 360.)
        ilon[lrglon_idx] = ilon[lrglon_idx] - 360.
        if any(ilon > 360.):
            flag2 = True
        else:
            flag2 = False

    # Return Lat/Lon for Integration Mesh Grid Midpoints
    return ilat, ilon, iarea
Exemplo n.º 7
0
def arctan_riemann_surface():
    """Riemann surface for real part of arctan(z)"""

    fig = plt.figure()
    ax = Axes3D(fig)
    Xres, Yres = .01, .2
    ax.view_init(elev=11., azim=-56)
    X = sp.arange(-4, -.0001, Xres)
    Y = sp.arange(-4, 4, Yres)
    X, Y = sp.meshgrid(X, Y)
    Z = sp.real(sp.arctan(X + 1j * Y))
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, linewidth=0, cmap=cmap)
    ax.plot_surface(X,
                    Y,
                    Z + sp.pi,
                    rstride=1,
                    cstride=1,
                    linewidth=0,
                    cmap=cmap)
    ax.plot_surface(X,
                    Y,
                    Z - sp.pi,
                    rstride=1,
                    cstride=1,
                    linewidth=0,
                    cmap=cmap)
    X = sp.arange(.0001, 4, Xres)
    Y = sp.arange(-4, 4, Yres)
    X, Y = sp.meshgrid(X, Y)
    Z = sp.real(sp.arctan(X + 1j * Y))
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, linewidth=0, cmap=cmap)
    ax.plot_surface(X,
                    Y,
                    Z + sp.pi,
                    rstride=1,
                    cstride=1,
                    linewidth=0,
                    cmap=cmap)
    ax.plot_surface(X,
                    Y,
                    Z - sp.pi,
                    rstride=1,
                    cstride=1,
                    linewidth=0,
                    cmap=cmap)
    plt.savefig('arctan_riemann_surface.pdf',
                bbox_inches='tight',
                pad_inches=0)
Exemplo n.º 8
0
 def setUp(self):
     self.n = 100
     self.m = 10
     self.kappa1=0.0
     self.errLevelPos = 6
     self.errLevelCurv= 5
     self.x = numpy.linspace(-1.5,1.5,self.n)
     self.lamb = numpy.linspace(-1.0,1.0,self.m)
     X,LAMB = scipy.meshgrid(self.x,self.lamb)
     lambField = DC.FieldContainer(LAMB,
                                   unit = '1 V / m**3',
                                   longname='parameter',
                                   shortname='\lambda')
     xField = DC.FieldContainer(X[0],
                                unit = '1 m',
                                longname = 'position',
                                shortname = 'x')
     V=[]
     for i in xrange(len(lambField.data)):
         u = xField.data
         V.append(-lambField.data[i]/2* u**2 + u**4/4-u*self.kappa1)
     self.I = DC.FieldContainer(numpy.array(V),
                                longname = 'intensity',
                                shortname='I')
     self.I.dimensions[-1]=xField
     self.I0 = DC.FieldContainer(numpy.ones(self.I.data.shape,'float'),
                                longname = 'white reference',
                                shortname='I_0')
     self.I0.dimensions[-1]=xField
     self.Id = DC.FieldContainer(numpy.zeros(self.I.data.shape,'float'),
                                longname = 'darf reference',
                                shortname='I_d')
     self.Id.dimensions[-1]=xField
     self.sampleC = DC.SampleContainer([self.I,self.I0,self.Id])
Exemplo n.º 9
0
 def make_grid_flip_y(self):
     """A way to make a basic grid from x,y data, inverting y.
     """
     self.y_grid, self.x_grid = scipy.meshgrid(self.y[::-1], self.x[:], indexing='ij')
     self.dims = (self.ny, self.nx)
     self.dy = self.y[0]-self.y[1]
     self.dx = self.x[1]-self.x[0]
Exemplo n.º 10
0
    def __init__(self, filename, **kwargs):
        print('opening SWMF Ionosphere Electrodynamics file %s' % filename)
        self.filename = filename
        self.missing_value = np.NAN
        data = self.read_swmf_ie(filename)
        self.variables = dict()
        self.coords = ['theta', 'phi', 'altitude']
        self.coord_units = ['deg', 'deg', 'km']
        self.x = data['Theta']
        self.y = data['Psi']
        self.z = [110.]
        #        self.coordinate_system='SM'
        # these three variables are needed to prevent errors in Kamodo
        self.verbose = False
        self.symbol_registry = dict()
        self.signatures = dict()

        #        self.z_, self.y_, self.x_ = scipy.meshgrid(self.z, self.y, self.x, indexing = 'ij')
        self.y_, self.x_ = scipy.meshgrid(self.y, self.x, indexing='ij')

        #        print(data['orig_units'])
        #        print(data['units'])
        for ivar in range(len(data['variables'])):
            varname = data['variables'][ivar]
            var_data = data['data'][:, :, ivar].squeeze().T
            unit = data['units'][ivar]
            #            print("variable:",varname,"unit:",unit,"data:",var_data)

            self.variables[varname] = dict(units=unit, data=var_data)
            self.register_variable(varname, unit)
Exemplo n.º 11
0
def draw_2Dsecondaryinfo(ax, gp, Xnew, Xminmax, step):
    Xmin, Xmax = Xminmax
    ax1 = ax[0,1]
    ax2 = ax[1,0]
    ax3 = ax[1,1]

    X_grid = sp.meshgrid(sp.linspace(Xmin[0], Xmax[0], 50), sp.linspace(Xmin[1], Xmax[1], 50))
    X_grid = sp.vstack([x.ravel() for x in X_grid]).reshape(n_features,-1).T

    y_grid, MSE_grid = gp.predict(X_grid, eval_MSE=True)
    ax2.clear()
    ax2.scatter(X_grid[:,0], X_grid[:,1], marker = 'h', s = 200, c = MSE_grid, cmap = 'YlGnBu', alpha = 1, edgecolors='none')
    ax2.scatter(Xnew[0], Xnew[1], marker='h', s = 400, c = 'g', alpha = 0.5)


    ax3.clear()
    ax3.scatter(X_grid[:,0], X_grid[:,1], s = 200, c = y_grid, cmap = 'YlGnBu', alpha = 1, edgecolors='none')
    ax3.scatter(Xnew[0], Xnew[1], marker='h', s = 400, c = 'g', alpha = 0.5)

    if step < 1:
        y_target = target_fun(X_grid)
        ax1.scatter(X_grid[:,0], X_grid[:,1], s = 200, marker='s', c = y_target, cmap = 'YlGnBu', alpha = 1, edgecolors='none')
    for axx in [ax1, ax2, ax3]:
        axx.set_xlabel('$CV 1$')
        axx.set_ylabel('$CV 2$')
        axx.set_xlim(Xmin[0], Xmax[0])
        axx.set_ylim(Xmin[1], Xmax[1])
Exemplo n.º 12
0
 def setUp(self):
     self.n = 100
     self.m = 10
     self.kappa1 = 0.0
     self.errLevelPos = 6
     self.errLevelCurv = 5
     self.x = numpy.linspace(-1.5, 1.5, self.n)
     self.lamb = numpy.linspace(-1.0, 1.0, self.m)
     X, LAMB = scipy.meshgrid(self.x, self.lamb)
     lambField = DC.FieldContainer(LAMB,
                                   unit='1 V / m**3',
                                   longname='parameter',
                                   shortname='\lambda')
     xField = DC.FieldContainer(X[0],
                                unit='1 m',
                                longname='position',
                                shortname='x')
     V = []
     for i in xrange(len(lambField.data)):
         u = xField.data
         V.append(-lambField.data[i] / 2 * u**2 + u**4 / 4 -
                  u * self.kappa1)
     self.I = DC.FieldContainer(numpy.array(V),
                                longname='intensity',
                                shortname='I')
     self.I.dimensions[-1] = xField
     self.I0 = DC.FieldContainer(numpy.ones(self.I.data.shape, 'float'),
                                 longname='white reference',
                                 shortname='I_0')
     self.I0.dimensions[-1] = xField
     self.Id = DC.FieldContainer(numpy.zeros(self.I.data.shape, 'float'),
                                 longname='darf reference',
                                 shortname='I_d')
     self.Id.dimensions[-1] = xField
     self.sampleC = DC.SampleContainer([self.I, self.I0, self.Id])
Exemplo n.º 13
0
def bump(category, number, vals):
    ys, xs = sp.meshgrid(sp.arange(vals.shape[1]), sp.arange(vals.shape[0]))

    z0 = sp.array([
        vals.mean(),  # background 
        vals.max() - vals.mean(),  # height
        min(vals.shape) // 2,  # scale/width
        vals.shape[1] // 2,  # x-center
        vals.shape[0] // 2
    ])  # y-center

    def estimate(z):
        mu, h, w, x, y = z

        dist = ((xs - x)**2 + (ys - y)**2) / w**2
        bump = h * sp.exp(-dist)
        return bump, bump + mu

    def loss(z):
        return ((vals - estimate(z)[1])**2).mean() / (vals**2).mean()

    #TODO: Make this faster by passing the Jacobian
    soln = sp.optimize.minimize(loss, z0)
    if soln['success']:
        return estimate(soln['x'])[0].clip(0, None)
    else:
        log.warn(
            f'A bump fitting failed on {category}/{number}; setting it to zero'
        )
        return sp.zeros_like(vals)
Exemplo n.º 14
0
def test_mayaxes():

    from mayaxes import mayaxes
    from scipy import sqrt,sin,meshgrid,linspace,pi
    import mayavi.mlab as mlab
        
    resolution = 200
    lambda_var = 3
    theta = linspace(-lambda_var*2*pi,lambda_var*2*pi,resolution)
    
    x, y = meshgrid(theta, theta)
    r = sqrt(x**2 + y**2)
    z = sin(r)/r
    
    fig = mlab.figure(size=(1024,768))
    surf = mlab.surf(theta,theta,z,colormap='jet',opacity=1.0,warp_scale='auto') 
    mayaxes(title_string='Figure 1: Diminishing polar cosine series', \
        xlabel='X data',ylabel='Y data',zlabel='Z data',handle=surf)
    
    fig.scene.camera.position = [435.4093863309094, 434.1268937227623, 315.90311468125287]
    fig.scene.camera.focal_point = [94.434632665253829, 93.152140057106593, -25.071638984402856]
    fig.scene.camera.view_angle = 30.0
    fig.scene.camera.view_up = [0.0, 0.0, 1.0]
    fig.scene.camera.clipping_range = [287.45231734040635, 973.59247058049255]
    fig.scene.camera.compute_view_plane_normal()
    fig.scene.render()   
    
    mlab.show() 
def grid(x, y, z, resX=100, resY=100):
    "Convert 3 column data to matplotlib grid"
    xi = sp.linspace(min(x), max(x), resX)
    yi = sp.linspace(min(y), max(y), resY)
    Z = griddata(x, y, z, xi, yi, interp='linear')
    X, Y = sp.meshgrid(xi, yi)
    return X, Y, Z
Exemplo n.º 16
0
def steepest_descent(X,Y, step=.001, tol=1e-5, maxiter=5000, bounds=[-5,5], res=.1):
    w = betahat(X,Y)
    a = sp.exp(X.dot(w))
    yhat = (a.T/sp.sum(a, axis=1)).T
    grad = X.T.dot(yhat-Y)
    while la.norm(grad)>tol and maxiter > 0:
        w = w - grad*step
        a=sp.exp(X.dot(w))
        yhat = (a.T/sp.sum(a,axis=1)).T
        grad = X.T.dot(yhat-Y)
        maxiter -= 1

    rang = sp.arange(bounds[0],bounds[1]+res, res)
    Xg, Yg = sp.meshgrid(rang, rang)
    
    Xm = sp.c_[sp.ones_like(Xg.flatten()), Xg.flatten(), Yg.flatten()]
    Xmdot = Xm.dot(w)
    
    types = Xmdot.argmax(axis=1)
    print Xm.shape
    #plot the regions
    c = ['b','r','g']
    for i in range(Xmdot.shape[1]):
        plot_on = types==i
        plt.plot(Xm[plot_on,1], Xm[plot_on,2], c[i]+'.', X[Y[:,i]==1,1], X[Y[:,i]==1,2], c[i]+'o')

    #plot the data segmented
    #tmp = sp.where(Ydat[:,0]==True)[0]
    #plt.plot(Xdat[tmp,1], Xdat[tmp,2], 'o', Xdat[~tmp,1], Xdat[~tmp,2], 'o')
    plt.show()
Exemplo n.º 17
0
def ex(num, a, b, Tb):
    #r = scipy.array([.55,.7,.9])
    r = scipy.linspace(a, 1, 1e3)
    s = ['-', ':', '-.']
    #t = scipy.linspace(0,1,1e3)
    t = scipy.array([.1, 1., 10.])
    toff = scipy.linspace(-1., 0., 1e3)
    r1, t1 = scipy.meshgrid(r, t)
    output = scipy.zeros((len(t), len(r), num))
    alpha = zeros(num, a)
    An, Bn = coeffs(alpha, a, Tb)
    print((jn(0, alpha[0] * r1)).shape, r1.shape, output.shape)
    for i in xrange(num):
        output[:, :, i] = (
            (An[i] * jn(0, alpha[i] * r1) + Bn[i] * yn(0, alpha[i] * r1)) *
            scipy.exp(-b * pow(alpha[i], 2) * t1))

    temp = scipy.sum(output, axis=2) + Tb * scipy.log(r1) / scipy.log(a)
    temp2 = Tb * scipy.log(r1) / scipy.log(a)
    for i in xrange(len(t)):

        #plt.plot(scipy.concatenate((toff,t)),scipy.concatenate((scipy.zeros(toff.shape),temp.T[i])),colors[c[i]],linewidth=2.)
        #plt.plot(t,temp.T[i],colors[c[i]],linewidth=2.)/temp2[:,i]

        #plt.plot(t,temp.T[i]/(Tb*scipy.log(r1)/scipy.log(a))[:,i],colors[c[i]],linewidth=2.)

        plt.plot(r, temp[i], 'k', linewidth=2., linestyle=s[i])
def Spectral_Gradient(nx, ny, lx, ly):
    # Create wavenumber vector for x-direction
    tmp1 = sc.linspace(0, nx/2, int(nx/2+1))*2*sc.pi/lx
    tmp2 = sc.linspace(1-nx/2, -1, int(nx/2-1))*2*sc.pi/lx
    kx = sc.concatenate((tmp1, tmp2))

    # Create wavenumber vector for y-direction
    tmp1 = sc.linspace(0, ny/2, int(ny/2+1))*2*sc.pi/ly
    tmp2 = sc.linspace(1-ny/2, -1, int(ny/2-1))*2*sc.pi/ly
    ky = sc.concatenate((tmp1, tmp2))

    # Dealiasing with the 2/3 rule
    trunc_x_low = int(sc.floor(2/3*nx/2))+1
    trunc_x_high = int(sc.ceil(4/3*nx/2))
    kx[trunc_x_low:trunc_x_high] = sc.zeros(trunc_x_high - trunc_x_low)

    trunc_y_low = int(sc.floor(2/3*ny/2))+1
    trunc_y_high = int(sc.ceil(4/3*ny/2))
    ky[trunc_y_low:trunc_y_high] = sc.zeros(trunc_y_high - trunc_y_low)

    # Create Gradient operators in Fourier domain for x- and y-direction
    Kx, Ky = sc.meshgrid(ky, kx)
    Kx = 1j*Kx
    Ky = 1j*Ky

    return Kx, Ky
Exemplo n.º 19
0
    def to_window(self, **params):

        window = WindowFunction2D(**params)

        ells = self.result.ells
        sedges = self.result.sedges
        counts = self.result.counts

        window.s = map(edges_to_mid, sedges)
        window.poles = [(ell1, ell2) for ell1 in ells[0] for ell2 in ells[1]]
        window.los = self.result.los
        window.window = counts.reshape(
            (-1, ) + counts.shape[2:])  #window.window is (ell,s,d)

        volume = scipy.prod(scipy.meshgrid(
            *[scipy.diff(s_to_cos(sedge)) for sedge in sedges],
            sparse=False,
            indexing='ij'),
                            axis=0)
        window.window /= volume[None, ...]

        window.pad_zero()

        window.s = [s_to_cos(s)[::-1] for s in window.s]
        window.window[0] = window.window[0][::-1, ::-1]

        return window
Exemplo n.º 20
0
def GetSq(filename, Nsamp=1):
    if type(filename) == str:
        filename = [filename]
    attrs = GetAttr(filename[0])
    #hfile=h5py.File(filename,'r')
    dpath, args = GetStat(filename, Nsamp)
    filetype = ''
    try:
        filetype = attrs['type']
    except KeyError:
        mo = re.match('.*/?[0-9]+-(StatSpinStruct)\.h5', filename[0])
        filetype = mo.groups()[0]
    if filetype != 'StatSpinStruct':
        raise InputFileError(
            '\"{0}\" is not a static structure factor file'.format(filename))
    N = pow(attrs['L'], 2)
    Sq = sc.zeros((Nsamp, 5, N), complex)
    for sample, b in enumerate(args):
        for d in b:
            hfile = h5py.File(dpath[d][0], 'r')
            dim = hfile[dpath[d][1]].shape[0]
            Sq[sample, :dim, :] += hfile[dpath[d][1]][
                0:, 0::2] + 1j * hfile[dpath[d][1]][0:, 1::2]
            hfile.close()
        Sq[sample, :, :] /= len(b)
    qx, qy = sc.meshgrid(np.arange(attrs['L']), np.arange(attrs['L']))
    return qx.flatten(), qy.flatten(), Sq
Exemplo n.º 21
0
def plot_mixture(fig, mixture, data):
  plt.subplot(fig)

  # Plot data.
  plt.scatter(data[:, 0], data[:, 1], color='r', marker='+', alpha=0.5)

  delta = 1.0
  coords = []
  # TODO: Should be configurable...
  xs = scipy.arange(-30, 30, delta)
  ys = scipy.arange(-30, 30, delta)
  for x in xs:
    for y in ys:
      coords.append((x, y))

  coords = scipy.asarray(coords)

  Z = None
  for i in range(mixture.degree):
    gaussian = MultivariateGaussianDensity(mixture.means[i], mixture.covs[i])
    z = mixture.mixcoeffs[i] * gaussian.multpdf(coords)

    if Z is None:
      Z = z
    else:
      Z += z

  X, Y = scipy.meshgrid(xs, ys)
  Z.shape = X.shape

  CS = plt.contour(X, Y, Z, 30)
  plt.plot(mixture.means[:, 1], mixture.means[:, 0], 'o', color='green')
Exemplo n.º 22
0
def task_5():
    def f(x):
        #return exp(cos(x[0] ** 2) ** 2 - sin(x[1]) ** 2)
        return -(sin(x[0])**2 + cos(x[1])**2) / (5 + x[0]**2 + x[1]**2)

    def neg_f(x):
        return -f(x)

    x0 = (1, 1)
    x_min = fmin(neg_f, x0)
    print(x_min)

    delta = 4
    x_knots = linspace(x_min[0] - delta, x_min[0] + delta, 41)
    y_knots = linspace(x_min[1] - delta, x_min[1] + delta, 41)
    X, Y = meshgrid(x_knots, y_knots)
    Z = zeros(X.shape)
    for i in range(Z.shape[0]):
        for j in range(Z.shape[1]):
            Z[i][j] = f([X[i, j], Y[i, j]])

    tab_max = x0
    value_max = f(x_min)
    for i in range(100):
        xa = [random.uniform(-3, 3), random.uniform(-3, 3)]
        print("a", xa)
        s = fmin(f, xa)
        print("s", s)
        z = f(s)
        if z < value_max:
            tab_max = s
            value_max = z

    print(tab_max)
    print(value_max)
    ax = Axes3D(figure(figsize=(8, 5)))
    ax.plot_surface(X,
                    Y,
                    Z,
                    rstride=1,
                    cstride=1,
                    cmap=cm.coolwarm,
                    linewidth=0.4)
    ax.plot([x0[0]], [x0[1]], [f(x0)],
            color='g',
            marker='o',
            markersize=5,
            label='initial')
    ax.plot([x_min[0]], [x_min[1]], [f(x_min)],
            color='b',
            marker='o',
            markersize=5,
            label='final')
    ax.plot([tab_max[0]], [tab_max[1]], [f(tab_max)],
            color='r',
            marker='o',
            markersize=10,
            label='best')
    ax.legend()
    show()
Exemplo n.º 23
0
def stepfunction(s):
    ''' eddy diffusivity with discontinuity for testing of mixing scheme'''
    Nparticles = range(s.elements.z.shape[0])
    K = s.environment_profiles['z'] * 0 + 0.1
    K[s.environment_profiles['z'] < -20] = K[s.environment_profiles['z'] < -20] * 0 + 0.02
    N, Kprofiles = sp.meshgrid(Nparticles, K)
    return Kprofiles
Exemplo n.º 24
0
def windspeed_Sundby1983(s):
    depths = s.environment_profiles['z']
    windspeed_squared = s.environment.x_wind**2 + s.environment.y_wind**2
    K = 76.1e-4 + 2.26e-4 * windspeed_squared
    #valid = windspeed_squared < 13**2
    Kprofiles, N = sp.meshgrid(K, depths)
    return Kprofiles
Exemplo n.º 25
0
def corr_high_freq(frame1, frame2, cut_off, one_is_ffted=False):
    """
    Parameters
    ----------


    """
    frame_size_x, frame_size_y = frame2.shape

    x, y = scipy.meshgrid(scipy.arange(-frame_size_x / 2, frame_size_x / 2),
                          scipy.arange(-frame_size_y / 2, frame_size_y / 2))

    freqs = scipy.sqrt(x**2 + y**2)

    frame2 = frame2 - frame2.mean()

    if not one_is_ffted:
        fft_1 = fft2(frame1) / (frame_size_x * frame_size_y)
    else:
        fft_1 = frame1
    fft_2 = fft2(frame2) / (frame_size_x * frame_size_y)

    correlation = fftshift(ifft2(fft_1 * scipy.conj(fft_2) *
                                 (freqs > cut_off)))**2

    return correlation
def Problem3Real():
    beta = 0.9
    N = 1000
    u = lambda c: sp.sqrt(c)
    W = sp.linspace(0, 1, N)
    X, Y = sp.meshgrid(W, W)
    Wdiff = sp.transpose(X - Y)
    index = Wdiff < 0
    Wdiff[index] = 0
    util_grid = u(Wdiff)
    util_grid[index] = -10**10

    Vprime = sp.zeros((N, 1))
    psi = sp.zeros((N, 1))
    delta = 1.0
    tol = 10**-9
    it = 0
    max_iter = 500

    while (delta >= tol) and (it < max_iter):
        V = Vprime
        it += 1
        #print(it)
        val = util_grid + beta * sp.transpose(V)
        Vprime = sp.amax(val, axis=1)
        Vprime = Vprime.reshape((N, 1))
        psi_ind = sp.argmax(val, axis=1)
        psi = W[psi_ind]
        delta = sp.dot(sp.transpose(Vprime - V), Vprime - V)

    return psi
Exemplo n.º 27
0
def relacion_dispersion(npuntos_malla, npasos_temporales, nparticulas,
                        E_acumulador, dt, longitud_malla):

    # Se calcula la frecuencia angular y espacial minima y maxima (Ver codigo KEMPO1):
    omega_min = 2 * sp.pi / (dt) / 2 / (npasos_temporales / 2)
    omega_max = omega_min * (npasos_temporales / 2)
    k_min = 2 * sp.pi / (npuntos_malla)
    k_max = k_min * ((npuntos_malla / 2) - 1)
    # Se crean los vectores de frecuencias espacial y angular simuladas:
    nxtp2 = nextpow2(npuntos_malla)
    k_simulada = sp.linspace(-k_max, k_max, nxtp2) * 10
    omega_simulada = sp.linspace(-omega_max, omega_max, nxtp2) / 10
    #El diez es normalizando con respecto a vt
    # Se genera una matriz de frecuencias angular y espacial:
    K, W = sp.meshgrid(k_simulada, omega_simulada)
    # Se muestrea la matriz espacio-temporal:
    E_acumulador_muestreado = E_acumulador[0:npuntos_malla:1,
                                           0:npasos_temporales:5]
    # Se efectua la FFT sobre la matriz espacio temporal muestreada, luego el
    # valor absoluto de dicha matriz y el corrimiento al cero de las frecuencias:
    E_wk = fft2(
        E_acumulador_muestreado,
        (nextpow2(npuntos_malla), nextpow2(npuntos_malla))) / longitud_malla
    E_wk_absoluto = abs(E_wk)
    E_wk_shift = shift(E_wk_absoluto)
    #    plt.xticks(np.linspace(0,0.7,6), fontsize = 18)
    #    plt.yticks(np.linspace(0,1,5), fontsize = 18)
    # Se grafica la relacion de dispersion simulada:
    plt.contourf(-K, W, E_wk_shift, 8, alpha=.75, cmap='rainbow')
    #    plt.xlim(0,0.7)
    #    plt.ylim(0.0,1.1)
    clb = plt.colorbar()
    clb.ax.set_title('|E|')
    plt.savefig('Graficas/Relaciondispersion.png')
Exemplo n.º 28
0
def plotOrthogonalField(sh, b):
    center=(np.array(sh)-1)/2.0
    C,R=sp.meshgrid(np.array(range(sh[1]), dtype=np.float64), np.array(range(sh[0]), dtype=np.float64))
    R=R-center[0]+b[0]
    C=C-center[1]+b[1]
    plt.figure()
    plt.quiver(R, -C)
Exemplo n.º 29
0
def plot_problem(X, y, h=None, surfaces=True) :
    '''
    Plots a two-dimensional labeled dataset (X,y) and, if function h(x) is given, 
    the decision boundaries (surfaces=False) or decision surfaces (surfaces=True)
    '''
    assert X.shape[1] == 2, "Dataset is not two-dimensional"
    if h!=None : 
        # Create a mesh to plot in
        r = 0.02  # mesh resolution
        x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
        y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
        xx, yy = sp.meshgrid(sp.arange(x_min, x_max, r),
                             sp.arange(y_min, y_max, r))
        XX = sp.c_[xx.ravel(), yy.ravel()]
        try:
            #Z_test = h(XX)
            #if sp.shape(Z_test) == () :
            #    # h returns a scalar when applied to a matrix; map explicitly
            #    Z = sp.array(map(h,XX))
            #else :
            #    Z = Z_test
            Z = sp.array(map(h,XX))
        except ValueError:
            # can't apply to a matrix; map explicitly
            Z = sp.array(map(h,XX))
        # Put the result into a color plot
        Z = Z.reshape(xx.shape)
        if surfaces :
            plt.contourf(xx, yy, Z, cmap=plt.cm.Pastel1)
        else :
            plt.contour(xx, yy, Z)
    # Plot the dataset
    plt.scatter(X[:,0],X[:,1],c=y, cmap=plt.cm.Paired,marker='o',s=50);
Exemplo n.º 30
0
def GetSq(filename,Nsamp=1):
    if type(filename)==str:
        filename=[filename]
    attrs=GetAttr(filename[0])
    #hfile=h5py.File(filename,'r')
    dpath,args=GetStat(filename,Nsamp)
    filetype=''
    try:
        filetype=attrs['type']
    except KeyError:
        mo=re.match('.*/?[0-9]+-(StatSpinStruct)\.h5',filename[0])
        filetype=mo.groups()[0]
    if filetype!='StatSpinStruct':
        raise InputFileError('\"{0}\" is not a static structure factor file'.format(filename))
    N=pow(attrs['L'],2)
    Sq=sc.zeros((Nsamp,5,N),complex)
    for sample,b in enumerate(args):
        for d in b:
            hfile=h5py.File(dpath[d][0],'r')
            dim=hfile[dpath[d][1]].shape[0]
            Sq[sample,:dim,:]+=hfile[dpath[d][1]][0:,0::2]+1j*hfile[dpath[d][1]][0:,1::2]
            hfile.close()
        Sq[sample,:,:]/=len(b)
    qx,qy=sc.meshgrid(np.arange(attrs['L']),np.arange(attrs['L']))
    return qx.flatten(),qy.flatten(),Sq
Exemplo n.º 31
0
def plot_delta():     
    beta = 0.99
    N = 1000
    u = lambda c: sp.sqrt(c)
    W = sp.linspace(0,1,N)
    X, Y = sp.meshgrid(W,W)
    Wdiff = sp.transpose(X-Y)
    index = Wdiff <0
    Wdiff[index] = 0
    util_grid = u(Wdiff)
    util_grid[index] = -10**10
    
    Vprime = sp.zeros((N,1))
    delta = sp.ones(1)
    tol = 10**-9
    it = 0
    max_iter = 500
    
    while (delta[-1] >= tol) and (it < max_iter):
        V = Vprime
        it += 1;
        print(it)
        val = util_grid + beta*sp.transpose(V)
        Vprime = sp.amax(val, axis = 1)
        Vprime = Vprime.reshape((N,1))
        delta = sp.append(delta,sp.dot(sp.transpose(Vprime - V),Vprime-V))
        
    plt.figure()
    plt.plot(delta[1:])
    plt.ylabel(r'$\delta_k$')
    plt.xlabel('iteration')
    plt.savefig('convergence.pdf')
Exemplo n.º 32
0
    def split(self, sagi, meri):
        """ utilizes geometry.grid to change the rectangle into a generalized surface,
        it is specified with a single set of basis vectors to describe the meridonial,
        normal, and sagittal planes."""
        ins = float((sagi - 1))/sagi
        inm = float((meri - 1))/meri
        stemp = self.sagi.s/sagi
        mtemp = self.meri.s/meri

        self.sagi.s,self.meri.s = scipy.meshgrid(scipy.linspace(-self.sagi.s*ins,
                                                                 self.sagi.s*ins,
                                                                 sagi),
                                                 scipy.linspace(-self.meri.s*inm,
                                                                 self.meri.s*inm,
                                                                 meri))

        x_hat = self + (self.sagi + self.meri) #creates a vector which includes all the centers of the subsurface
        self.sagi.s = stemp*sagi #returns values to previous numbers
        self.meri.s = mtemp*meri

        print(x_hat.x().shape)

        temp = Rect(x_hat,
                    self._origin,
                    [2*stemp,2*mtemp],
                    vec=[self.meri.copy(), self.norm.copy()],
                    flag=self.flag)
        #return temp

        return super(Rect, temp).split(temp._origin,
                                       [2*stemp,2*mtemp],
                                       vec=[temp.meri,temp.norm],
                                       flag=temp.flag,
                                       obj=type(temp))
Exemplo n.º 33
0
def w_frequencies(state, spacing):
    """
    This function calculates the FFT frequencies
    """
    nX = state.shape[0]
    nY = state.shape[1]
    return sp.meshgrid(2.0 * sp.pi * pl.fftfreq(nX, spacing), 2.0 * sp.pi * pl.fftfreq(nY, spacing))
Exemplo n.º 34
0
    def __init__(self, filename, outermost_layer=-1):
        print 'initializing tiegcm with {}'.format(filename)
        self.rootgrp = Dataset(filename, 'r')
        self.lat = np.concatenate(
            ([-90], np.array(self.rootgrp.variables['lat']), [90]))
        self.lon = np.array(self.rootgrp.variables['lon'])

        self.boundary_set = []
        self.wrapped = []

        self.set_outermost_layer(outermost_layer)

        self.wrap_longitude()

        self.ilev = np.array(
            self.rootgrp.variables['ilev'])[:self.outermost_layer]

        self.ilev_, self.lat_, self.lon_ = scipy.meshgrid(self.ilev,
                                                          self.lat,
                                                          self.lon,
                                                          indexing='ij')

        self.ut = np.array(self.rootgrp.variables['ut'])
        if self.ut[-1] < self.ut[0]:
            self.ut[-1] += 24

        self.time_range = self.get_time_range()

        self.z_scale = 100000

        self.set_interpolators()

        self.set_3d_boundary_conditions()
        self.wrap_3d_variables()

        self.set_points2D()  # for testing

        self.set_variable_boundary_condition(
            'ZG')  #prior to wrapping to avoid double counting
        self.wrap_variable('ZG')
        self.z = np.array(
            self.rootgrp.variables['ZG']
        )[:, :self.
          outermost_layer, :, :]  # Z is "geopotential height" -- use geometric height ZG?
        self.set_zmax()

        self.high_altitude_trees = dict()
        self.fill_value = np.nan

        self.midpoint_variables = [
            'TN', 'O2', 'O1', 'N2', 'HE', 'ZGMID', 'NO', 'CO2_COOL', 'NO_COOL'
        ]  # index with lev
        self.interface_variables = ['DEN', 'ZG', 'Z']  #index with ilev

        self.set_variable_boundary_condition(
            'ZGMID')  #prior to wrapping to avoid double counting
        self.wrap_variable('ZGMID')
        self.zgmid = np.array(self.rootgrp.variables['ZGMID']
                              )[:, :self.outermost_layer, :, :]  # zach added
        self.zgmid_scale = 100000
Exemplo n.º 35
0
def getMeshGrid(t, z, minT=None, maxT=None, export=False):
    if minT is None:
        minT = t.min()
    if maxT is None:
        maxT = t.max()

    nt = settings.XGDS_PLOT_PROFILE_TIME_GRID_RESOLUTION
    intervalStart = minT + TIME_OFFSET_DAYS
    if export:
        dt = EXPORT_TIME_RESOLUTION
        intervalStart = int(float(intervalStart) / dt) * dt
    else:
        dt = float(maxT - minT) / nt
    tvals = np.arange(intervalStart,
                      maxT + TIME_OFFSET_DAYS,
                      dt)

    if 0:
        minZ = z.min()
        maxZ = z.max()
        nz = settings.XGDS_PLOT_PROFILE_Z_GRID_RESOLUTION
        dz = float(maxZ - minZ) / nz
        zvals = np.arange(minZ, maxZ, dz)

    zvals = np.arange(*settings.XGDS_PLOT_PROFILE_Z_RANGE)

    return scipy.meshgrid(tvals, zvals)
Exemplo n.º 36
0
def m_circles(mags, phase_min=-359.75, phase_max=-0.25):
    """Constant-magnitude contours of the function Gcl = Gol/(1+Gol), where
    Gol is an open-loop transfer function, and Gcl is a corresponding
    closed-loop transfer function.

    Usage
    =====
    contours = m_circles(mags, phase_min, phase_max)

    Parameters
    ----------
    mags : array-like
        Array of magnitudes in dB of the M-circles
    phase_min : degrees
        Minimum phase in degrees of the N-circles
    phase_max : degrees
        Maximum phase in degrees of the N-circles

    Return values
    -------------
    contours : complex array
        Array of complex numbers corresponding to the contours.
    """
    # Convert magnitudes and phase range into a grid suitable for
    # building contours
    phases = sp.radians(sp.linspace(phase_min, phase_max, 2000))
    Gcl_mags, Gcl_phases = sp.meshgrid(10.0**(mags/20.0), phases)
    return closed_loop_contours(Gcl_mags, Gcl_phases)
Exemplo n.º 37
0
def n_circles(phases, mag_min=-40.0, mag_max=12.0):
    """Constant-phase contours of the function Gcl = Gol/(1+Gol), where
    Gol is an open-loop transfer function, and Gcl is a corresponding
    closed-loop transfer function.

    Usage
    ===== 
    contours = n_circles(phases, mag_min, mag_max)

    Parameters
    ----------
    phases : array-like
        Array of phases in degrees of the N-circles
    mag_min : dB
        Minimum magnitude in dB of the N-circles
    mag_max : dB
        Maximum magnitude in dB of the N-circles

    Return values
    -------------
    contours : complex array
        Array of complex numbers corresponding to the contours.
    """
    # Convert phases and magnitude range into a grid suitable for
    # building contours    
    mags = sp.linspace(10**(mag_min/20.0), 10**(mag_max/20.0), 2000)
    Gcl_phases, Gcl_mags = sp.meshgrid(sp.radians(phases), mags)
    return closed_loop_contours(Gcl_mags, Gcl_phases)
Exemplo n.º 38
0
def Problem3Real():
    beta = 0.9
    N = 1000
    u = lambda c: sp.sqrt(c)
    W = sp.linspace(0,1,N)
    X, Y = sp.meshgrid(W,W)
    Wdiff = sp.transpose(X-Y)
    index = Wdiff <0
    Wdiff[index] = 0
    util_grid = u(Wdiff)
    util_grid[index] = -10**10
    
    Vprime = sp.zeros((N,1))
    psi = sp.zeros((N,1))
    delta = 1.0
    tol = 10**-9
    it = 0
    max_iter = 500
    
    while (delta >= tol) and (it < max_iter):
        V = Vprime
        it += 1;
        #print(it)
        val = util_grid + beta*sp.transpose(V)
        Vprime = sp.amax(val, axis = 1)
        Vprime = Vprime.reshape((N,1))
        psi_ind = sp.argmax(val,axis = 1)
        psi    = W[psi_ind]
        delta = sp.dot(sp.transpose(Vprime - V),Vprime-V)
    
    return psi
Exemplo n.º 39
0
def Problem1Real():
    beta = 0.9;
    T = 10;
    N = 100;
    u = lambda c: sp.sqrt(c);
    W = sp.linspace(0,1,N);
    X, Y = sp.meshgrid(W,W);
    Wdiff = Y-X
    index = Wdiff <0;
    Wdiff[index] = 0;
    util_grid = u(Wdiff);
    util_grid[index] = -10**10;
    V = sp.zeros((N,T+2));
    psi = sp.zeros((N,T+1));


    for k in xrange(T,-1,-1):
        val = util_grid + beta*sp.tile(sp.transpose(V[:,k+1]),(N,1));
        vt = sp.amax(val, axis = 1);
        psi_ind = sp.argmax(val,axis = 1)
        V[:,k]    = vt;
        psi[:,k]    = W[psi_ind];

    
    return V,psi
Exemplo n.º 40
0
def plot_mixture(fig, mixture, data):
    plt.subplot(fig)

    # Plot data.
    plt.scatter(data[:, 0], data[:, 1], color='r', marker='+', alpha=0.5)

    delta = 1.0
    coords = []
    # TODO: Should be configurable...
    xs = scipy.arange(-30, 30, delta)
    ys = scipy.arange(-30, 30, delta)
    for x in xs:
        for y in ys:
            coords.append((x, y))

    coords = scipy.asarray(coords)

    Z = None
    for i in range(mixture.degree):
        gaussian = MultivariateGaussianDensity(mixture.means[i],
                                               mixture.covs[i])
        z = mixture.mixcoeffs[i] * gaussian.multpdf(coords)

        if Z is None:
            Z = z
        else:
            Z += z

    X, Y = scipy.meshgrid(xs, ys)
    Z.shape = X.shape

    CS = plt.contour(X, Y, Z, 30)
    plt.plot(mixture.means[:, 1], mixture.means[:, 0], 'o', color='green')
Exemplo n.º 41
0
    def __plot__(self, show=True, save=False, title="no_title", max_pix=(1000, 1000), limit=()):
        x_step = int(self.mesh.x_num / max_pix[0]) + 1
        t_step = int(self.mesh.x_num / max_pix[1]) + 1
        x_grid, t_grid = meshgrid(self.mesh.x_vector[::x_step], self.mesh.t_vector[::t_step])
        phi2 = absolute(self.solution()[1::t_step, ::x_step]) ** 2
        potential_ = self.potential.vector
        x = self.mesh.x_vector
        fig = figure()
        above = fig.add_axes((0.06, 0.25, 0.9, 0.7))
        under = fig.add_axes((0.06, 0.1, 0.9, 0.17), sharex=above)

        above.set_title(title)
        above.tick_params(labelbottom="off")
        above.set_ylabel("time(a.u.)")
        under.tick_params(labelleft="off")
        under.set_xlabel("space(a.u.)")

        above.pcolormesh(x_grid, t_grid, phi2, cmap="nipy_spectral_r")
        under.plot(x, potential_)

        if limit is not ():
            above.set_xlim(*limit)
            under.set_xlim(*limit)

        if save:
            fig.savefig(title + ".png")

        if show:
            fig.show()
        return fig
Exemplo n.º 42
0
def plot_delta():     
    beta = 0.99
    N = 1000
    u = lambda c: sp.sqrt(c)
    W = sp.linspace(0,1,N)
    X, Y = sp.meshgrid(W,W)
    Wdiff = sp.transpose(X-Y)
    index = Wdiff <0
    Wdiff[index] = 0
    util_grid = u(Wdiff)
    util_grid[index] = -10**10
    
    Vprime = sp.zeros((N,1))
    delta = sp.ones(1)
    tol = 10**-9
    it = 0
    max_iter = 500
    
    while (delta[-1] >= tol) and (it < max_iter):
        V = Vprime
        it += 1;
        print(it)
        val = util_grid + beta*sp.transpose(V)
        Vprime = sp.amax(val, axis = 1)
        Vprime = Vprime.reshape((N,1))
        delta = sp.append(delta,sp.dot(sp.transpose(Vprime - V),Vprime-V))
        
    plt.figure()
    plt.plot(delta[1:])
    plt.ylabel(r'$\delta_k$')
    plt.xlabel('iteration')
    plt.savefig('convergence.pdf')
Exemplo n.º 43
0
    def split(self, sagi, meri):
        """ utilizes geometry.grid to change the rectangle into a generalized surface,
        it is specified with a single set of basis vectors to describe the meridonial,
        normal, and sagittal planes."""
        ins = old_div(float((sagi - 1)), sagi)
        inm = old_div(float((meri - 1)), meri)
        stemp = old_div(self.sagi.s, sagi)
        mtemp = old_div(self.meri.s, meri)

        self.sagi.s, self.meri.s = scipy.meshgrid(
            scipy.linspace(-self.sagi.s * ins, self.sagi.s * ins, sagi),
            scipy.linspace(-self.meri.s * inm, self.meri.s * inm, meri))

        x_hat = self + (
            self.sagi + self.meri
        )  #creates a vector which includes all the centers of the subsurface
        self.sagi.s = stemp * sagi  #returns values to previous numbers
        self.meri.s = mtemp * meri

        print(x_hat.x().shape)

        temp = Rect(x_hat,
                    self._origin, [2 * stemp, 2 * mtemp],
                    vec=[self.meri.copy(), self.norm.copy()],
                    flag=self.flag)
        #return temp

        return super(Rect, temp).split(temp._origin, [2 * stemp, 2 * mtemp],
                                       vec=[temp.meri, temp.norm],
                                       flag=temp.flag,
                                       obj=type(temp))
def plotDecisionBoundary(data, X, theta):
    """
    Plots the data points X and y into a new figure with the
    decision boundary defined by theta
    """
    plotData(data)
    if X.shape[1] <= 3:
        plot_x = sp.array([min(X[:, 1]), max(X[:, 1])])
        plot_y = (-1.0 / theta[2]) * (theta[1] * plot_x + theta[0])
        plt.plot(plot_x, plot_y)
        plt.axis([30, 100, 30, 100])
    else:
        u = sp.linspace(-1, 1.5, 50)
        v = sp.linspace(-1, 1.5, 50)
        z = sp.zeros((len(u), len(v)))

        for i in range(0, len(u)):
            for j in range(0, len(v)):
                z[i, j] = (mapFeature(sp.array([u[i]]), sp.array([v[j]]))).dot(theta)

        z = z.T # important to transpose z before calling contour

        u, v = sp.meshgrid(u, v)

        plt.contour(u, v, z, [0.0, 0.0])
Exemplo n.º 45
0
 def initiatespatial(self):
     self.spatial=True
     self.pMap = Basemap(projection='stere',lat_0=68.0,lon_0=15.0,llcrnrlon=3.,llcrnrlat=60.3,urcrnrlon=47.0,urcrnrlat=71.,resolution='c')
     self.x, self.y = self.pMap(self.lon, self.lat)
     XI,ETA = sp.meshgrid(range(self.y.shape[1]),range(self.y.shape[0]))
     self.xip, self.etap = XI.ravel(), ETA.ravel()
     self.Tree = spatial.KDTree(zip(self.x.ravel(), self.y.ravel()))
Exemplo n.º 46
0
    def to_window(self, **params):

        window = WindowFunction2D(**params)

        ells = self.result.ells
        sedges = self.result.sedges
        counts = self.result.counts

        window.poles = [(ell1, ell2) for ell1 in ells[0] for ell2 in ells[1]]
        window.los = self.result.los
        window.s = map(edges_to_mid, sedges)
        window.window = counts.reshape((-1, ) + counts.shape[2:])
        if window.zero in window:
            window.error = window.window[window.index(window.zero)]**(1. / 4.)

        volume = (4. * constants.pi)**2 * scipy.prod(scipy.meshgrid(
            *map(radial_volume, sedges), sparse=False, indexing='ij'),
                                                     axis=0)
        for ill, (ell1, ell2) in enumerate(window):
            window.window[ill] *= (2 * ell1 + 1) * (2 * ell2 + 1) / volume

        window.window /= self.normalization
        if hasattr(window, 'error'):
            window.error /= volume * self.normalization

        window.norm = self.normref
        window.pad_zero()

        return window
Exemplo n.º 47
0
    def split(self, sagi, meri):
        """ utilizes geometry.grid to change the rectangle into a generalized surface,
        it is specified with a single set of basis vectors to describe the meridonial,
        normal, and sagittal planes."""
        ins = float((sagi - 1))/sagi
        inm = float((meri - 1))/meri
        stemp = self.norm.s/sagi
        mtemp = self.meri.s/meri

        z,theta = scipy.meshgrid(scipy.linspace(-self.norm.s*ins,
                                                self.norm.s*ins,
                                                sagi),
                                 scipy.linspace(-self.meri.s*inm,
                                                self.meri.s*inm,
                                                meri))

        vecin =geometry.Vecr((self.sagi.s*scipy.ones(theta.shape),
                              theta+scipy.pi/2,
                              scipy.zeros(theta.shape))) #this produces an artificial
        # meri vector, which is in the 'y_hat' direction in the space of the cylinder
        # This is a definite patch over the larger problem, where norm is not normal
        # to the cylinder surface, but is instead the axis of rotation.  This was
        # done to match the Vecr input, which works better with norm in the z direction
               
        pt1 = geometry.Point(geometry.Vecr((scipy.zeros(theta.shape),
                                            theta,
                                            z)),
                             self)

        pt1.redefine(self._origin)

        vecin = vecin.split()

        x_hat = self + pt1 #creates a vector which includes all the centers of the subsurface

        out = []
        #this for loop makes me cringe super hard
        for i in xrange(meri):
            try:
                temp = []
                for j in xrange(sagi):
                    inp = self.rot(vecin[i][j])
                    temp += [Cyl(geometry.Vecx(x_hat.x()[:,i,j]),
                                 self._origin,
                                 [2*stemp,2*mtemp],
                                 self.sagi.s,
                                 vec=[inp, self.norm.copy()],
                                 flag=self.flag)]
                out += [temp]
            except IndexError:
                inp = self.rot(vecin[i])
                out += [Cyl(geometry.Vecx(x_hat.x()[:,i]),
                            self._origin,
                            [2*stemp,2*mtemp],
                            self.norm.s,
                            vec=[inp, self.norm.copy()],
                            flag=self.flag)]
                

        return out
Exemplo n.º 48
0
 def find_contour(self,mask,level=0.5):
     """ returns a list of segments """
     import matplotlib._cntr as cntr
     X,Y = sp.meshgrid(sp.arange(mask.shape[0]),sp.arange(mask.shape[1]))
     c = cntr.Cntr(X, Y, mask.T)
     nlist = c.trace(level, level, 0)
     segs = nlist[:len(nlist)//2]
     return segs
Exemplo n.º 49
0
def phase_plot(func, max_time=1.0, numx = 10, numv = 10, spread_amp = 1.25, args = (), span = (-1,1,-1,1)):
    """Plot the phase plane plot of the function defined by func.

    Parameters
    -----------
    func : string like
           name of function providing state derivatives
    max_time : float, optional
               total time of integration
    numx, numy : floats, optional
                 number of starting points for the grid of integrations
    spread_amp : float, optional
                 axis "growth" for plotting, relative to initial grid
    args : float, other
           arguments needed by the state derivative function
    span : 4-tuple of floats, optional
           (xmin, xmax, ymin, tmax)
    """
    x = sp.linspace(span[0], span[1], numx)
    v = sp.linspace(span[2], span[3], numv)
    x0, v0 = sp.meshgrid(x, v)
    x0.shape = (numx*numv,1) # Python array trick to reorganize numbers in an array
    v0.shape = (numx*numv,1)
    x0 = sp.concatenate((x0, v0), axis = 1)
    N = x0.shape[0]
    # Solve for the trajectories
    t = sp.linspace(0, max_time, int(250*max_time))
    x_t = sp.asarray([sp.integrate.odeint(func, y0 = x0i, t = t, args = args)
                      for x0i in x0])

    for i in range(N):
        x, v = x_t[i,:,:].T            
        line, = plt.plot(x, v,'-')
        #Let's plot '*' at the end of each trajectory.
        plt.plot(x[-1],v[-1],'^')
    plt.grid('on')
    xrange = (span[1]-span[0])/2
    xmid = (span[0]+span[1])/2
    yrange = (span[3]-span[2])/2
    ymid = (span[3]+span[2])/2
    plt.axis((xmid-spread_amp*xrange,xmid+spread_amp*xrange,ymid-spread_amp*yrange,ymid+spread_amp*yrange))
    #print(plt.axis())
    head_length = .1*sp.sqrt(xrange**2+yrange**2)
    head_width = head_length/3
    for i in range(N):
        x, v = x_t[i,:,:].T
        if abs(x[-1]-x[-2]) > 0 or abs(v[-1]-v[-2]) > 0:
            dx = x[-1]-x[-2]
            dv = v[-1]-v[-2]
            length = sp.sqrt(dx**2+dv**2)
            delx = dx/length*head_length
            delv = dv/length*head_length
            #plt.arrow(x[-1],v[-1],(x[-1]-x[-2])/1000,(v[-1]-v[-2])/1000, head_width=head_width, head_length = head_length, fc='k', ec='k', length_includes_head = True, width = 0.0)#,'-')
            #plt.annotate(" ", xy = (x[-1],v[-1]),xytext = (x[-1]-delx,v[-2]-delv),arrowprops=dict(facecolor='black',width = 2, frac = .5))
        plt.plot(x[0],v[0],'.')

        
    return line
def U_cheby_nodes_2D(N1, N2):
	"""
	A function to compute the positions (x,y) of the nodes of the
	2-dimensional Chebyshev polynomials of degree (N1,N2).
	"""

	x_cheby = numpy.array([numpy.cos(numpy.pi*(2*idx+1)/N1/2) for idx in range(N1)])
	y_cheby = numpy.array([numpy.cos(numpy.pi*(2*idx+1)/N2/2) for idx in range(N2)])
	return scipy.meshgrid(x_cheby, x_cheby)
Exemplo n.º 51
0
def RiemannSurface2():
    """riemann surface for imaginary part of sqrt(z)"""

    fig = plt.figure()
    ax = Axes3D(fig)
    X = sp.arange(-5, 5, 0.25)
    Y = sp.arange(-5, 0, 0.25)
    X, Y = sp.meshgrid(X, Y)
    Z = sp.imag(sp.sqrt(X+1j*Y))
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, linewidth=0, cmap=cmap_r)
    ax.plot_surface(X, Y, -Z, rstride=1, cstride=1, linewidth=0, cmap=cmap)
    X = sp.arange(-5, 5, 0.25)
    Y = sp.arange(0,5,.25)
    X, Y = sp.meshgrid(X, Y)
    Z = sp.imag(sp.sqrt(X+1j*Y))
    ax.plot_surface(X, Y, -Z, rstride=1, cstride=1, linewidth=0, cmap=cmap_r)
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, linewidth=0, cmap=cmap)
    plt.savefig('RiemannSurface2.pdf', bbox_inches='tight', pad_inches=0)
Exemplo n.º 52
0
def plotSurface(x, y, z, contour_plot=True, title=None,filename=None):
    from mpl_toolkits.mplot3d import Axes3D
    from scipy import meshgrid, array
    import scipy.interpolate

    fig = plt.figure()

    if contour_plot:
        ax = fig.add_subplot(111)
    else:
        ax = fig.add_subplot(111, projection='3d')

    x_coordinates = x
    y_coordinates = y

    f_int = scipy.interpolate.RectBivariateSpline(x_coordinates,y_coordinates, z)

    #x_coordinates = np.linspace(min(x_coordinates), max(x_coordinates), 400)
    #y_coordinates = np.linspace(min(y_coordinates), max(y_coordinates), 400)
    #z = f_int(x_coordinates, y_coordinates)

    if isinstance(z,np.ndarray):
        plane = []
        for i_x in range(len(x_coordinates)):
            for i_y in range(len(y_coordinates)):
                plane.append(float(z[i_x,i_y]))
    else:
        plane = z

    X, Y = meshgrid(x_coordinates,
                    y_coordinates)

    zs = array(plane)

    Z = z.transpose()# zs.reshape(X.shape)

    if contour_plot:
        CS = ax.contour(X, Y, Z)
        CB = plt.colorbar(CS, shrink=0.8, extend='both')
    else:
        ax.plot_surface(X, Y, Z)

    ax.set_xlabel('X in plane')
    ax.set_ylabel('Y in plane')

    if not contour_plot:
        ax.set_zlabel('z')


    if title is not None:
        plt.title(title)

    if filename is None:
        plt.show()
    else:
        plt.savefig(filename, bbox_inches='tight')
Exemplo n.º 53
0
 def __call__(self, xstart, xend, ystart, yend):
     self.x = sp.linspace(xstart, xend, self.width)
     self.y = sp.linspace(ystart, yend, self.height)
     X,Y = sp.meshgrid(self.x,self.y)
     #c = 0.4+0.125j
     z = X+1.0j*Y
     for i in xrange(self.niter):
         z = z**self.power + self.c
         W = sp.exp(-abs(z))
     return W