Beispiel #1
0
def plotForceField(mouse,points,delta=0.,cm=0.):
    N=51
    sz=12
    rng=np.linspace(-sz,sz,N)
    R=np.zeros((N,N,2))
    for x in range(rng.size):
        for y in range(rng.size):
            offset=np.array([np.cos(points[:,2]),np.sin(points[:,2])]).T
            res=computeForce([rng[x],rng[y]],points=points[:,:2]+delta*offset,
                             maxmag=0.1,circlemass=cm)
            R[x,y,:]=res#np.linalg.norm(res)
    plt.cla()
    c=plt.Circle((0,0),radius=11.75,fill=False)
    plt.gca().add_patch(c)
    plt.plot(points[:,0],points[:,1],'ks',ms=8)
    plt.plot(mouse[0],mouse[1],'go',ms=8)
    plt.xlim([-12,12])
    plt.ylim([-12,12])
    plt.gca().set_aspect(1)
    #plt.pcolormesh(rng,rng,R.T,vmax=0.1)
    #R=np.square(R)
    plt.quiver(rng,rng,R[:,:,0].T,R[:,:,1].T,np.linalg.norm(R,axis=2).T,scale=3)
    #plt.pcolormesh(rng,rng,np.linalg.norm(R,axis=2).T)
    loc,minforce,ms=findNearestLocalMin(points[:,:2],start=np.copy(mouse[:2]),
                                        circlemass=cm)
    plt.plot(loc[0],loc[1],'bd',ms=8)
    plt.grid(b=False)
    ax=plt.gca()
    ax.spines['top'].set_visible(True)
    ax.spines['right'].set_visible(True)
    ax.set_xticklabels([]);ax.set_yticklabels([])
Beispiel #2
0
def ode_slope_1state(func, x_list, time_list):
    """
    Plot field of arrows indicating derivatives of the state
    :param func:
    :param x_list:
    :param time_list:
    :return:
    """
    time_mesh, x_mesh = np.meshgrid(time_list, x_list)
    u_mesh = np.ones_like(x_mesh)
    v_mesh = func(x_mesh, time_mesh)
    # magnitude as color
    color_mesh = np.sqrt(u_mesh * u_mesh + v_mesh * v_mesh)

    # https://stackoverflow.com/questions/29589119/plot-width-settings-in-ipython-notebook
    py.figure(figsize=(12, 12))
    py.quiver(time_mesh, x_mesh, u_mesh, v_mesh, color_mesh, angles='xy')

    xy_labels()

    py.xlim(
        (time_list[0] - (time_list[1] - time_list[0]) * 0.125, time_list[-1]))
    py.ylim((min(x_list) - (x_list[1] - x_list[0]) * 0.125,
             max(x_list) + (x_list[-1] - x_list[-2]) * 0.125))
    py.grid(True)
Beispiel #3
0
def whiskerplot(shear,dRA=1.,dDEC=1.,scale=5, combine=1, offset=(0,0) ):
    if combine>1:
        s = (combine*int(shear.shape[0]/combine),
             combine*int(shear.shape[1]/combine))
        shear = shear[0:s[0]:combine, 0:s[1]:combine] \
                + shear[1:s[0]:combine, 0:s[1]:combine] \
                + shear[0:s[0]:combine, 1:s[1]:combine] \
                + shear[1:s[0]:combine, 1:s[1]:combine]
        shear *= 0.25

        dRA *= combine
        dDEC *= combine

    
    theta = shear**0.5
    RA = offset[0] + np.arange(shear.shape[0])*dRA
    DEC = offset[1] + np.arange(shear.shape[1])*dDEC

    pylab.quiver(RA,DEC,
                 theta.real.T,theta.imag.T,
                 pivot = 'middle',
                 headwidth = 0,
                 headlength = 0,
                 headaxislength = 0,
                 scale=scale)
    pylab.xlim(0,shear.shape[0]*dRA)
    pylab.ylim(0,shear.shape[1]*dDEC)
    pylab.xlabel('RA (arcmin)')
    pylab.ylabel('DEC (arcmin)')
Beispiel #4
0
def spatial_plot_with_arrows(x,
                             y,
                             v1,
                             v2,
                             arrow_scale,
                             title,
                             xlabel,
                             ylabel,
                             xlim=False,
                             ylim=False):
    """
    Function to plot quiver plots, when velocity info is desired alongside position
    """
    plt.figure()
    pylab.quiver(x,
                 y,
                 v1,
                 v2,
                 angles='uv',
                 scale_units='xy',
                 scale=arrow_scale)
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    if xlim != False:
        plt.xlim(xlim)
    if ylim != False:
        plt.ylim(ylim)
Beispiel #5
0
def transform(W):
    global N
    print W[20]
    t = 20


    MM = N
    N = 356

    #bakk = W[t]
    arr = np.zeros((N+1,N+1)).astype(np.float32)

    # interpolation in order to keep baking in 32 array elements (for stability)
    bakk = interp1d(range(MM+1), W[t], kind='cubic')

    for i in range(-N/2,N/2+1):
        for j in range(-N/2,N/2+1):
            i2 = i
            j2 = j
            r = np.sqrt(i2*i2+j2*j2).astype(np.float32)
            if(r < N and r >= 0):
                arr[N/2-i,N/2-j] = bakk((N-r)*MM/N)

    if(False):
        I2 = Image.frombuffer('L',(N+1,N+1), (arr).astype(np.uint8),'raw','L',0,1)
        imgplot = plt.imshow(I2)
        plt.colorbar()
        gx, gy = np.gradient(arr)
        pylab.quiver(gx,gy)
        pylab.show()

        plt.show()
    #print "Saving Image res.png..."
    #I2.save('res.png')
    return arr
Beispiel #6
0
def main(argv=None):
  if argv is None:
    argv=sys.argv
  iresfile=argv[1];
  try:
    ct=float(argv[2]);
  except:
    ct=0.0
  ires=adore.res2dict(iresfile);
  A=ires['fine_coreg']['results'];
  A=A[A[:,5]>ct,:]
  az=int(ires['fine_coreg']['Initial offsets'].split(',')[0]);
  rg=int(ires['fine_coreg']['Initial offsets'].split(',')[1]);
#figure1
  pylab.figure()
  pylab.title('Fine Correlation Results')
  pylab.quiver(A[:,2], A[:,1], A[:,4], A[:,3], A[:,5]);
  pylab.colorbar()
#figure2

  pylab.figure()
  pylab.title('Fine Correlation Deviations')
  pylab.quiver(A[:,2], A[:,1], A[:,4]-rg, A[:,3]-az, A[:,5]);
  pylab.colorbar()
  pylab.show()
Beispiel #7
0
def plotSurface(pt, td, winds, map, stride, title, file_name):
    pylab.figure()
    pylab.axes((0.05, 0.025, 0.9, 0.9))

    u, v = winds

    nx, ny = pt.shape
    gs_x, gs_y = goshen_3km_gs
    xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny))   

    data_thin = tuple([ slice(None, None, stride) ] * 2)

    td_cmap = matplotlib.cm.get_cmap('Greens')
    td_cmap.set_under('#ffffff')
    pylab.contourf(xs, ys, td, levels=np.arange(40, 80, 5), cmap=td_cmap)
    pylab.colorbar()
    CS = pylab.contour(xs, ys, pt, colors='r', linestyles='-', linewidths=1.5, levels=np.arange(288, 324, 4))
    pylab.clabel(CS, inline_spacing=0, fmt="%d K", fontsize='x-small')
    pylab.quiver(xs[data_thin], ys[data_thin], u[data_thin], v[data_thin])

    drawPolitical(map, scale_len=75)

    pylab.suptitle(title)
    pylab.savefig(file_name)
    pylab.close()
    return
Beispiel #8
0
def quiver_image(X, Y, U, V):
    pylab.figure(1)
    pylab.quiver(X, Y, U, V)
    canvas = pylab.get_current_fig_manager().canvas
    canvas.draw()
    pil_image = Image.fromstring('RGB', canvas.get_width_height(), canvas.tostring_rgb())
    return pil_image
Beispiel #9
0
def gradient_demo(pxs):
    """Plot mean amplitudes (and their gradients) EM cascade light source."""

    t_edges, az_edges, amps, grads = azi_scan(
        pxs,
        t_edges=numpy.linspace(0, 300, 51),
        az_edges=numpy.linspace(-180, 180, 51),
        omx=-50)  ### See azi_scan() for comments

    import pylab as p
    from icecube.icetray import I3Units

    mid = lambda t: 0.5 * (t[1:] + t[:-1])
    T, A = numpy.meshgrid(mid(t_edges), mid(az_edges))

    fig = p.figure(figsize=(12, 6))
    fig.subplots_adjust(left=0.06, right=0.96)

    p.subplot(1, 2, 1)
    ax = p.gca()
    colorplot = ax.pcolorfast(az_edges, t_edges, amps.transpose())
    cb = p.colorbar(colorplot)
    cb.set_label('mean PE')
    p.xlabel('source-observer angle [deg]')
    p.ylabel('delay time [ns]')
    p.title('Mean amplitudes')

    p.subplot(1, 2, 2)
    p.quiver(A, T, grads[:, :, 5] * I3Units.degree, grads[:, :, 3])
    p.xlabel('source-observer angle [deg]')
    p.ylabel('delay time [ns]')
    p.title('Amplitude gradients')
Beispiel #10
0
def draw_MAP_residuals(objectsA, objectsB, P, scaled='no'):
    from pyBA.distortion import compute_displacements, compute_residual
    from numpy import array
    
    # Compute displacements between frames for tie objects
    xobs, yobs, vxobs, vyobs, sxobs, syobs = compute_displacements(objectsA, objectsB)

    # Compute residual
    dx, dy = compute_residual(objectsA, objectsB, P)

    # Draw residuals
    fig = figure(figsize=(16,16))
    ax = fig.add_subplot(111, aspect='equal')
    if scaled is 'yes':
        # Allow relative scaling of arrows
        quiver(xobs,yobs,dx,dy)
    else:
        # Show residuals in absolute size (often very tiny), with uncertainties

        # Also plot error ellipses
        ellipses = array([ Bivarg( mu = array([xobs[i] + dx[i], yobs[i] + dy[i]]),
                                   sigma = objectsA[i].sigma + objectsB[i].sigma )
                           for i in range(len(objectsA)) ])
        draw_objects(ellipses, replot='yes')

        # Residuals
        quiver(xobs,yobs,dx,dy,color='r', angles='xy', scale_units='xy', scale=1)
    ax.autoscale(enable=None, axis='both', tight=True)
    show()
Beispiel #11
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    iresfile = argv[1]
    try:
        ct = float(argv[2])
    except:
        ct = 0.0
    ires = adore.res2dict(iresfile)
    A = ires['fine_coreg']['results']
    A = A[A[:, 5] > ct, :]
    az = int(ires['fine_coreg']['Initial offsets'].split(',')[0])
    rg = int(ires['fine_coreg']['Initial offsets'].split(',')[1])
    #figure1
    pylab.figure()
    pylab.title('Fine Correlation Results')
    pylab.quiver(A[:, 2], A[:, 1], A[:, 4], A[:, 3], A[:, 5])
    pylab.colorbar()
    #figure2

    pylab.figure()
    pylab.title('Fine Correlation Deviations')
    pylab.quiver(A[:, 2], A[:, 1], A[:, 4] - rg, A[:, 3] - az, A[:, 5])
    pylab.colorbar()
    pylab.show()
Beispiel #12
0
def main():
    # Create the grid
    x = arange(-100, 101)
    y = arange(-100, 101)

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

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

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

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

    # Draw the quivers and the image
    clf()
    imshow(F, cmap=cm.gray, extent=(-100, 100, -100, 100))
    quiver(ys, xs, -FFy, FFx, color='red')
    show()
Beispiel #13
0
        def doSubplot(multiplier=1.0, layout=(-1, -1)):
            if time_sec < 16200:
                xs, ys = xs_1, ys_1
                domain_bounds = bounds_1sthalf
                grid = grid_1
            else:
                xs, ys = xs_2, ys_2
                domain_bounds = bounds_2ndhalf
                grid = grid_2

            try:
                mo = ARPSModelObsFile("%s/%s/KCYS%03dan%06d" % (base_path, exp, min_ens, time_sec))
            except AssertionError:
                mo = ARPSModelObsFile("%s/%s/KCYS%03dan%06d" % (base_path, exp, min_ens, time_sec), mpi_config=(2, 12))
            except:
                print "Can't load reflectivity ..."
                mo = {'Z':np.zeros((1, 255, 255), dtype=np.float32)}

            pylab.contour(xs, ys, wind[exp]['w'][wdt][domain_bounds], levels=np.arange(2, 102, 2), styles='-', colors='k')
            pylab.contour(xs, ys, wind[exp]['w'][wdt][domain_bounds], levels=np.arange(-100, 0, 2), styles='--', colors='k')

            pylab.quiver(xs[thin], ys[thin], wind[exp]['u'][wdt][domain_bounds][thin], wind[exp]['v'][wdt][domain_bounds][thin])

            pylab.contourf(xs, ys, mo['Z'][0][domain_bounds], levels=np.arange(10, 85, 5), cmap=NWSRef, zorder=-10)

            grid.drawPolitical(scale_len=10)

            row, col = layout
            if col == 1:
                pylab.text(-0.075, 0.5, exp_names[exp], transform=pylab.gca().transAxes, rotation=90, ha='center', va='center', size=12 * multiplier)
Beispiel #14
0
def plotSurface(pt, td, winds, map, stride, title, file_name):
    pylab.figure()
    pylab.axes((0.05, 0.025, 0.9, 0.9))

    u, v = winds

    nx, ny = pt.shape
    gs_x, gs_y = goshen_3km_gs
    xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny))

    data_thin = tuple([slice(None, None, stride)] * 2)

    td_cmap = matplotlib.cm.get_cmap('Greens')
    td_cmap.set_under('#ffffff')
    pylab.contourf(xs, ys, td, levels=np.arange(40, 80, 5), cmap=td_cmap)
    pylab.colorbar()
    CS = pylab.contour(xs,
                       ys,
                       pt,
                       colors='r',
                       linestyles='-',
                       linewidths=1.5,
                       levels=np.arange(288, 324, 4))
    pylab.clabel(CS, inline_spacing=0, fmt="%d K", fontsize='x-small')
    pylab.quiver(xs[data_thin], ys[data_thin], u[data_thin], v[data_thin])

    drawPolitical(map, scale_len=75)

    pylab.suptitle(title)
    pylab.savefig(file_name)
    pylab.close()
    return
 def vectorField(self,plt,X,Y,U,V,title):
     if self.plotFields:
         # Create mask corresponding to 0 fluid velocity values inside obstructions
         M = zeros([X.quiverLength,Y.quiverLength],dtype='bool')
         M = (U.quiver == 0)
         
         # Mask the obstructions in the fluid velocity vector field
         U.quiver = ma.masked_array(U.quiver,mask=M)
         V.quiver = ma.masked_array(V.quiver,mask=M)
         
         # Build and scale the plot
         fig = plt.figure()        
         ax = fig.add_subplot(111)
         ax.set_ylim(Y.minValue, Y.maxValue)
         ax.set_xlim(X.minValue, X.maxValue)
         pos1 = ax.get_position()  
         pos2 = [pos1.x0+((pos1.width - (pos1.width*self.scaleX))*.5), pos1.y0+((pos1.height - (pos1.height*self.scaleY))*.5),  pos1.width*self.scaleX, pos1.height*self.scaleY] 
         ax.set_position(pos2)
         title = title + ' Vector Field'        
         plt.title(title)
         plt.xlabel("X [m]")
         plt.ylabel("Y [m]")
         plt.grid()
         
         quiver(X.quiver,Y.quiver,U.quiver,V.quiver)        
     
     
 
             
Beispiel #16
0
def plot_mag_field(data_U, time='dom_swo', mask_U='Master'):
    x = data_U.get_data(mask_U, time)
    y = numpy.zeros(len(x))
    br = data_U.get_data(mask_U, 'Br')
    bt = data_U.get_data(mask_U, 'Bt')
    pylab.figure()
    pylab.quiver(x, y, br, bt, scale=50, units='y')
Beispiel #17
0
def draw_astar_graph(obs_map, graph):
    """Debugging function which will show the current state of the m*
    graph
    """
    # Draw the obstacles
    pylab.hold(False)
    sizex = len(obs_map)
    sizey = len(obs_map[0])
    pylab.plot([-.5, sizex - .5, sizex - .5, -.5, -.5],
               [-.5, -.5, sizey - .5, sizey - .5, -.5], 'k')
    pylab.hold(True)
    pylab.matshow((1 - numpy.array(obs_map)).T, fignum=0)
    pylab.gray()
    pylab.clim(-2, 1)
    # Assemble the quiver
    X, Y, U, V = [[] for i in xrange(4)]
    for node in graph.graph.itervalues():
        x, y = node.coord
        u, v = map(lambda w, v: w - v, node.policy, node.coord)
        X.append(x)
        Y.append(y)
        U.append(u)
        V.append(v)
    pylab.quiver(X, Y, U, V)
    pylab.xlim([-.5, sizex - .5])
    pylab.ylim([-.5, sizey - .5])
    pylab.xticks([])
    pylab.yticks([])
    pylab.hold(False)
    pylab.show()
Beispiel #18
0
    def plot_force_vector(self, velocity_vector):
        '''速度ベクトルから合力ベクトルを計算する'''
        ax = plt.subplot(self.row, self.col, self.pos)
        force_vector = self.LeanedPairDampers.compute_force_vector(
            velocity_vector)
        plt.quiver(0,
                   0,
                   force_vector[0],
                   force_vector[1],
                   angles='xy',
                   scale_units='xy',
                   scale=1,
                   width=0.01,
                   color="r",
                   label="Damping Force")
        plt.quiver(0,
                   0,
                   velocity_vector[0],
                   velocity_vector[1],
                   angles='xy',
                   scale_units='xy',
                   scale=1,
                   width=0.01,
                   label="Velocity")

        max_value = max(
            [np.linalg.norm(velocity_vector),
             np.linalg.norm(force_vector)])
        ax.set_xlim([-max_value, max_value])
        ax.set_ylim([-max_value, max_value])
        plt.legend()
Beispiel #19
0
def ode_slopes_2states(func, radii_list, theta_deg_list, time_list):
    """
    Plot field of arrows indicating derivatives of the state
    :param func:
    :param radii_list:
    :param theta_deg_list:
    :param time_list:
    :return:
    """
    # to convert angle unit from degree to radian
    deg2rad = np.pi / 180
    # list of angles in radian
    theta_rad_list = tuple([(theta_deg * deg2rad) for theta_deg in theta_deg_list])
    # radii x angles mesh grid
    radii_mesh, theta_rad_mesh = np.meshgrid(radii_list, theta_rad_list)
    # polar coordinate to cartesian coordinate
    y = radii_mesh * np.cos(theta_rad_mesh), radii_mesh * np.sin(theta_rad_mesh)
    # derivatives of state at each point
    y_dot = func(y, time_list)
    # color
    color_mesh = np.sqrt(y_dot[0] * y_dot[0] + y_dot[1] * y_dot[1])
    # 1
    pylab.figure()
    pylab.quiver(y[0], y[1], y_dot[0], y_dot[1], color_mesh, angles='xy')
    l, r, b, t = pylab.axis()
    x_span, y2_mesh = r - l, t - b
    pylab.axis([l - 0.05 * x_span, r + 0.05 * x_span, b - 0.05 * y2_mesh, t + 0.05 * y2_mesh])
    pylab.axis('equal')
    pylab.grid()
Beispiel #20
0
def plotField(x, F, titleStr, filename):
    import pylab as p
    import griddata as g
    import numpy
    p.ion()
    p.clf()
    xhat = Vector3d(1, 0, 0)
    yhat = Vector3d(0, 1, 0)
    numInternalNodes = len(x.internalValues())
    indices = [i for i in xrange(numInternalNodes) if abs(x[i].z) < 1e-8]
    xs = numpy.array([x[i].dot(xhat) for i in indices])
    ys = numpy.array([x[i].dot(yhat) for i in indices])
    x1 = p.linspace(-0.5, 1.5, 50)
    y1 = p.linspace(-0.5, 1.5, 50)
    xg, yg = p.meshgrid(x1, y1)
    if isinstance(F, VectorField3d) or isinstance(F[0], Vector3d):
        Fxs = numpy.array([F[i].dot(xhat) for i in indices])
        Fys = numpy.array([F[i].dot(yhat) for i in indices])
        Fxg = g.griddata(xs, ys, Fxs, xg, yg)
        Fyg = g.griddata(xs, ys, Fys, xg, yg)
        p.quiver(xg, yg, Fxg, Fyg)
    else:
        #      levels = [0.1*i for i in xrange(32)]
        Fs = numpy.array([F[i] for i in indices])
        Fg = g.griddata(xs, ys, Fs, xg, yg)
        p.contour(xg, yg, Fg, 30)
        p.colorbar()
    p.title(titleStr)
    p.savefig(filename)
Beispiel #21
0
def ode_slopes_2states(func, radii_list, theta_deg_list, time_list):
    """
    Plot field of arrows indicating derivatives of the state
    :param func:
    :param radii_list:
    :param theta_deg_list:
    :param time_list:
    :return:
    """
    # to convert angle unit from degree to radian
    deg2rad = np.pi / 180
    # list of angles in radian
    theta_rad_list = tuple([(theta_deg * deg2rad)
                            for theta_deg in theta_deg_list])
    # radii x angles mesh grid
    radii_mesh, theta_rad_mesh = np.meshgrid(radii_list, theta_rad_list)
    # polar coordinate to cartesian coordinate
    y = radii_mesh * np.cos(theta_rad_mesh), radii_mesh * np.sin(
        theta_rad_mesh)
    # derivatives of state at each point
    y_dot = func(y, time_list)
    # color
    color_mesh = np.sqrt(y_dot[0] * y_dot[0] + y_dot[1] * y_dot[1])
    # 1
    pylab.figure()
    pylab.quiver(y[0], y[1], y_dot[0], y_dot[1], color_mesh, angles='xy')
    l, r, b, t = pylab.axis()
    x_span, y2_mesh = r - l, t - b
    pylab.axis([
        l - 0.05 * x_span, r + 0.05 * x_span, b - 0.05 * y2_mesh,
        t + 0.05 * y2_mesh
    ])
    pylab.axis('equal')
    pylab.grid()
Beispiel #22
0
def draw_MAP_residuals(objectsA, objectsB, P, scaled='no'):
    from pyBA.distortion import compute_displacements, compute_residual
    from numpy import array
    
    # Compute displacements between frames for tie objects
    xobs, yobs, vxobs, vyobs, sxobs, syobs = compute_displacements(objectsA, objectsB)

    # Compute residual
    dx, dy = compute_residual(objectsA, objectsB, P)

    # Draw residuals
    fig = figure(figsize=(16,16))
    ax = fig.add_subplot(111, aspect='equal')
    if scaled is 'yes':
        # Allow relative scaling of arrows
        quiver(xobs,yobs,dx,dy)
    else:
        # Show residuals in absolute size (often very tiny), with uncertainties

        # Also plot error ellipses
        ellipses = array([ Bivarg( mu = array([xobs[i] + dx[i], yobs[i] + dy[i]]),
                                   sigma = objectsA[i].sigma + objectsB[i].sigma )
                           for i in range(len(objectsA)) ])
        draw_objects(ellipses, replot='yes')

        # Residuals
        quiver(xobs,yobs,dx,dy,color='r', angles='xy', scale_units='xy', scale=1)
    ax.autoscale(enable=None, axis='both', tight=True)
    show()
Beispiel #23
0
def showVectorDisplacements():

    global testImage, croppedRefImage, u, v, valid, q1, umean, vmean, x, y, sxyVar, wxyVar, goodvectorsVar
    from scipy import where, compress, logical_and, median, logical_or, nan
    from pylab import resize, transpose, quiver, title, show, find, imshow, hist, figure, clf, draw, save, load, xlabel, ylabel, flipud

    mxy = 3
    wxy = int(wxyVar.get())
    sxy = int(sxyVar.get())
    goodvectors = float(goodvectorsVar.get())
    #process to find PIV-style displacements
    x, y, u, v, q1, valid = simplepiv(croppedRefImage, testImage, wxy, mxy,
                                      sxy)
    good = where(logical_and(q1 > goodvectors, valid > 0), True, False)
    umean = median(compress(good.flat, u.flat))
    vmean = median(compress(good.flat, v.flat))
    u = where(logical_or(q1 < goodvectors, valid < 0), 0, u)
    v = where(logical_or(q1 < goodvectors, valid < 0), 0, v)
    u = u - umean
    v = v - vmean
    save('vecx.out', x)
    save('vecy.out', y)
    save('vecu.out', u)
    save('vecv.out', v)
    save('vecq1.out', q1)
    save('vecvalid.out', valid)
    u = flipud(u)
    v = -flipud(v)
    quiver(x, y, u, v)
    title('Vector displacements')
    xlabel('Pixels')
    ylabel('Pixels')
    show()
    return
Beispiel #24
0
def plot_stiffness_field(k_cart,plottitle=''):
    n_points = 20
    ang_step = math.radians(360)/n_points
    x_list = []
    y_list = []
    u_list = []
    v_list = []
    k_cart = k_cart[0:2,0:2]

    for i in range(n_points):
        ang = i*ang_step
        for r in [0.5,1.,1.5]:
            dx = r*math.cos(ang)
            dy = r*math.sin(ang)
            dtau = -k_cart*np.matrix([dx,dy]).T
            x_list.append(dx)
            y_list.append(dy)
            u_list.append(dtau[0,0])
            v_list.append(dtau[1,0])
    
    pl.figure()
#    mpu.plot_circle(0,0,1.0,0.,math.radians(360))
    mpu.plot_radii(0,0,1.5,0.,math.radians(360),interval=ang_step,color='r')
    pl.quiver(x_list,y_list,u_list,v_list,width=0.002,color='k',scale=None)
    pl.axis('equal')
    pl.title(plottitle)
Beispiel #25
0
def getvectorfield( fitsa, fitsb, graph=False):
    mysex = sexparser.sextractorresult(fitsa)
    mysex.loaddata()
    testsex = sexparser.sextractorresult(fitsb)
    testsex.loaddata()

    flann = pyflann.FLANN()
    dataset = buildvec( mysex.objects["X_IMAGE"], mysex.objects["Y_IMAGE"] )
    testset = buildvec( testsex.objects["X_IMAGE"], testsex.objects["Y_IMAGE"] )

    ids, dists = flann.nn(dataset,testset,1,algorithm="linear")

    
    f=numpy.vectorize( lambda x:  x > 0 and x < 100 )
    cond = numpy.where( f(dists) )

    if graph:
	pylab.hist(dists,bins=100,range=(0,10),histtype="bar")
	pylab.hist(dists[cond],bins=100,range=(0,10))
	pylab.show()
    
    diffvec = dataset[ids[cond]]-testset[cond]

    x,y=numpy.transpose(testset)
    q,u=numpy.transpose(diffvec)

    if graph:
	pylab.quiver(x,y,q,u)
	pylab.xlim(0,2048)
	pylab.ylim(0,2048)
	pylab.show()

    return q.mean(), u.mean(), q.std(), u.std()
Beispiel #26
0
def getAuxMats(Z):
	k = 1
	delX = 1
	delY = 1
	if((len(Z[0])+len(Z))//(2)>=10):
		n=(len(Z[0])+len(Z))//(2*10)
	else:
		n=1
	dx = np.linspace(0,(len(Z[0])-n),len(Z[0])//n)	
	dy = np.linspace(0,(len(Z)-n),len(Z)//n)	
	X,Y = np.meshgrid(dx,dy)
	u = np.zeros((len(X),len(X[0])))
	v = np.zeros((len(X),len(X[0])))
	a,b=0,0
	for x in range(len(X)):
		for y in range(len(X[0])):
			if(a!=0 and a!=len(Z)-1 and b!=0 and b!=len(Z[0])-1):
				v[x][y]= k*(Z[a+1][b]-Z[a-1][b])/(2*delX)
				u[x][y]= -k*(Z[a][b+1]-Z[a][b-1])/(2*delY)		
			else:
				v[x][y]= 0
				u[x][y]= 0
			b+=n
		a+=n
		b=0
	return [X,Y,u,v]
	plt.imshow(z)
	plt.colorbar()
	plt.quiver(X,Y,u,v,width=.01,linewidth=1)	
	plt.show()
def plot_samples(S, axis_list=None):
    pl.scatter(S[:, 0], S[:, 1], s=2, marker='o', linewidths=0, zorder=10)
    if axis_list is not None:
        colors = [(0, 0.6, 0), (0.6, 0, 0)]
        for color, axis in zip(colors, axis_list):
            axis /= axis.std()
            x_axis, y_axis = axis
            # Trick to get legend to work
            pl.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color)
            # pl.quiver(x_axis, y_axis, x_axis, y_axis, zorder=11, width=0.01,
            pl.quiver(0,
                      0,
                      x_axis,
                      y_axis,
                      zorder=11,
                      width=0.01,
                      scale=6,
                      color=color)

    pl.hlines(0, -3, 3)
    pl.vlines(0, -3, 3)
    pl.xlim(-3, 3)
    pl.ylim(-3, 3)
    pl.xlabel('x')
    pl.ylabel('y')
def plot_flow_direction(flow_dataset_uri, output_uri):
    """Generates a quiver plot (arrows on a grid) of a flow matrix

    flow_dataset_uri - a uri to a GDAL compatable raster whose values are
        radians indicating the direction of outward flow.
    output_uri - the location to disk to save the resulting plot png file

    returns nothing"""

    LOGGER.info('Loading %s' % flow_dataset_uri)
    flow_dataset = gdal.Open(flow_dataset_uri, gdal.GA_ReadOnly)
    flow_matrix = (flow_dataset.GetRasterBand(1).ReadAsArray(
        0, 0, flow_dataset.RasterXSize, flow_dataset.RasterYSize))
    LOGGER.info('Done loading %s' % flow_dataset_uri)

    LOGGER.info('Starting plot of flow direction')
    pylab.figure()
    steps = flow_matrix.size
    xmax = flow_matrix.shape[0]
    ymax = flow_matrix.shape[1]
    steps = 10
    pylab.quiver(np.sin(flow_matrix[0:xmax:steps, 0:ymax:steps]),
                 np.cos(flow_matrix[0:xmax:steps, 0:ymax:steps]))
    pylab.axes().set_aspect('equal')
    LOGGER.info('Saving plot as %s' % output_uri)
    pylab.savefig(output_uri, dpi=1600, units='x')
    LOGGER.info('Done with plot of flow direction')
Beispiel #29
0
    def OnCalcShiftmap(self, event):
        from PYME.Analysis import twoColour, twoColourPlot
        import pylab
        masterChan = self.chChannel.GetSelection()
        
        master = self.objFitRes[masterChan]
        x0 = master['fitResults']['x0']
        y0 = master['fitResults']['y0']
        err_x0 = master['fitError']['x0']
        err_y0 = master['fitError']['y0']
        z0 = master['fitResults']['z0']

        wxy = master['fitResults']['wxy']

        wxy_bead = float(self.tBeadWXY.GetValue())

        mask = numpy.abs(wxy - wxy_bead) < (.25*wxy_bead)
        
        self.shiftfields ={}

        pylab.figure() 
        
        nchans = self.image.data.shape[3]
        ch_i = 1
        
        for ch in range(nchans):
            if not ch == masterChan:
                res = self.objFitRes[ch]
                
                x = res['fitResults']['x0']
                y = res['fitResults']['y0']
                z = res['fitResults']['z0']
                err_x = numpy.sqrt(res['fitError']['x0']**2 + err_x0**2)
                err_y = numpy.sqrt(res['fitError']['y0']**2 + err_y0**2)
                
                dx = x - x0
                dy = y - y0
                dz = z - z0
                
                print(('dz:', numpy.median(dz[mask])))
                
                
                spx, spy = twoColour.genShiftVectorFieldLinear(x[mask], y[mask], dx[mask], dy[mask], err_x[mask], err_y[mask])
                self.shiftfields[ch] = (spx, spy, numpy.median(dz[mask]))
                #twoColourPlot.PlotShiftField2(spx, spy, self.image.data.shape[:2])
                
                pylab.subplot(1,nchans -1, ch_i)
                ch_i += 1
                twoColourPlot.PlotShiftResidualsS(x[mask], y[mask], dx[mask], dy[mask], spx, spy)
                
        pylab.figure()
        X, Y = numpy.meshgrid(numpy.linspace(0., 70.*self.image.data.shape[0], 20), numpy.linspace(0., 70.*self.image.data.shape[1], 20))
        X = X.ravel()
        Y = Y.ravel()
        for k in self.shiftfields.keys():
            spx, spy, dz = self.shiftfields[k]
            pylab.quiver(X, Y, spx.ev(X, Y), spy.ev(X, Y), color=['r', 'g', 'b'][k], scale=2e3)
            
        pylab.axis('equal')
Beispiel #30
0
def main():
    x0, x1 = -0.5, 0.5
    y0, y1 = -0.5, 0.5
    h = .125
    nu = 1e3
    dt = 0.01
    t0 = 0.01

    plot_rows, plot_cols = 3, 3
    plot_every = 10

    x, y = init_position.triangular(x0, x1, y0, y1, cell_size=h)

    # initial vorticity and circulation
    vort = problems.lamb_oseen.vorticity(x, y, t0, nu=nu)
    circ = h**2 * vort

    # particle colors
    from itertools import cycle, izip as zip
    colors = ('#FF0000 #00FF00 #0000FF #FFFF00 #FF00FF #00FFFF '
              '#660000 #006600 #000066 #666600 #660066 #006666 '
             ).split()
    colors = [c for (c, _) in zip(cycle(colors), x)]

    t = t0
    iteration = 0
    plot_count = 0
    while True:
        plot_now = (iteration % plot_every == 0)

        if plot_now:
            plot_count += 1
            pylab.subplot(plot_rows, plot_cols, plot_count,
                          autoscale_on=False,
                          xlim=(1.2 * x0, 1.2 * x1),
                          ylim=(1.2 * y0, 1.2 * y1))
            pylab.scatter(x, y, s=2, c=colors, edgecolors='none')
            pylab.grid(True)

        u, v = vm.eval_velocity(x, y, circ)

        #pylab.quiver(x[::10], y[::10], u[::10], v[::10])

        if plot_now:
            pylab.quiver(x, y, u, v, color=colors)
            pylab.title('$t = %.2f$' % t)

        # convect
        x += u * dt
        y += v * dt

        iteration += 1
        t += dt

        if plot_count == plot_rows * plot_cols:
            break

    pylab.suptitle(ur'Lamb Oseen vortex, $\nu = %.3f$' % nu)
    pylab.show()
Beispiel #31
0
def compute_system(m1, m2, separation):
    '''
    Computes the entire system of the two bodies.  Accepts the masses of the two bodies
    and their separation as inputs.  Returns nothing but plots potential contours and acceleration vectors
    on plot.
    '''
    print 'Computing the system for M1=%d M2=%d Separation=%d' % (m1, m2,
                                                                  separation)
    size = 100  # number of points to compute along each axis
    xs = numpy.linspace(-2, 2, size)  #define 1d array from -2,2 with 100 steps
    ys = numpy.linspace(-2, 2, size)
    pot_grid = numpy.zeros(
        (size, size
         ))  #arrays full of zeros to hold potentials and acceleration vectors
    accell_x_grid = numpy.zeros((size, size))
    accell_y_grid = numpy.zeros((size, size))
    x_accell = []  #empty lists to hold x and y acceleration
    y_accell = []
    pos_m1 = (((1.0 / (m1 + m2))) * 25 + 50, 50
              )  #position of masses in grid coordinates (plotted coordinates)
    pos_m2 = ((100 - ((1 - (1.0 / (m1 + m2))) * 25 + 50)), 50)
    if os.path.exists('%d_%d_%d_system.txt' % (m1, m2, separation)):
        os.remove('%d_%d_%d_system.pdf' %
                  (m1, m2, separation))  #remove output txt file if it exists
    fout = open('%d_%d_%d_system.txt' % (m1, m2, separation),
                'a')  #open file for appending
    print 'Printing X,Y,potential,x acceleration,y acceleration to file.'
    for i, y in enumerate(
            ys):  #return index (i) and value (y) if the list ys and iterate.
        for j, x in enumerate(xs):
            potential = grav(x, y, m1, m2)
            pot_grid[i][j] = potential
            acc_vect = accel(x, y, m1, m2)
            accell_x_grid[i][j] = acc_vect[0]
            accell_y_grid[i][j] = acc_vect[1]
            x_accell.append(
                acc_vect[0]
            )  #append acceleration components to [x,y]_accell list
            y_accell.append(acc_vect[1])
            #print x,y,potential,acc_vect[0],acc_vect[1]
            fout.write('%1.3f %1.3f %1.3f %1.3f %1.3f\n' %
                       (y, x, potential, acc_vect[0], acc_vect[1]))
    find_l(accell_x_grid, accell_y_grid, pos_m1, pos_m2, size, separation)
    x_accell = numpy.array(x_accell)  #convert list to array for indexing
    y_accell = numpy.array(y_accell)
    index = numpy.where((numpy.fabs(x_accell) > 3) |
                        (numpy.fabs(y_accell) >
                         3))  #suppress large accelerations for clearer plot
    x_accell[index] = 0
    y_accell[index] = 0
    pylab.contour(pot_grid, size *
                  4)  #plot contours of pot_grid with size*4 number of contours
    X, Y = numpy.meshgrid(range(len(pot_grid)), range(len(pot_grid)))
    pylab.quiver(
        X, Y, x_accell, y_accell, units='xy',
        scale=1)  #plot vectors at points X,Y with components x_accell,y_accell
    #pylab.show()
    pylab.savefig('%d_%d_%d_system.pdf' % (m1, m2, separation))  #save figure
    pylab.close()  #close plot
Beispiel #32
0
    def OnCalcShiftmap(self, event):
        from PYME.Analysis.points import twoColour, twoColourPlot
        import pylab
        masterChan = self.chChannel.GetSelection()
        
        master = self.objFitRes[masterChan]
        x0 = master['fitResults']['x0']
        y0 = master['fitResults']['y0']
        err_x0 = master['fitError']['x0']
        err_y0 = master['fitError']['y0']
        z0 = master['fitResults']['z0']

        wxy = master['fitResults']['wxy']

        wxy_bead = float(self.tBeadWXY.GetValue())

        mask = numpy.abs(wxy - wxy_bead) < (.25*wxy_bead)
        
        self.shiftfields ={}

        pylab.figure() 
        
        nchans = self.image.data.shape[3]
        ch_i = 1
        
        for ch in range(nchans):
            if not ch == masterChan:
                res = self.objFitRes[ch]
                
                x = res['fitResults']['x0']
                y = res['fitResults']['y0']
                z = res['fitResults']['z0']
                err_x = numpy.sqrt(res['fitError']['x0']**2 + err_x0**2)
                err_y = numpy.sqrt(res['fitError']['y0']**2 + err_y0**2)
                
                dx = x - x0
                dy = y - y0
                dz = z - z0
                
                print(('dz:', numpy.median(dz[mask])))
                
                
                spx, spy = twoColour.genShiftVectorFieldLinear(x[mask], y[mask], dx[mask], dy[mask], err_x[mask], err_y[mask])
                self.shiftfields[ch] = (spx, spy, numpy.median(dz[mask]))
                #twoColourPlot.PlotShiftField2(spx, spy, self.image.data.shape[:2])
                
                pylab.subplot(1,nchans -1, ch_i)
                ch_i += 1
                twoColourPlot.PlotShiftResidualsS(x[mask], y[mask], dx[mask], dy[mask], spx, spy)
                
        pylab.figure()
        X, Y = numpy.meshgrid(numpy.linspace(0., 70.*self.image.data.shape[0], 20), numpy.linspace(0., 70.*self.image.data.shape[1], 20))
        X = X.ravel()
        Y = Y.ravel()
        for k in self.shiftfields.keys():
            spx, spy, dz = self.shiftfields[k]
            pylab.quiver(X, Y, spx.ev(X, Y), spy.ev(X, Y), color=['r', 'g', 'b'][k], scale=2e3)
            
        pylab.axis('equal')
Beispiel #33
0
	def quiver(self):
		mins = self.aus.min(axis=0)
		maxs = self.aus.max(axis=0)
		X,Y = np.meshgrid(linspace(mins[0], maxs[0], self.quiver_res), 
								linspace(mins[1], maxs[1], self.quiver_res))
		Z = np.dstack([X,Y])
		vals = self.f(0,Z.transpose(2,0,1))
		PL.quiver(X,Y,vals[0], vals[1])
def ContourPlot2D(u, v, p, Y, X):
    pl.figure(figsize = (11,7), dpi = 100)
    pl.contourf(X,Y,p,alpha=0.5,cmap=cm.gist_heat)# plotting the pressure field contours
    pl.colorbar()
    pl.quiver(X[::2,::2],Y[::2,::2],u[::2,::2],v[::2,::2]) # plotting velocity vectors
    pl.xlabel('X')
    pl.ylabel('Y')
    pl.title('Pressure contours and velocity vectors')
Beispiel #35
0
def main():
    nu = 5e-4     # ν
    gamma0 = 1.0  # Γ₀
    vortex = LambOseenVortex(total_circulation=gamma0, viscosity=nu)

    # particle initialization
    x0, x1 = -0.5, 0.5
    y0, y1 = -0.5, 0.5
    h = .125 / 4
    e = 2 * h     # ε
    x, y = init_position.triangular(x0, x1, y0, y1, cell_size=h)

    # integration parameters
    t0 = 4
    dt = 0.001      # δt
    nr_iterations = 100

    # initial circulation evaluation
    initial_vorticity = vortex(x, y, t0)
    circ = h**2 * initial_vorticity

    iteration = 0
    t = t0
    while True:

        # convection
        u, v = eval_velocity(x, y, circ, e ** 2)
        x += u * dt
        y += v * dt

        # diffusion
        dcirc = eval_circulation_change(x, y, circ, nu, e ** 2)
        circ += dcirc * dt

        if iteration % 10 == 0:
            err2 = squared_velocity_errors(x, y, u, v, t, vortex)
            print "Iteration {0}, t = {1}".format(iteration, t)
            print "Squared error: {0} ± {1}".format(err2.mean(), err2.std())
            print

            #pylab.subplot(2, 5, (iteration + 1) // 10)
            #u_a, v_a = vortex.velocity(x, y, t)
            #pylab.scatter(x, y, s=1, c='red', edgecolor='none')
            #pylab.quiver(x, y, u, v, color='red')
            #pylab.quiver(x, y, u_a, v_a, color='blue')

        if not (iteration < nr_iterations):
            break

        iteration += 1
        t += dt

    u_a, v_a = vortex.velocity(x, y, t)
    pylab.scatter(x, y, s=1, c='red', edgecolor='none')
    pylab.quiver(x, y, u, v, color='red')
    pylab.quiver(x, y, u_a, v_a, color='blue')

    pylab.show()
Beispiel #36
0
def vis2d(pts,
          bds,
          draw_points=False,
          draw_edges=True,
          eigenfunction=None,
          eigenfunctions=None,
          ecolors=None,
          figname=None,
          noshow=False,
          figidx=None):
    fig = pylab.figure(figsize=(8, 8))
    ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])
    fig.figurePatch.set_edgecolor('white')
    fig.figurePatch.set_facecolor('white')
    ax.set_aspect('equal')
    ax.set_axis_off()

    if (draw_edges):
        cutoff = 10.
        xpairs = [[pts[bd[0]][0], pts[bd[1]][0]] for bd in bds
                  if np.linalg.norm(pts[bd[0]] - pts[bd[1]]) < cutoff]
        ypairs = [[pts[bd[0]][1], pts[bd[1]][1]] for bd in bds
                  if np.linalg.norm(pts[bd[0]] - pts[bd[1]]) < cutoff]
        xlist = []
        ylist = []
        for xends, yends in zip(xpairs, ypairs):
            xlist.extend(xends)
            xlist.append(None)
            ylist.extend(yends)
            ylist.append(None)
        plotpts, = pylab.plot(xlist, ylist, '-', color=(.5, .5, .5))

    if (draw_points):
        pylab.scatter(pts[:, 0], pts[:, 1])

    if (eigenfunction is not None):
        pylab.quiver(pts[:, 0],
                     pts[:, 1],
                     eigenfunction[::2],
                     eigenfunction[1::2],
                     color='r')

    if (eigenfunctions is not None):
        for i, eig in enumerate(eigenfunctions):
            pylab.quiver(pts[:, 0],
                         pts[:, 1],
                         eig[::2],
                         eig[1::2],
                         color=ecolors[i])

    if figname is None and not noshow:
        pylab.show()

    if figname is not None:
        pylab.savefig(figname)
        pylab.close()

    return plotpts
Beispiel #37
0
def plot_vfield(x, y, u, I=1):
    pl.figure()
    pl.gca().set_aspect('equal')
    M = pl.sqrt(u['X'][::I, ::I]**2 + u['Y'][::I, ::I]**2)
    pl.quiver(x[::I], y[::I], u['X'][::I, ::I], u['Y'][::I, ::I], M)
    pl.xlabel(r'$x$')
    pl.ylabel(r'$y$')
    pl.colorbar()
    pl.show()
Beispiel #38
0
def draw_box_2d(obbs, **args):
        from pylab import plot, quiver
        if isinstance(obbs, Box2D):
            obbs = [obbs]
        for obb in obbs:
            box = vstack([obb.box, obb.box[0]])
            plot(box.T[0], box.T[1], lw=5, hold=True, **args)
            quiver([obb.center[0]], [obb.center[1]], [obb.orientation[
                   0]], [obb.orientation[1]], pivot='middle', hold=True, **args)
	def PlotVel(self, **Scatter_args):
		"""Plot the current configuration."""
		
		X, U = self.X, self.U
		
		m.quiver(X[:,0], X[:,1], U[:,0], U[:,1], **Scatter_args)
	
		m.xlim(0, 1)
		m.ylim(0, 1)
    def PlotVel(self, **Scatter_args):
        """Plot the current configuration."""

        X, U = self.X, self.U

        m.quiver(X[:, 0], X[:, 1], U[:, 0], U[:, 1], **Scatter_args)

        m.xlim(0, 1)
        m.ylim(0, 1)
Beispiel #41
0
        def doSubplot(multiplier=1.0, layout=(-1, -1)):
            if time_sec < 16200:
                xs, ys = xs_1, ys_1
                domain_bounds = bounds_1sthalf
                grid = grid_1
            else:
                xs, ys = xs_2, ys_2
                domain_bounds = bounds_2ndhalf
                grid = grid_2

            try:
                mo = ARPSModelObsFile("%s/%s/KCYS%03dan%06d" %
                                      (base_path, exp, min_ens, time_sec))
            except AssertionError:
                mo = ARPSModelObsFile("%s/%s/KCYS%03dan%06d" %
                                      (base_path, exp, min_ens, time_sec),
                                      mpi_config=(2, 12))
            except:
                print "Can't load reflectivity ..."
                mo = {'Z': np.zeros((1, 255, 255), dtype=np.float32)}

            pylab.contour(xs,
                          ys,
                          wind[exp]['w'][wdt][domain_bounds],
                          levels=np.arange(2, 102, 2),
                          styles='-',
                          colors='k')
            pylab.contour(xs,
                          ys,
                          wind[exp]['w'][wdt][domain_bounds],
                          levels=np.arange(-100, 0, 2),
                          styles='--',
                          colors='k')

            pylab.quiver(xs[thin], ys[thin],
                         wind[exp]['u'][wdt][domain_bounds][thin],
                         wind[exp]['v'][wdt][domain_bounds][thin])

            pylab.contourf(xs,
                           ys,
                           mo['Z'][0][domain_bounds],
                           levels=np.arange(10, 85, 5),
                           cmap=NWSRef,
                           zorder=-10)

            grid.drawPolitical(scale_len=10)

            row, col = layout
            if col == 1:
                pylab.text(-0.075,
                           0.5,
                           exp_names[exp],
                           transform=pylab.gca().transAxes,
                           rotation=90,
                           ha='center',
                           va='center',
                           size=12 * multiplier)
Beispiel #42
0
def plot_residuals_year_2pos(year, filt, pos1, pos2, refresh=False):
    year = str(year) 
    
    dir_xym = year + '_' + filt + '/01.XYM/'

    # Try to read from a FITS table of compiled data if possible.
    if refresh == True:
        make_residuals_table_year_2pos(year, filt, pos1, pos2)

    d = read_residuals_table_year_2pos(year, filt, pos1, pos2)

    print d.xstd_p.min(), d.xstd_p.max()

    # Remember, this was all aligned to F814W in ACS. So there is a
    # relative scale change between the transformed and the raw pixels.
    # We need to put evertyhing back on the same scale.
    # The plate scale was 0.411095 (pulled from TRANS.xym2mat.ref4)
    scale = 0.411095

    dx1 = d.xmean_p[0, :] - d.stars['x']
    dx2 = d.xmean_p[1, :] - d.stars['x']
    dy1 = d.ymean_p[0, :] - d.stars['y']
    dy2 = d.ymean_p[1, :] - d.stars['y']
    lim = 0.06
    idx = np.where((np.abs(dx1) < lim) & (np.abs(dy1) < lim) & 
                   (np.abs(dx2) < lim) & (np.abs(dy2) < lim))[0]

    # Plot the offsets for each position on a common coordinate system.
    py.clf()
    q1 = py.quiver(d.xmean[idx], d.ymean[idx], dx1[idx], dy1[idx], 
                   color='red', scale=1.8)
    q1 = py.quiver(d.xmean[idx], d.ymean[idx], dx2[idx], dy2[idx], 
                   color='blue', scale=1.8)
    py.quiverkey(q1, -0.1, -0.12, 0.02/scale, '0.02 WFC3IR pixels')
    py.axis('equal')
    py.xlabel("X (pixels)")
    py.ylabel("Y (pixels)")
    py.title(year + ',' + filt + ',' + pos1 + ',' + pos2)
    py.savefig('plots/resid_final_{0}_{1}_{2}_{3}.png'.format(year, filt, pos1, pos2))

    # Plot the offsets for each position on the raw coordinate system.
    py.clf()
    xraw1 = d.xraw[0,:,:].mean(axis=0)
    yraw1 = d.yraw[0,:,:].mean(axis=0)
    xraw2 = d.xraw[1,:,:].mean(axis=0)
    yraw2 = d.yraw[1,:,:].mean(axis=0)
    
    q1 = py.quiver(xraw1[idx], yraw1[idx], dx1[idx], dy1[idx], 
                   color='red', scale=1.8)
    q1 = py.quiver(xraw2[idx], yraw2[idx], dx2[idx], dy2[idx], 
                   color='blue', scale=1.8)
    py.quiverkey(q1, -0.1, -0.12, 0.02/scale, '0.02 WFC3IR pixels')
    py.axis('equal')
    py.xlabel("X (pixels)")
    py.ylabel("Y (pixels)")
    py.title(year + ',' + filt + ',' + pos1 + ',' + pos2)
    py.savefig('plots/resid_raw_{0}_{1}_{2}_{3}.png'.format(year, filt, pos1, pos2))
def main():
    import pylab

    N = 2**4
    h = 1/N
    x, y = mgrid[0.0:1.0:h, 0.0:1.0:h]

    pylab.quiver(x, y, *velocity(x, y))
    pylab.show()
def plot_electric_field(E_theta, E_phi):
	#Variables for plotting purposes
	x = np.arange(0, 360)
	y = np.arange(60, 90)
	X , Y = np.meshgrid(x, y)

	#Quiver plot of the electric field E = -grad(Phi), to show the direction in weak areas, all the arrows should have the same length and the magnitude should be given by the color below
	#Getting the magnitude and normalizing
	magnitude = np.sqrt((E_theta*E_theta) + (E_phi*E_phi))
	E_phi_norm = np.zeros(E_phi.shape)
	E_phi_norm[1:-1,1:-1] = E_phi[1:-1,1:-1]/magnitude[1:-1,1:-1]
	E_theta_norm = np.zeros(E_theta.shape)
	E_theta_norm[1:-1,1:-1] = E_theta[1:-1,1:-1]/magnitude[1:-1,1:-1]

	plt.figure()
	x = np.arange(0,potential.shape[1])
	y = 60 + np.arange(0,potential.shape[0])
	X, Y = np.meshgrid(x,y)

	skipArrows = 10
	eArrows = plt.contourf(X,Y, magnitude)
	plt.quiver(X[:,::skipArrows],Y[:,::skipArrows], E_phi_norm[:,::skipArrows], E_theta_norm[:,::skipArrows], angles = 'uv', scale = 40)

	cbar = plt.colorbar(eArrows)

	#Labels
	plt.title('Electric field in the higher latitudes')
	cbar.set_label('$|\\vec{E}|$')
	plt.xlabel('Longitude [ $ ^\circ$]')
	plt.ylabel('Latitude  [ $ ^\circ$]')

	plt.savefig('eArrows.eps')

	#Let's plot the electric field on the map as well
	fig = plt.figure()
	my_map = draw_map()

	longitude, latitude = my_map(X, Y)

	my_map.contourf(longitude, latitude, magnitude)
	my_map.quiver(longitude[:,::skipArrows],latitude[:,::skipArrows], E_phi_norm[:,::skipArrows], E_theta_norm[:,::skipArrows], angles = 'uv', scale = 40)
	plt.savefig('map_efield')

	#Plotting it on as a stereographic projection


	fig = plt.figure()
	X2 = (90 - Y)*np.sin(np.deg2rad(X))
	Y2 = (90 - Y)*np.cos(np.deg2rad(X))
	quiver = pl.quiver(X2[2:-2,::skipArrows],Y2[2:-2,::skipArrows],E_phi[2:-2,::skipArrows], E_theta[2:-2,::skipArrows])
	quiver.set_label(' $\Phi$  [V]')#, rotation = 0)
	pl.title('Electric Field')

	plt.savefig('other_proj.eps')

	return 
Beispiel #45
0
def runanalysis():
    filename = ourgui.openFile(type="npz")

    data = np.load(filename, mmap_mode="r")
    Y = data["Y"]
    Z = data["Z"]
    BY = data["BY"]
    BZ = data["BZ"]
    coilpos = getdata(data, "coilpos")
    coilwidth = getdata(data, "coilwidth")
    nturns = getdata(data, "nturns")
    coilsize = getdata(data, "coilsize")

    infopiece = []
    if coilpos:
        infopiece += ['Cpos: %g"' % coilpos]
    if coilwidth:
        infopiece += ['Cwidth: %g"' % coilwidth]
    if coilsize:
        infopiece += ['Csize: %g"' % coilsize]
    if nturns:
        infopiece += ["Turns: %d" % nturns]
    infotitle = ", ".join(infopiece)

    fig = pl.figure(figsize=(11.69, 8.27), dpi=100)
    fig.text(0.4, 0.95, infotitle)

    pl.subplot(2, 2, 1)
    pl.quiver(Z, Y, BZ, BY)
    pl.xlabel("Z")
    pl.ylabel("Y")
    pl.title("Magnetic field direction")

    pl.subplot(2, 2, 2)
    CS = pl.contour(Z, Y, BY / BZ)
    pl.xlabel("Z")
    pl.ylabel("Y")
    pl.title("Y-strength/Z-strength")
    pl.clabel(CS, inline=1, fontsize=10)

    pl.subplot(2, 2, 3)
    zpos = Z[:, 0]
    zfield = BZ[:, 0] / BZ[0, 0]
    pl.plot(zpos, zfield)
    pl.xlabel("Z position")
    pl.ylabel("On axis field strength")

    pl.subplot(2, 2, 4)
    fieldstrength = np.sqrt(BY ** 2 + BZ ** 2)
    CS = pl.contour(Z, Y, fieldstrength)
    pl.xlabel("Z")
    pl.ylabel("Y")
    pl.title("Field strength", fontsize=10)
    pl.clabel(CS, inline=1, fontsize=10)

    pl.show()
Beispiel #46
0
def slice_velocity(fname_list, slice_axis):
	# Open HDF5 file
	try:
		h5f = openFile(fname_list[0])
	except:
		raise
	# Get dimensions
	rows = [i for i in h5f.root.ZONE]
	shape = [i for i in rows[0]['NAXES']]
	naxes = [i for i in rows[0]['NAXES']]

	axis_titles = ["X", "Y", "Z"]
	slice_axis_title = axis_titles.pop(slice_axis)

	axis_indices = [0, 1, 2]
	axis_indices.pop(slice_axis)

	# Load data
	table = getattr(h5f.root, "GRID")
	data = [i['V_cen'] for i in table]
	iter_max = shape.pop(slice_axis) # --> xy, xz or yz
	grid_i = ndarray(shape)
	grid_j = ndarray(shape)
	intensity = ndarray(shape)
	pos_x = ndarray(shape)
	pos_y = ndarray(shape)

	if opts.index is not None:
		indices = [opts.index]
	else:
		indices = range(iter_max)

	for slice_index in indices:
		for i, val in ndenumerate(grid_i):
			index = [j for j in i]
			index.insert(slice_axis, slice_index)
			row_id = index[2] + naxes[2] * (index[1] + naxes[1] * index[0])
			grid_i[i] = data[row_id][axis_indices[0]]
			grid_j[i] = data[row_id][axis_indices[1]]
			intensity[i] = sqrt(grid_i[i]**2 + grid_j[i]**2)
			pos_x[i] = i[0] + 0.5
			pos_y[i] = i[1] + 0.5

		from pylab import quiver, colorbar, axis, title, xlabel, ylabel, pcolor
		pcolor(intensity.transpose())
		colorbar()
		#quiver(pos_x.transpose(), pos_y.transpose(), grid_i.transpose(), grid_j.transpose(), scale=10000.0)
		quiver(pos_x.transpose(), pos_y.transpose(), grid_i.transpose(), grid_j.transpose(), scale=None)
		axis([0, shape[0], 0, shape[1]])
		title("Velocity, %s index=%d" % (slice_axis_title, slice_index))
		xlabel(axis_titles[0])
		ylabel(axis_titles[1])

		PylabShow()
	# Close HDF5 file
	h5f.close()
Beispiel #47
0
def plot_ring(self):
    import pylab
    pylab.quiver(self.data['x'], self.data['y'], self.input['u'],
            self.input['v'], color='r')
    pylab.quiver(self.data['xr'], self.data['yr'], self.data['ur'], self.data['vr'])
    pylab.plot(self.data['xc'], self.data['yc'], 'ro')
    pylab.figure()
    pylab.plot(self.data['r'], self.data['vtan'], 'r')
    pylab.plot(self.data['r'], self.data['vrad'], 'g')
    pylab.show()
Beispiel #48
0
def plot_vfield(x, y, z, u, Z=1, I=1):
    pl.figure()
    pl.gca().set_aspect('equal')
    M = pl.sqrt(u['X'][Z, ::I, ::I]**2 + u['Y'][Z, ::I, ::I]**2)
    #pl.quiver(y[::I], y[::I], u['X'][Z, ::I, ::I], u['Y'][Z, ::I, ::I], M)
    pl.quiver(u['X'][Z, ::I, ::I], u['Y'][Z, ::I, ::I], M)
    pl.xlabel('y')
    pl.ylabel('X')
    pl.colorbar()
    pl.show()
Beispiel #49
0
 def plot_vector(self):
     self.plot_basic()
     X, Y, U, V = zip(
         numpy.array([
             0, 0,
             float(self.get_x_cartesian()),
             float(self.get_y_cartesian())
         ]))
     pylab.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)
     pylab.show()
def ContourPlot2D(u, v, p, Y, X):
    pl.figure(figsize=(11, 7), dpi=100)
    pl.contourf(X, Y, p, alpha=0.5,
                cmap=cm.gist_heat)  # plotting the pressure field contours
    pl.colorbar()
    pl.quiver(X[::2, ::2], Y[::2, ::2], u[::2, ::2],
              v[::2, ::2])  # plotting velocity vectors
    pl.xlabel('X')
    pl.ylabel('Y')
    pl.title('Pressure contours and velocity vectors')
def plot_grid_reconstruction_grid(mydae,
                                  outputfile,
                                  plotgrid_N_buckets=30,
                                  window_width=0.3,
                                  center=(0.0, 0.0)):

    (plotgrid_X, plotgrid_Y) = np.meshgrid(
        np.arange(center[0] - window_width, center[0] + window_width,
                  2 * window_width / plotgrid_N_buckets),
        np.arange(center[1] - window_width, center[1] + window_width,
                  2 * window_width / plotgrid_N_buckets))
    plotgrid = np.vstack([np.hstack(plotgrid_X), np.hstack(plotgrid_Y)]).T

    # Not sure it's worth truncating some elements now that we're
    # producing more plots.
    #    D = np.sqrt(plotgrid[:,0]**2 + plotgrid[:,1]**2)
    #    plotgrid = plotgrid[D<0.7]
    #    print plotgrid_X.shape
    #    print plotgrid_Y.shape
    #    print "Will keep only %d points on the plotting grid after starting from %d." % (plotgrid.shape[0], plotgrid_X.shape[0])

    print "Making predictions for the grid."

    grid_pred = mydae.encode_decode(plotgrid)
    grid_error = np.sqrt(((grid_pred - plotgrid)**2).sum(axis=1)).mean()
    print "grid_error = %0.6f (not necessarily a relevant information)" % grid_error

    print "Generating plot."

    # print only one point in 100
    # pylab.scatter(data[0:-1:100,0], data[0:-1:100,1], c='#f9a21d')
    #pylab.scatter(clean_data[:,0], clean_data[:,1], c='#f9a21d')
    import matplotlib.pyplot as plt
    plt.hexbin(clean_data[:, 0],
               clean_data[:, 1],
               bins='log',
               cmap=plt.cm.YlOrRd_r)
    # doesn't work for hist2d
    #from matplotlib import pyplot
    #pyplot.hist2d(clean_data[:,0], clean_data[:,1],nbins=100)

    pylab.hold(True)
    arrows_scaling = 1.0
    pylab.quiver(plotgrid[:, 0], plotgrid[:, 1],
                 arrows_scaling * (grid_pred[:, 0] - plotgrid[:, 0]),
                 arrows_scaling * (grid_pred[:, 1] - plotgrid[:, 1]))
    pylab.draw()
    pylab.axis([
        center[0] - window_width * 1.0, center[0] + window_width * 1.0,
        center[1] - window_width * 1.0, center[1] + window_width * 1.0
    ])
    pylab.savefig(outputfile, dpi=300)
    pylab.close()

    return grid_error
Beispiel #52
0
def make_quiver_overlay(background, arr_x, arr_y, title='', skip=8):
    nx, ny = arr_x.shape
    if nx != ny:
        raise ValueError("nx != ny")
    slicer = slice(0, nx, skip)
    X,Y = np.ogrid[slicer, slicer]
    # pl.imshow(background, origin='lower', cmap=pl.cm.hot)
    pl.imshow(background)
    pl.colorbar()
    pl.quiver(X, Y, arr_x[slicer, slicer], arr_y[slicer, slicer])
    pl.title(title)
Beispiel #53
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    iresfile = argv[1]
    try:
        ct = float(argv[2])
    except:
        ct = 0.0
    ires = adore.res2dict(iresfile)
    A = ires['fine_coreg']['results']
    A = A[A[:, 5] > ct, :]
    az = int(ires['fine_coreg']['Initial offsets'].split(',')[0])
    rg = int(ires['fine_coreg']['Initial offsets'].split(',')[1])
    #figure1
    pylab.figure()
    pylab.title('Fine Correlation Results')
    Q = pylab.quiver(A[:, 2], A[:, 1], A[:, 4], A[:, 3], A[:, 5])
    azAvg = round(pylab.np.mean(A[:, 3]))
    rgAvg = round(pylab.np.mean(A[:, 4]))
    qk = pylab.quiverkey(Q,
                         0.33,
                         0.92,
                         azAvg, ('%d [px az]' % (azAvg)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    qk = pylab.quiverkey(Q,
                         0.66,
                         0.92,
                         rgAvg, ('%d [px rg]' % (rgAvg)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    pylab.colorbar()

    #figure2
    pylab.figure()
    pylab.title('Fine Correlation Deviations')
    pylab.quiver(A[:, 2], A[:, 1], A[:, 4] - rg, A[:, 3] - az, A[:, 5])
    Q = pylab.quiver(A[:, 2], A[:, 1], A[:, 4] - rg, A[:, 3] - az, A[:, 5])
    azStd = round(pylab.np.std(A[:, 3] - az))
    rgStd = round(pylab.np.std(A[:, 4] - rg))
    qk = pylab.quiverkey(Q,
                         0.33,
                         0.92,
                         azStd, ('%d [px az]' % (azStd)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    qk = pylab.quiverkey(Q,
                         0.66,
                         0.92,
                         rgStd, ('%d [px rg]' % (rgStd)),
                         labelpos='W',
                         fontproperties={'weight': 'bold'})
    pylab.colorbar()
    pylab.show()
Beispiel #54
0
def plot_gradient_trajectory_g_params(X, plot_filename):

    import matplotlib
    # This has already been specified in .scitools.cfg
    # so we don't need to explicitly pick 'Agg'.
    # matplotlib.use('Agg')
    import pylab
    import matplotlib.pyplot as plt

    N_a, N_b = 10, 10

    A, B = np.meshgrid(np.linspace(0.5, 2.0, N_a),
                       np.linspace(0.5, 2.0, N_b))

    Z = np.zeros(B.shape)
    # values Z[n_b, n_a] will be set
    # through two for loops
    grad_ZA = np.zeros(A.shape)
    grad_ZB = np.zeros(B.shape)

    for n_a in range(N_a):
        a = A[0, n_a]
        g_params[0].set_value(a)

        for n_b in range(N_b):
            b = B[n_b, 0]
            g_params[1].set_value(b)

            H = sample_H_given_X(X)

            # could be optimized better, but we're just losing a
            # factor of two in the worst case
            omega, qX = compute_omega_qX(X, H)
            #print "mean log q(X) is %f" % np.log(qX).mean()
            Z[n_b, n_a] = np.log(qX).mean()

            _, _, J_log_ga, J_log_gb, _, _, J_log_fa, J_log_fb = func_compute_all(X, H)
            subs_J_log_g = (omega.dot(J_log_ga).mean(axis=0), omega.dot(J_log_gb).mean(axis=0))
            #subs_J_log_f = (omega.dot(J_log_fa).mean(axis=0), omega.dot(J_log_fb).mean(axis=0))

            grad_ZA[n_a, n_b] = subs_J_log_g[0]
            grad_ZB[n_a, n_b] = subs_J_log_g[1]

        print "Done with a=%f." % a


    dpi=150
    pylab.hold(True)
    plt.contourf(A, B, Z)
    pylab.quiver(A, B, grad_ZA, grad_ZB)
    pylab.draw()
    pylab.savefig(plot_filename, dpi=dpi)
    pylab.close()
    print "Wrote %s." % (plot_filename,)
Beispiel #55
0
 def plot(self, *args, **kwargs):
   from pylab import quiver
   a = self.asarray()
   if not 'pivot' in kwargs:
     kwargs['pivot'] = 'middle' 
   if not 'scale' in kwargs:
     kwargs['scale'] = 10
   if a.any():
     norm = hypot( a[:,2], a[:,3] )
     a[:,2] /= norm
     a[:,3] /= norm
     quiver( a[:,0], a[:,1], a[:,2], -a[:,3], **kwargs )
def compute_phase_diagram(hunting_rate_x, hunting_rate_y, duration, start_x, start_y):
    '''
    Compute multiple simulations with parameters taken from the arguments.
    Create graph that shows the simulation results one after the other.

    ARGUMENTS
    ---------
    hunting_rate_x:  hunting rate for species 1 (small fish)
    hunting_rate_y:  hunting rate for species 2 (predatory fish)
    duration:        list of duration for each simulation
    start_x:         list of start values for species 1
    start_y          list of start values for species 2
    '''
    model = EnhancedModel() #create a simulation object instance
    figure() #create new figure window

    #max_i = len(duration)-1
    xmax, ymax = -1e100, -1e100
    xmin, ymin = 1e100, 1e100
    #do simulations with the different parameter values,
    #plot results into phase plane
    for i in range(len(duration)):
        model.init_hunting(hunting_rate_x, hunting_rate_y,
                           start_x[i], start_y[i], duration[i])
        model.simulateDynamic()   #solve ODE
        res = model.getResults()  #get results as a storage.DictStore object
        #color_tuple = cm.jet(i/max_i)
        plot(res['x'], res['y'], color='black', linestyle='-')

        #find maximum figure dimensions for quiver plot
        xmax = max(xmax, amax(res['x']))
        ymax = max(ymax, amax(res['y']))
        xmin = min(xmin, amin(res['x']))
        ymin = min(ymin, amin(res['y']))

    #Sample differentials at different points in phase plane,
    #plot field of arrows
    X, Y = mgrid[xmin:xmax:20j,ymin:ymax:20j]
    U, V = zeros(X.shape), zeros(X.shape)
    for i in range(X.shape[0]):
        for j in range(X.shape[1]):
            s_dt = model.dynamic(0, [X[i,j], Y[i,j]])
            U[i,j],V[i,j] = s_dt[0], s_dt[1]
    #The axes don't have the same scale, therefore scale the arrows
    #TODO: this is a bad hack; future keyword 'angles' should do the trick
    scale_xy = (ymin-ymax)/(xmin-xmax) * 1.3
    quiver(X, Y, scale_xy*U, V, pivot='center', units='inches', color='red',zorder=0)

    #finishing touches on plot
    xlabel('x - prey')
    ylabel('y - predators')
    legend()
    title('Predator prey with hunting - hx = %g, hy = %g' % (hunting_rate_x, hunting_rate_y))