コード例 #1
0
ファイル: efields.py プロジェクト: woznia62/E_fields
def octupole(a):
    """Function: octupole(a)"""
    plt.figure(figsize=(20, 14))
    xlim = (a+5); ylim = (a+5)
    plt.axes = plt.gca()
    plt.axes.set_xlim([-xlim,xlim])
    plt.axes.set_ylim([-ylim,ylim])
    x = np.linspace(-xlim, xlim, 100)
    y = np.linspace(-ylim, ylim, 100)
    x, y = np.meshgrid(x, y)
    # RR
    E1 = mkcharge(a+2*a, a, -1, x, y)
    E2 = mkcharge(a+2*a, -a, 1, x, y)
    # R
    E5 = mkcharge(a, a, 1, x, y)
    E6 = mkcharge(a, -a, -1, x, y)
    # L
    E7 = mkcharge(-a, a, -1, x, y)
    E8 = mkcharge(-a, -a, 1, x, y)
    # LL
    E3 = mkcharge(-(a+2*a), a, 1, x, y)
    E4 = mkcharge(-(a+2*a), -a, -1, x, y)
    Ex = E1[0] + E2[0] + E3[0] + E4[0] + E5[0] + E6[0] + E7[0] + E8[0]
    Ey = E1[1] + E2[1] + E3[1] + E4[1] + E5[1] + E6[1] + E7[1] + E8[1]
    #color = log(sqrt(abs(Ex) + abs(Ey)+2))
    color = np.log(np.sqrt(Ex**2 + Ey**2))
    plt.streamplot(x, y, Ex/np.sqrt(Ex**2+Ey**2), Ey/np.sqrt(Ex**2+Ey**2), color=color, linewidth=1, cmap=plt.cm.inferno, density=3.5, arrowstyle='->', arrowsize=1.5)
    plt.xlabel('$x$')
    plt.ylabel('$y$')
    plt.savefig('electric_octupole.pdf', transparent=True, bbox_inches='tight', pad_inches=0)
コード例 #2
0
ファイル: efields.py プロジェクト: woznia62/E_fields
def quadrupole(a):
    """Function: quadrupole(a)
    Plot the electric field lines of two antiparallel dipoles were the horizontal and vertical
    distance between charges is 2*a."""
    plt.figure(figsize=(20, 14))
    xlim = (a+5); ylim = (a+5)
    plt.axes = plt.gca()
    plt.axes.set_xlim([-xlim,xlim])
    plt.axes.set_ylim([-ylim,ylim])
    x = np.linspace(-xlim, xlim, 100)
    y = np.linspace(-ylim, ylim, 100)
    x, y = np.meshgrid(x, y)
    E1 = mkcharge(a, a, 1, x, y)
    E2 = mkcharge(a, -a, -1, x, y)
    E3 = mkcharge(-a, a, -1, x, y)
    E4 = mkcharge(-a, -a, +1, x, y)
    Ex = E1[0] + E2[0] + E3[0] + E4[0]
    Ey = E1[1] + E2[1] + E3[1] + E4[1]
    color = np.log(np.sqrt(Ex**2 + Ey**2))
    #streamplot(x, y, Ex/sqrt(Ex**2+Ey**2), Ey/sqrt(Ex**2+Ey**2), color=color, linewidth=1, cmap=plt.cm.inferno, density=3.5, minlength=0.11, arrowstyle='->', arrowsize=1.5)
    plt.streamplot(x, y, Ex/np.sqrt(Ex**2+Ey**2), Ey/np.sqrt(Ex**2+Ey**2), color=color, linewidth=1, cmap=plt.cm.inferno, density=3.5, arrowstyle='->', arrowsize=1.5)
    #color = u + v
    #streamplot(x, y, Ex/sqrt(Ex**2+Ey**2), Ey/sqrt(Ex**2+Ey**2), color=color, linewidth=1, cmap=plt.cm.seismic, density=2, arrowstyle='->', arrowsize=1.5)
    plt.xlabel('$x$')
    plt.ylabel('$y$')
    plt.savefig('electric_quadrupole.pdf', transparent=True, bbox_inches='tight', pad_inches=0)
コード例 #3
0
ファイル: efields.py プロジェクト: woznia62/E_fields
def capacitor(a):
    plt.figure(figsize=(20, 14), dpi=80)
    xlim = (a+2); ylim = (a+2)
    plt.axes = plt.gca()
    plt.axes.set_xlim([-xlim,xlim])
    plt.axes.set_ylim([-ylim,ylim])
    x = np.linspace(-xlim, xlim, 60)
    y = np.linspace(-ylim, ylim, 60)
    x, y = np.meshgrid(x, y)
    Lx = []
    Ly = []
    Ex = 0
    Ey = 0
    for m in range(-30,30):
        EFt = mkcharge(0.015*m, a, -1, x, y)
        Lx.append(EFt[0])
        Ly.append(EFt[1])
    for n in range(-30,30):
        EFb = mkcharge(0.015*n, -a, 1, x, y)
        Lx.append(EFb[0])
        Ly.append(EFb[1])
    for xelem in Lx:
        Ex += xelem
    for yelem in Ly:
        Ey += yelem
    color = np.log(np.sqrt(np.abs(Ex) + np.abs(Ey)))
    plt.streamplot(x, y, Ex/np.sqrt(Ex**2+Ey**2), Ey/np.sqrt(Ex**2+Ey**2), color=color, linewidth=1, cmap=plt.cm.inferno, density=2, arrowstyle='->', arrowsize=1.5)
    plt.xlabel('$x$')
    plt.ylabel('$y$')
    plt.savefig('capacitor.pdf', transparent=True, bbox_inches='tight', pad_inches=0)
コード例 #4
0
ファイル: test_pickle.py プロジェクト: Cassie90/matplotlib
def test_complete():
    fig = plt.figure('Figure with a label?', figsize=(10, 6))

    plt.suptitle('Can you fit any more in a figure?')

    # make some arbitrary data
    x, y = np.arange(8), np.arange(10)
    data = u = v = np.linspace(0, 10, 80).reshape(10, 8)
    v = np.sin(v * -0.6)

    plt.subplot(3, 3, 1)
    plt.plot(list(xrange(10)))

    plt.subplot(3, 3, 2)
    plt.contourf(data, hatches=['//', 'ooo'])
    plt.colorbar()

    plt.subplot(3, 3, 3)
    plt.pcolormesh(data)

    plt.subplot(3, 3, 4)
    plt.imshow(data)

    plt.subplot(3, 3, 5)
    plt.pcolor(data)

    plt.subplot(3, 3, 6)
    plt.streamplot(x, y, u, v)

    plt.subplot(3, 3, 7)
    plt.quiver(x, y, u, v)

    plt.subplot(3, 3, 8)
    plt.scatter(x, x**2, label='$x^2$')
    plt.legend(loc='upper left')

    plt.subplot(3, 3, 9)
    plt.errorbar(x, x * -0.5, xerr=0.2, yerr=0.4)

    ###### plotting is done, now test its pickle-ability #########

    # Uncomment to debug any unpicklable objects. This is slow (~200 seconds).
#    recursive_pickle(fig)

    result_fh = BytesIO()
    pickle.dump(fig, result_fh, pickle.HIGHEST_PROTOCOL)

    plt.close('all')

    # make doubly sure that there are no figures left
    assert_equal(plt._pylab_helpers.Gcf.figs, {})

    # wind back the fh and load in the figure
    result_fh.seek(0)
    fig = pickle.load(result_fh)

    # make sure there is now a figure manager
    assert_not_equal(plt._pylab_helpers.Gcf.figs, {})

    assert_equal(fig.get_label(), 'Figure with a label?')
コード例 #5
0
ファイル: track.py プロジェクト: LingBW/Auto-track
 def animate(n):  # del ax.collections[:]; del ax.lines[:]; ;
     ax.cla()
     if track_way == "backward":
         Time = (locstart_time - timedelta(hours=n)).strftime("%d-%b-%Y %H:%M")
     else:
         Time = (locstart_time + timedelta(hours=n)).strftime("%d-%b-%Y %H:%M")
     plt.suptitle(
         "%.f%% simulated drifters ashore\n%d days, %d m, %s" % (int(round(p)), track_days, depth, Time)
     )
     if streamline == "ON":
         plt.streamplot(
             lonpps[n], latpps[n], US[n], VS[n], color=speeds[n], arrowsize=4, cmap=plt.cm.cool, density=2.0
         )
     for j in xrange(stp_num):
         ax.plot(lon_set[j][0], lat_set[j][0], color=colors[j % 10], marker="x", markersize=4)
         if n >= len(lon_set[j]):
             ax.plot(lon_set[j][-1], lat_set[j][-1], "o", color=colors[j % 10], markersize=5)
         if n < 5:
             if n < len(lon_set[j]):
                 ax.plot(
                     lon_set[j][: n + 1], lat_set[j][: n + 1], "o-", color=colors[j % 10], markersize=4
                 )  # ,label='Depth=10m'
         if n >= 5:
             if n < len(lon_set[j]):
                 ax.plot(
                     lon_set[j][n - 4 : n + 1],
                     lat_set[j][n - 4 : n + 1],
                     "o-",
                     color=colors[j % 10],
                     markersize=4,
                 )
     draw_basemap(ax, points)  # points is using here
コード例 #6
0
ファイル: aero.py プロジェクト: minrk/fenics-16
def plot_cylinder_lift(gamma=4.):
    # computes the velocity field on the mesh grid
    u_vortex, v_vortex = get_velocity_vortex(gamma, x_vortex, y_vortex, X, Y)

    # computes the stream-function on the mesh grid
    psi_vortex = get_stream_function_vortex(gamma, x_vortex, y_vortex, X, Y)
    # superposition of the doublet on the freestream flow
    u = u_freestream + u_doublet + u_vortex
    v = v_freestream + v_doublet + v_vortex

    # calculates the stagnation points
    x_stagn1, y_stagn1 = +math.sqrt(R**2-(gamma/(4*math.pi*u_inf))**2), -gamma/(4*math.pi*u_inf)
    x_stagn2, y_stagn2 = -math.sqrt(R**2-(gamma/(4*math.pi*u_inf))**2), -gamma/(4*math.pi*u_inf)

    # plots the streamlines
    size = 10
    pyplot.figure(figsize=(size, (y_end-y_start)/(x_end-x_start)*size))
    pyplot.xlabel('x', fontsize=16)
    pyplot.ylabel('y', fontsize=16)
    pyplot.xlim(x_start, x_end)
    pyplot.ylim(y_start, y_end)
    pyplot.streamplot(X, Y, u, v, density=2, linewidth=1, arrowsize=1.5, arrowstyle='->')
    circle = pyplot.Circle((0, 0), radius=R, color='#CD2305', alpha=0.5)
    pyplot.gca().add_patch(circle)
    pyplot.scatter(x_vortex, y_vortex, color='#CD2305', s=80, marker='o')
    pyplot.scatter([x_stagn1, x_stagn2], [y_stagn1, y_stagn2], color='g', s=80, marker='o');
コード例 #7
0
def test_linewidth():
    X, Y, U, V = velocity_field()
    speed = np.hypot(U, V)
    lw = 5 * speed / speed.max()
    df = 25 / 30   # Compatibility factor for old test image
    plt.streamplot(X, Y, U, V, density=[0.5 * df, 1. * df], color='k',
                   linewidth=lw)
コード例 #8
0
ファイル: track.py プロジェクト: LingBW/Auto-track
 def animate(n):  # del ax.collections[:]; del ax.lines[:]; ax.cla();ax.clf()
     ax.cla()
     if streamline == "ON":
         plt.streamplot(
             lonpps[n], latpps[n], US[n], VS[n], color=speeds[n], arrowsize=4, cmap=plt.cm.cool, density=2.0
         )
     for j in range(stp_num):
         if n == 0:  # facecolor=colors[i]'''
             ax.annotate(
                 "Start %d" % (j + 1),
                 xy=(lon_set[j][0], lat_set[j][0]),
                 xytext=(lon_set[j][0] + 0.01 * stp_num, lat_set[j][0] + 0.01 * stp_num),
                 fontsize=6,
                 arrowprops=dict(arrowstyle="fancy"),
             )
         if n < len(lon_set[j]):  # markerfacecolor='r',
             ax.plot(
                 lon_set[j][: n + 1],
                 lat_set[j][: n + 1],
                 "o-",
                 color=colors[j % 10],
                 markersize=4,
                 label="Start %d" % (j + 1),
             )
     draw_basemap(ax, points)  # points is using here
コード例 #9
0
def test_masks_and_nans():
    X, Y, U, V = velocity_field()
    mask = np.zeros(U.shape, dtype=bool)
    mask[40:60, 40:60] = 1
    U = np.ma.array(U, mask=mask)
    U[:20, :20] = np.nan
    plt.streamplot(X, Y, U, V, color=U, cmap=plt.cm.Blues)
コード例 #10
0
ファイル: two-state.py プロジェクト: argriffing/ctmczoo
def plot_streamplot():
    a = Model(1, 1)
    J = a.joint_distn
    gridshape = (20, 20)
    U = np.empty(gridshape, dtype=float)
    V = np.empty(gridshape, dtype=float)
    Y, X = np.mgrid[0.1:2:20j, 0.1:2:20j]
    for i in range(20):
        for j in range(20):
            ap = X[i, j]
            bp = Y[i, j]
            b = Model(ap, bp)
            alpha, beta = b.solve_EM(J)
            U[i, j] = alpha - ap
            V[i, j] = beta - bp

    # init the figure
    pyplot.figure(figsize=(10, 10))

    # stream plot
    speed = np.sqrt(U*U + V*V)
    lw = 5 * speed / speed.max()
    pyplot.streamplot(X, Y, U, V, density=0.8, color='k', linewidth=lw)
    #pyplot.show()
    pyplot.savefig('streamplot.png')
コード例 #11
0
def displayWindMapPlot(vdata,udata, lons, lats,):
    """ TODO add a docstring! """
    #plt.clf()
    #pc = plt.contourf(lons, lats, data, 20)
    #plt.colorbar(pc, orientation='horizontal')
    #plt.title(title)
    #plt.xlabel("longitude (degrees east)")
    #plt.ylabel("latitude (degrees north)")
    #plt.show()
    fig, ax = plt.subplots()
    # Do the plot code
    # make orthographic basemap.
    m = Basemap(projection='cyl',llcrnrlat=-40,urcrnrlat=0,\
            llcrnrlon=-20,urcrnrlon=60,resolution='l')

    X,Y=np.meshgrid(lons, lats)
    x,y=m(X,Y) #Convert to map coordinates
    #m.barbs(x,y,vdata,udata,20)
    m.quiver(x,y,vdata,udata,10)
    plt.streamplot(x,y,vdata,udata,10)
    #plt.colorbar(pc,orientation='horizontal')
    m.drawmapboundary()
    m.drawcountries()
    
    m.drawcoastlines(linewidth=1.5)
    
    fig.savefig('myimage.svg', format='svg', dpi=1200)
    plt.show()
    #m.drawparallels(parallels)
    #m.drawmeridians(meridians)
    
    
    """ Contains code for displaying data """
コード例 #12
0
def test_startpoints():
    X, Y, U, V = velocity_field()
    start_x = np.linspace(X.min(), X.max(), 10)
    start_y = np.linspace(Y.min(), Y.max(), 10)
    start_points = np.column_stack([start_x, start_y])
    plt.streamplot(X, Y, U, V, start_points=start_points)
    plt.plot(start_x, start_y, 'ok')
コード例 #13
0
def test_masks_and_nans():
    X, Y, U, V = velocity_field()
    mask = np.zeros(U.shape, dtype=bool)
    mask[40:60, 40:60] = 1
    U[:20, :20] = np.nan
    U = np.ma.array(U, mask=mask)
    with np.errstate(invalid='ignore'):
        plt.streamplot(X, Y, U, V, color=U, cmap=plt.cm.Blues)
コード例 #14
0
def plot_stresses_cartesian(chi, F, R_min):#, R_max, R_steps):
    Y, X = np.mgrid[-5:5:1000j, -5:5:1000j]
    R = np.sqrt(X**2. + Y**2.)

    # pre_X = np.linspace(-R_max, R_max, R_steps) 
    # X, Y = np.meshgrid(pre_X, pre_X)
    # R = np.sqrt(X**2. + Y**2.)

    cart_betas1 = stress_beta1_cartesian(X, Y, chi, F, R_min)
    beta_X1s = to_unit_vector_x(cart_betas1)
    beta_Y1s = to_unit_vector_y(cart_betas1)
    beta_X1s[R<1] = 1
    beta_Y1s[R<1] = 0

    cart_betas2 = stress_beta2_cartesian(X, Y, chi, F, R_min)
    beta_X2s = to_unit_vector_x(cart_betas2)
    beta_Y2s = to_unit_vector_y(cart_betas2)
    beta_X2s[R<1] = 0
    beta_Y2s[R<1] = 1

    fig = plt.figure(figsize=(5, 5))
    ax=fig.add_subplot(111)

    # streamplot
    # ax=fig.add_subplot(111)
    ax.set_title('Stress Trajectories')
    plt.streamplot(X, Y, beta_X1s, beta_Y1s, arrowstyle='-', density=2.7, color='b', minlength=0.9)
    plt.streamplot(X, Y, beta_X2s, beta_Y2s, arrowstyle='-', density=1.1, color='olive', minlength=0.9)

    ax.add_patch(Circle((0, 0), radius=1, zorder=10, facecolor='k', linewidth=2))

    plt.axis("image")
    # ax.add_patch(Circle((6.55, 0), radius=.2, zorder=10, facecolor='r', linewidth=1))
    # ax.add_patch(Circle((-6.55, 0), radius=.2, zorder=10, facecolor='r', linewidth=1))
    # ax.add_patch(Circle((-np.sqrt(2)/2., np.sqrt(2)/2.), radius=.2, zorder=10, facecolor='r', linewidth=1))
    # ax.add_patch(Circle((-np.sqrt(2)/2., -np.sqrt(2)/2.), radius=.2, zorder=10, facecolor='r', linewidth=1))

    # quiver
    # plt.quiver(X, Y, beta_X1s, beta_Y1s, pivot='middle', headwidth=2, headlength=4, color='b')
    # plt.quiver(X, Y, beta_X2s, beta_Y2s, pivot='middle', headwidth=2, headlength=4, color='g')
    for label in ax.xaxis.get_ticklabels() + ax.yaxis.get_ticklabels():
        # label is a Text instance
        label.set_color('k')
        # label.set_rotation(45)
        label.set_fontsize(12)

    for line in ax.xaxis.get_ticklines() + ax.yaxis.get_ticklines():
        # line is a Line2D instance
        line.set_color('k')
        line.set_markersize(5)
        line.set_markeredgewidth(2)

    plt.xlabel(r'$\chi = $'+str(round(chi, 1)) + ', ' + r'$F = $'+ str(round(F, 1)))
    plt.ylim(-5, 5)
    plt.xlim(-5, 5)
    # plt.tight_layout()
    # plt.savefig("stream.png", dpi=300)
    plt.show()
コード例 #15
0
ファイル: function2d.py プロジェクト: lukemarris/ctf
 def plot_both(self, c_points=200, g_points=200):
     """ Plots the grad quiver plot over the domain of the function. """
     # Latex
     plt.rc('text', usetex=True)
     plt.rc('font', family='serif')
     ## Domain Correction
     # Lower x0 Limit
     if np.isfinite(self.domain[0][0]):
         x0_lim_lower = self.domain[0][0]
     else:
         x0_lim_lower = -10.0
     # Upper x0 Limit
     if np.isfinite(self.domain[0][1]):
         x0_lim_upper = self.domain[0][1]
     else:
         x0_lim_upper = +10.0
     # Lower x1 Limit
     if np.isfinite(self.domain[1][0]):
         x1_lim_lower = self.domain[1][0]
     else:
         x1_lim_lower = -10.0
     # Upper x1 Limit
     if np.isfinite(self.domain[1][1]):
         x1_lim_upper = self.domain[1][1]
     else:
         x1_lim_upper = +10.0
     ## Lines
     x0c = np.linspace(x0_lim_lower, x0_lim_upper, c_points)
     x1c = np.linspace(x1_lim_lower, x1_lim_upper, c_points)
     x0g = np.linspace(x0_lim_lower, x0_lim_upper, g_points)
     x1g = np.linspace(x1_lim_lower, x1_lim_upper, g_points)
     ## Meshes
     X0c, X1c = np.meshgrid(x0c, x1c)
     X0g, X1g = np.meshgrid(x0g, x1g)
     ## Combined
     Xc = np.array([X0c, X1c])
     Xg = np.array([X0g, X1g])
     ## Calculate Costs
     cost = self.cost(Xc)
     ## Renormalise
     cost_norm = np.log(cost - np.min(cost) + 1)
     ## Calculate Grad
     grad = self.grad(Xg)
     ## Renormalise
     grad_norm = grad / np.linalg.norm(grad, axis=0)
     ## Plot
     plt.figure()
     plt.contourf(X0c, X1c, cost_norm, 50)
     plt.scatter(self.min[..., 0], self.min[..., 1], c='w', marker='x')
     plt.streamplot(X0g, X1g, -grad_norm[0], -grad_norm[1], density=4.0, color='k')
     plt.scatter(self.min[0], self.min[1], c='w', marker='x')
     plt.grid()
     plt.title(self.latex_name + "\n" + self.latex_cost)
     plt.subplots_adjust(top=0.8)
     plt.xlabel('$x_0$')
     plt.ylabel('$x_1$')
     plt.xlim([x0_lim_lower, x0_lim_upper])
     plt.ylim([x1_lim_lower, x1_lim_upper])
コード例 #16
0
ファイル: Track.py プロジェクト: brorfred/Track_Python
 def animate(n): #del ax.collections[:]; del ax.lines[:]; ax.cla();ax.clf()
     ax.cla()
     ax.plot(drifter_points['lon'],drifter_points['lat'],'bo-',markersize=6,label='Drifter')
     if streamline == 'ON':
         plt.streamplot(lonpps[n],latpps[n],US[n],VS[n], color=speeds[n],arrowsize=4,cmap=plt.cm.cool,density=2.0)              
     if n==0:#facecolor=colors[i]'''
         ax.annotate(an2,xy=(dr_points['lon'][-1],dr_points['lat'][-1]),xytext=(dr_points['lon'][-1]+0.01*track_days,
                     dr_points['lat'][-1]+0.01*track_days),fontsize=6,arrowprops=dict(arrowstyle="fancy"))
     ax.plot(model_points['lon'][:n+1],model_points['lat'][:n+1],'ro-',markersize=6,label=MODEL)
     draw_basemap(ax, points)  # points is using here
コード例 #17
0
ファイル: MacroLab.py プロジェクト: yiyuezhuo/EconomicNote
def stream(i,a,b):
    '''
    dy=c+i-y
    dc=a+b*y-c
    '''
    y, c = np.mgrid[0:30:100j, 0:30:100j]
    dy=c+i-y
    dc=a+b*y-c
    plt.streamplot(c,y,dc,dy)
    plt.show()
コード例 #18
0
ファイル: main.py プロジェクト: IsabelleTan/Vortex
def velFieldPlot(folder, t_0, t_end, iter):
    # Go to current directory
    curDir = os.getcwd()
    os.chdir(curDir)

    # Prepare image
    fig = plt.figure()
    fig.add_subplot(111)

    # Read data
    filenameX = folder + "/" + str(iter) + "_X.txt"
    filenameY = folder + "/" + str(iter) + "_Y.txt"
    filenameU = folder + "/" + str(iter) + "_U.txt"
    filenameV = folder + "/" + str(iter) + "_V.txt"
    nParticles, X = readFile(filenameX)
    nParticles, Y = readFile(filenameY)
    nParticles, U = readFile(filenameU)
    nParticles, V = readFile(filenameV)

    # Interpolate onto grid
    U_grid = interpolate(X,Y,U)
    V_grid = interpolate(X,Y,V)

    # Compute the extent of the coordinates
    xmin = np.min(X)
    ymin = np.min(Y)
    xmax = np.max(X)
    ymax = np.max(Y)

    # Make an XY grid corresponding to the interpolated locations of U and V
    Y_grid, X_grid = np.mgrid[xmin:xmax:400j, ymin:ymax:400j]

    # Make a speed grid
    speed = np.sqrt(U_grid**2 + V_grid**2)
    print(speed.max())
    if(speed.max() != 0):
        lw = 3*speed/speed.max()
    else:
        lw = 1
        print("Maximum speed is 0.")


    # Make a streamfunction plot
    plt.streamplot(X_grid, Y_grid, U_grid.T, V_grid.T,          # data
                   density=[0.5, 1],
                   color='DarkRed',
                   linewidth=lw)

    plt.title('Streamline Plot, at t = 0.00001 sec')
    plt.xlabel("x")
    plt.ylabel("y")
    plt.show(fig)


    return
コード例 #19
0
ファイル: f05.py プロジェクト: robjstan/modelling-course
def plot_fisher(c:(0,4,0.1)=1):
    gx, gy = np.meshgrid(np.linspace(-0.5, 1.5, 11), \
                         np.linspace(-1, 1, 11))
    dx, dy = fisher([gx, gy], 0, c)

    plt.figure(figsize=[9,6])
    plt.streamplot(gx, gy, dx, dy, color=col[0])
    plt.xlabel('U')
    plt.ylabel('V')
    plt.xlim(-0.5,1.5)
    plt.ylim(-1,1)
    plt.show()
コード例 #20
0
def PhasePortrait(p):
    Y, X = np.mgrid[0.1:0.3:5000j, 0:0.72:5000j]
    K1, K2, K3, KM1, KM3 = p
    U, V = [K1*(1 - X - 2*Y) - KM1*X - K3*X*(1 - X - 2*Y) + KM3*Y - K2*((1 - X - 2*Y)**2)*X,
            K3*X*(1 - X - 2*Y) - KM3*Y]
    #U, V = [K1*(1 - X - Y) - KM1*X - K3*X + KM3*Y - K2*((1 - X - Y)**2)*X,
    #        K3*X - KM3*Y]
    plt.streamplot(X, Y, U, V, density = [2, 2])
    plt.xlim([0, 0.72])
    plt.ylim([0.1, 0.3])
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()
コード例 #21
0
ファイル: star_model.py プロジェクト: tthieme/Akamai2016
def plot_streamplot(r,z,Br,Bz,title='',xlab = '',ylab=''):
    
    """
    This function creates a streamplot with four parameters (r,z,Br,Bz).
    """
    
    plt.streamplot(r, z, Br, Bz)
    plt.title(title, fontsize=16)
    plt.xlabel(xlab, fontsize=14)
    plt.ylabel(ylab, fontsize=14)
    plt.xticks(fontsize=8)
    plt.yticks(fontsize=8)
    plt.legend()
コード例 #22
0
ファイル: streamplot.py プロジェクト: jzrake/ctf
def draw_streamlines(fx, fy, title=None):
    plt.figure()
    plt.axis('equal')
    plt.title(title)
    nz = h5f['prim/vx'].shape[2]
    vx = h5f['prim/%s'%fx][:,:,nz/2].T
    vy = h5f['prim/%s'%fy][:,:,nz/2].T
    scalar = vx**2 + vy**2
    x = np.linspace(-0.5, 0.5, vx.shape[0])
    y = np.linspace(-0.5, 0.5, vx.shape[1])
    plt.xlim(-0.5, 0.5)
    plt.ylim(-0.5, 0.5)
    plt.streamplot(x, y, vx, vy, color=scalar, density=4, cmap='cool')
コード例 #23
0
def plot_current_field(xs,ys,vx,vy):
    ###define grid
    x_grid = np.linspace(xs.min(),xs.max(),200)
    y_grid = np.linspace(ys.min(),ys.max(),200)

    vxs = griddata(xs, ys, vx, x_grid, y_grid, interp='linear')
    vys = griddata(xs, ys, vy, x_grid, y_grid, interp='linear')


    speed = np.sqrt(vxs**2+vys**2)
    lw = 5*speed / speed.max()
    plt.figure()
    plt.streamplot(x_grid, y_grid, vxs,vys, color=lw, linewidth=2, cmap=plt.cm.autumn)
    plt.colorbar()
    plt.show()
コード例 #24
0
ファイル: post_processing.py プロジェクト: GitDerek/pyIBM
def plot_velocity(u, v, body=None, limits=None):
	"""Plots velocity field on the mesh.
	
	Arguments
	---------
	u, v -- instances Variable for the velocity components.
	body -- immersed body (default None).
	limits -- plot limits (default None).
	"""
	u.read()
	v.read()
	
	# initializes figure
	plt.figure(num=None)
	plt.grid(False)
	plt.xlabel(r'$x$', fontsize=20)
	plt.xlabel(r'$y$', fontsize=20)

	# creates contour of velocity magnitude and adds streams
	nc = 100
	magn = np.sqrt(u.field**2+v.field**2)
	umin, umax = magn.min(), magn.max()
	umin, umax = 0., 1.
	levels = np.linspace(umin, umax, nc)

	cont = plt.contourf(Mesh.x, Mesh.y, magn.reshape(Mesh.Nx, Mesh.Ny),
						levels, extend='both', cmap=cm.jet)
	cbar = plt.colorbar(cont)
	cbar.set_label('velocity')

	plt.streamplot(Mesh.x, Mesh.y,
				   u.field.reshape(Mesh.Ny, Mesh.Nx),
				   v.field.reshape(Mesh.Ny, Mesh.Nx))

	# plots body if there is one
	if Mesh.is_body:
		plt.plot(np.append(body.x,body.x[0]), np.append(body.y, body.y[0]), 'k', ls='-', lw=1)

	# sets axis limits
	plt.xlim(limits[0], limits[1])
	plt.ylim(limits[2], limits[3])

	# inserts title and saves the figure
	plt.title('velocity - '+str(Parameters.ite))
	plt.savefig(Case.path+'/images/'+'velocity'+str('%04d'%(Parameters.ite,))+'.png')
	
	plt.clf()
	plt.close()
コード例 #25
0
ファイル: testfunctions.py プロジェクト: jwyl/joycesoft
def streamlineBxz_dens():
    fig=plt.figure()
    ppy=yt.ProjectionPlot(ds, "y", "Bxz", weight_field="density") #Project X-component of B-field from z-direction
    By=ppy._frb["density"]
    ax=fig.add_subplot(111)
    plt.xticks(tick_locs,tick_lbls)
    plt.yticks(tick_locs,tick_lbls)
    Bymag=ax.pcolormesh(np.log10(By), cmap="YlGn")
    cbar_m=plt.colorbar(Bymag)
    cbar_m.set_label("density")
    res=800

    #densxy=Density2D(0,1) #integrated density along given axis
    U=Flattenx(0,1) #X-magnetic field integrated along given axis
    V=Flattenz(0,1) #Z-magnetic field
    #U=np.asarray(zip(*x2)[::-1]) #rotate the matrix 90 degrees to correct orientation to match projected plots
    #V=np.asarray(zip(*y2)[::-1])
    norm=np.sqrt(U**2+V**2) #magnitude of the vector
    Unorm=U/norm #normalise vectors 
    Vnorm=V/norm
    #mask_Unorm=np.ma.masked_where(densxy<np.mean(densxy),Unorm) #create a masked array of Unorm values only in high density regions
    #mask_Vnorm=np.ma.masked_where(densxy<np.mean(densxy),Vnorm)
    X,Y=np.meshgrid(np.linspace(0,res,64, endpoint=True),np.linspace(0,res,64,endpoint=True))
    streams=plt.streamplot(X,Y,Unorm,Vnorm,color=norm*1e6,density=(3,3),cmap=plt.cm.autumn)
    cbar=plt.colorbar(orientation="horizontal")
    cbar.set_label('Bxz streamlines (uG)')
    plt.title("Bxz streamlines on weighted density projection")
    plt.xlabel("(1e4 AU)")
    plt.ylabel("(1e4 AU)")
コード例 #26
0
ファイル: post.py プロジェクト: sayop/CFM03
def plotStreamLine(x,y,U,V,nIter):
   pltFile = 'streamLine_%5.5d.png' % int(nIter)
   x = np.asarray(x)
   y = np.asarray(y)
   U = np.swapaxes(U,1,0)
   V = np.swapaxes(V,1,0)

   strm = plt.streamplot(x,y,U,V, color='k', density=1, linewidth=1)

   plt.axis([x.min(), x.max(), y.min(), y.max()])
   plt.xscale('linear')
   plt.yscale('linear')
   plt.xlabel('x [m]', fontsize=18)
   plt.ylabel('y [m]', fontsize=18)
   plt.grid(True)
   ax = plt.gca()
   xlabels = plt.getp(ax, 'xticklabels')
   ylabels = plt.getp(ax, 'yticklabels')
   plt.setp(xlabels, fontsize=10)
   plt.setp(ylabels, fontsize=10)

   fig = plt.gcf()
   fig.set_size_inches(5,6)
   plt.tight_layout()
   plt.savefig(pltFile, format='png')
   plt.close()

   print "%s DONE!!" % (pltFile)
   plt.show()
コード例 #27
0
def streamline_plot(time, v, x_min, x_max, y_min, y_max):
    print(v.shape)
    fig = plt.figure(figsize = (20, 5))
    ax = plt.subplot(111)
    ax.set_xlabel(u'X-координата.')
    ax.set_ylabel(u'Y-координата.')
#    plt.title(u'Линии тока, Re=' + str(Re) + '.')
    
    x = np.array([i for i in range(x_min,x_max)])
    y = np.array([i for i in range(y_min, y_max)])
    
    vx = v[0].transpose()
    vy = v[1].transpose()
    
    
#    print(v.shape)
    vx = vx[y_min:y_max,x_min:x_max]
    vy = vy[y_min:y_max,x_min:x_max]
    strm = plt.streamplot(x, y, vx, vy, density = [0.6, 1], linewidth=2, color = '#1f77b4')  # color = 'k', linewidth=2, minlength = 0.1) #cmap=plt.cm.autumn
    #plt.colorbar(strm.lines)
    
    obstacle = plt.Circle((cx, cy), r, color='k')
    ax.add_artist(obstacle)
    
    out_name = '_'.join(['strml', 're' + str(Re), 't' + str(time)])
    out_name += '.png'
    plt.savefig(out_name)
    plt.clf()
コード例 #28
0
ファイル: efields.py プロジェクト: woznia62/E_fields
def planes(r, theta):
    """Function: Planes(r, theta)
    Plot two intersecting planes using n point charges superimposed, where the planes have length
    2*r and are separated by an angle theta (in degrees)."""
    plt.figure(figsize=(20, 14))
    n=30
    d = 0.03
    xlim = n*d*r + 1; ylim = n*d*r +1
    plt.axes = plt.gca()
    plt.axes.set_xlim([-xlim,xlim])
    plt.axes.set_ylim([-ylim,ylim])
    x = np.linspace(-xlim, xlim, 100)
    y = np.linspace(-ylim, ylim, 100)
    x, y = np.meshgrid(x, y)
    lboxx = []
    lboxy = []
    Ex = 0
    Ey = 0
    trad = theta*np.pi/180
    a = 0
    b = 0
    c = 0
    for l in range(1,n+1):
        a += d*r*np.cos(trad)
        b += d*r*np.sin(trad)
        c += d*r
        E1 = mkcharge( -c, 0, 1, x, y)
        E2 = mkcharge( c, 0, 1, x, y)
        E3 = mkcharge( a, b, -1, x, y)
        E4 = mkcharge( -a, -b, -1, x, y)
        lboxx.append(E1[0])
        lboxx.append(E2[0])
        lboxx.append(E3[0])
        lboxx.append(E4[0])
        lboxy.append(E1[1])
        lboxy.append(E2[1])
        lboxy.append(E3[1])
        lboxy.append(E4[1])
    for xelem in lboxx:
        Ex += xelem
    for yelem in lboxy:
        Ey += yelem
    color = np.log(np.sqrt(np.abs(Ex) + np.abs(Ey)))
    plt.streamplot(x, y, Ex/np.sqrt(Ex**2+Ey**2), Ey/np.sqrt(Ex**2+Ey**2), color=color, linewidth=1, cmap=plt.cm.inferno, density=2, arrowstyle='->', arrowsize=1.5)
    plt.xlabel('$x$')
    plt.ylabel('$y$')
    plt.savefig('electric_planes.pdf', transparent=True, bbox_inches='tight', pad_inches=0)
コード例 #29
0
def phaseport(derivs,BL,UR,gridspacing=.01,linedensity=1):
    from pylab import arange, array
    X=arange(BL[0],UR[0],gridspacing)
    Y=arange(BL[1],UR[1],gridspacing)
    dx, dy = map(deriv,derivs)
    U=array([[dx(x=x,y=y) for x in X] for y in Y])
    V=array([[dy(x=x,y=y) for x in X] for y in Y])
    return plt.streamplot(X,Y,U,V,density=linedensity)
コード例 #30
0
ファイル: f05.py プロジェクト: robjstan/modelling-course
def plot_fisher2(c:(0,4,0.1)=1):
    gx, gy = np.meshgrid(np.linspace(0, 1.1, 11), \
                         np.linspace(-0.5, 0.1, 21))
    dx, dy = fisher([gx, gy], 0, c)

    t = np.linspace(0, 100, 500)
    u,v = list(zip(* integrate.odeint(fisher, [0.9999,0], t, (c,)) ))

    plt.figure(figsize=[9,6])
    plt.streamplot(gx, gy, dx, dy, color=col[0])
    plt.scatter([0,1],[0,0], s=60, marker='o', c='k')
    plt.plot(u,v, c='k')
    plt.xlabel('U')
    plt.ylabel('V')
    plt.xlim(-0.01,1.01)
    plt.ylim(-0.5,0.01)
    plt.show()
            if b / 2 < x[i] < 3 * b / 2 and abs(y[j]) > 0.5 * (2 - b):
                ux[j, i] = 0
                uy[j, i] = 0

    ux = np.roll(ux, shift=int(Nx / 2), axis=1)
    uy = np.roll(uy, shift=int(Nx / 2), axis=1)

    speed = np.sqrt(np.square(ux) + np.square(uy))
    plt.gca().set_aspect('equal', adjustable='box')

    if k % 3 == 0:
        for i in [0, 1, 2, 3]:
            plt.streamplot(X + 2 * b * i,
                           Y,
                           ux,
                           uy,
                           density=0.6 + 0.3,
                           color='k',
                           arrowsize=0.6)
            CS = plt.contourf(X + 2 * b * i, Y, speed, 10, cmap=Map)
            if i == 0:
                cbar = plt.colorbar(CS, fraction=0.02725, pad=0.02)
                cbar.ax.set_ylabel('Velocity $[U]$', fontsize=8)
                cbar.ax.yaxis.set_major_formatter(
                    tick.FormatStrFormatter('%.1f'))
            plt.fill_between([0 + 2 * b * i, b / 2 + 2 * b * i],
                             [-1 - b / 2, -1 - b / 2],
                             [-1 + b / 2, -1 + b / 2],
                             color="k")
            plt.fill_between([0 + 2 * b * i, b / 2 + 2 * b * i],
                             [+1 + b / 2, +1 + b / 2],
コード例 #32
0
ファイル: Vortex.py プロジェクト: oncernhan/PythonCFD
def vortex_function(strength, xv, yv, X, Y):
    u = strength / (2*pi) * (Y - yv) / ((X - xv)**2 + (Y - yv)**2)
    v =-strength / (2*pi) * (X - xv) / ((X - xv)**2 + (Y - yv)**2)
    psi = strength / (4*pi) * np.log((X - xv)**2 + (Y - yv)**2)
    return u, v, psi

u_vortex, v_vortex, psi_vortex = vortex_function(gamma, x_vortex, y_vortex, X, Y)

width = 10.0
length = (y_end - y_start) / (x_end - x_start) * width
plt.figure(figsize = (width, length))
plt.xlabel('x', fontsize = 16)
plt.ylabel('y', fontsize = 16)
plt.xlim(x_start, x_end)
plt.ylim(y_start, y_end)
plt.streamplot(X, Y, u_vortex, v_vortex, density = 2, linewidth = 1, arrowsize = 1, arrowstyle = '->')
plt.scatter(x_vortex, y_vortex, color = '#CD2305', s = 80, marker = 'o')
plt.show()


"""Vortex and Sink"""
from Source_Sink_Freestream import freestream, source_sink, stream_function_source_sink

strength_sink = -1.0
x_sink, y_sink = 0.0, 0.0
u_freestream, v_freestream, psi_freestream = freestream(N, Y)
u_sink, v_sink = source_sink(strength_sink, x_sink, y_sink, X, Y)
psi_sink = stream_function_source_sink(strength_sink, x_sink, y_sink, X, Y)

u_combine = u_sink + u_vortex + u_freestream
v_combine = v_sink + v_vortex + v_freestream
コード例 #33
0
def test_streamplot_grid():
    u = np.ones((2, 2))
    v = np.zeros((2, 2))

    # Test for same rows and columns
    x = np.array([[10, 20], [10, 30]])
    y = np.array([[10, 10], [20, 20]])

    with pytest.raises(ValueError, match="The rows of 'x' must be equal"):
        plt.streamplot(x, y, u, v)

    x = np.array([[10, 20], [10, 20]])
    y = np.array([[10, 10], [20, 30]])

    with pytest.raises(ValueError, match="The columns of 'y' must be equal"):
        plt.streamplot(x, y, u, v)

    x = np.array([[10, 20], [10, 20]])
    y = np.array([[10, 10], [20, 20]])
    plt.streamplot(x, y, u, v)

    # Test for maximum dimensions
    x = np.array([0, 10])
    y = np.array([[[0, 10]]])

    with pytest.raises(ValueError, match="'y' can have at maximum "
                                         "2 dimensions"):
        plt.streamplot(x, y, u, v)

    # Test for equal spacing
    u = np.ones((3, 3))
    v = np.zeros((3, 3))
    x = np.array([0, 10, 20])
    y = np.array([0, 10, 30])

    with pytest.raises(ValueError, match="'y' values must be equally spaced"):
        plt.streamplot(x, y, u, v)

    # Test for strictly increasing
    x = np.array([0, 20, 40])
    y = np.array([0, 20, 10])

    with pytest.raises(ValueError, match="'y' must be strictly increasing"):
        plt.streamplot(x, y, u, v)
コード例 #34
0
	for i in range(len(x)):
		for j in range(len(y)):
			if b/2 < x[i] < 3*b/2 and abs(y[j]) > 0.5*(2-b):
				ux[j,i] = 0
				uy[j,i] = 0

	ux = np.roll(ux, shift=int(Nx/2), axis=1)
	uy = np.roll(uy, shift=int(Nx/2), axis=1)

	speed = np.sqrt(np.square(ux) + np.square(uy))
	plt.gca().set_aspect('equal', adjustable='box')

	if k % 3 == 0:
		for i in [0, 1, 2, 3]:
			plt.streamplot(X+2*b*i, Y, ux, uy, density=1.0, color='k')
			CS = plt.contourf(X+2*b*i, Y, speed, 100, cmap="Spectral")
			if i == 0:
				cbar = plt.colorbar(CS, fraction=0.02725, pad=0.02)
				cbar.ax.set_ylabel('Velocity $[U]$', fontsize=12)
				cbar.ax.yaxis.set_major_formatter(tick.FormatStrFormatter('%.1f'))
			plt.fill_between([0+2*b*i, b/2+2*b*i], [-1-b/2, -1-b/2], [-1+b/2, -1+b/2],     color="k")
			plt.fill_between([0+2*b*i, b/2+2*b*i], [+1+b/2, +1+b/2], [+1-b/2, +1-b/2],     color="k")
			plt.fill_between([3*b/2+2*b*i, 2*b+2*b*i], [+1+b/2, +1+b/2], [+1-b/2, +1-b/2], color="k")
			plt.fill_between([3*b/2+2*b*i, 2*b+2*b*i], [-1-b/2, -1-b/2], [-1+b/2, -1+b/2], color="k")
			plt.fill_between([0, 2*b+2*b*i], [-1-b/2, -1-b/2], [-1-b_max/2, -1-b_max/2],   color="k")
			plt.fill_between([0, 2*b+2*b*i], [1+b/2, 1+b/2],   [1+b_max/2, 1+b_max/2],     color="k")
			#plt.axis([0, i*2*b+2*b, -1-b_max/2, 0])


	if int(k - 1) % 3 == 0:
コード例 #35
0
titleVelocity = "MAGNITUDE KECEPATAN" " (t= 1 s)"
titlePressure = "MEDAN SKALAR TEKANAN" " (t= 1 s)"

fig1 =  plt.figure()
plt.pcolor(x,y,VelocityMagnitude, cmap=colorMagnitude)
plt.colorbar()
plt.quiver(x,y,U,V)
plt.xlabel("x")
plt.ylabel("y")
plt.title(titleVelocity )
plt.show()

fig2 =  plt.figure()
plt.pcolor(x,y,VelocityMagnitude, cmap=colorMagnitude)
plt.colorbar()
plt.streamplot(x,y,U,V, color='k')
plt.xlabel("x")
plt.ylabel("y")
plt.title(titleVelocity)
plt.show()

fig3 =  plt.figure()
plt.pcolor(x,y,Pn, cmap=colorPressure)
plt.colorbar()
plt.quiver(x,y,U,V)
plt.xlabel("x")
plt.ylabel("y")
plt.title(titlePressure)
plt.show()

fig4 =  plt.figure()
コード例 #36
0
ファイル: VortexLift.py プロジェクト: Nic42/AeroHydro
psiFreestream = Uinf * Y

# superimposing the doublet and freestream flow
# which is the same as defining flow around a cylinder
u = uDoublet + uFreestream
v = vDoublet + vFreestream
psi = psiDoublet + psiFreestream

# plotting
size = 10
plt.figure(figsize=(size, (yEnd - yStart) / (xEnd - xStart) * size))
plt.xlim(xStart, xEnd)
plt.ylim(yStart, yEnd)
plt.xlabel('x', fontsize=16)
plt.ylabel('y', fontsize=16)
plt.streamplot(X, Y, u, v, density=2.0, arrowsize=1.0, arrowstyle='->')
plt.scatter(xDoublet, yDoublet, s=80, c='r')

# calculating and plotting a circle over the cylinder
R = np.sqrt(kappa / (2 * pi * Uinf))
circle = plt.Circle((0, 0), radius=R, color='r', alpha=0.5)
plt.gca().add_patch(circle)

# calculating and adding the stagnation points
xStagn1, yStagn1 = +np.sqrt(kappa / (2 * pi * Uinf)), 0
xStagn2, yStagn2 = -np.sqrt(kappa / (2 * pi * Uinf)), 0
plt.scatter([xStagn1, xStagn2], [yStagn1, yStagn2], c='g', s=80, marker='o')

# defining a vortex located at the origin
gamma = 7.5  # strength of a vortex
xVortex, yVortex = 0.0, 0.0
コード例 #37
0
for i in range(3):
    min = dummy.max()
    minList = np.append(minList, min)
    location = np.where(dummy == min)
    locationList = np.append(locationList, location)
    dummy = dummy[dummy != min]
print(locationList)
print(minList)
'''

#force2 = force2(x_2d,y_2d)
#fig = plt.figure()
plt.xlabel("x")
plt.ylabel("y")
plt.title("Force Plot in Two Dimensions")
plt.streamplot(x_1, y_1, force2_x, force2_y, color='black')

#plt.plot(force2)
#xs = np.linspace(-2, 2, 11)
#ys = np.linspace(-2, 2, 11)

#for x in x_1:
#plt.quiver(x_2d, y_2d, force2_x, force2_y)
#[np.ones(len(y_1))*x
#plt.quiver(force2_x, force2_y, [force2])
#plt.plot(force2_x, force2_y)
#plt.show()

#force2 = np.vstack((force2_x, force2_y))
#force2 = np.transpose(force2)
コード例 #38
0
pyplot.ylabel('y', fontsize=16)
pyplot.xlim(x_start, x_end)
pyplot.ylim(y_start, y_end)
pyplot.scatter(X, Y, s=5, color='#CD2305', marker='o')

strength_source = 5.0  # source strength
x_source, y_source = -1.0, 0.0  # location of the source

# compute the velocity field on the mesh grid
u_source = (strength_source / (2 * math.pi) * (X - x_source) /
            ((X - x_source)**2 + (Y - y_source)**2))
v_source = (strength_source / (2 * math.pi) * (Y - y_source) /
            ((X - x_source)**2 + (Y - y_source)**2))

# plot the streamlines
width = 10.0
height = (y_end - y_start) / (x_end - x_start) * width
pyplot.figure(figsize=(width, height))
pyplot.xlabel('x', fontsize=16)
pyplot.ylabel('y', fontsize=16)
pyplot.xlim(x_start, x_end)
pyplot.ylim(y_start, y_end)
pyplot.streamplot(X,
                  Y,
                  u_source,
                  v_source,
                  density=2,
                  linewidth=1,
                  arrowsize=2,
                  arrowstyle='->')
pyplot.scatter(x_source, y_source, color='#CD2305', s=80, marker='o')
コード例 #39
0
rho1 = lambda x: 2 * x
x = np.arange(-5.0, 5.0, 0.05)
y = np.arange(-5.0, 5.0, 0.05)
Xm, Ym = np.meshgrid(x, y, sparse=True)
Z = epotentialx(rho1, 0, 1, Xm, Ym)
im = plt.imshow(Z, cmap='Reds', extent=(-5, 5, -5, 5))
plt.plot([0, 1], [0, 0], c='w')
plt.colorbar(im)
plt.title("Electric potential for line charge (units of k)")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
plt.close()

U, V = np.gradient(Z)
strm = plt.streamplot(x, y, V, U, density=2, color=V, cmap='Reds')
plt.colorbar(strm.lines)
plt.title("Electric field for line charge (units of k)")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
plt.close()

# Second charge distribution
rho2x = lambda x: x**2
rho2y = lambda y: y
x = np.arange(-5.0, 5.0, 0.05)
y = np.arange(-5.0, 5.0, 0.05)
Xm, Ym = np.meshgrid(x, y, sparse=True)
Z = epotentialx(rho2x, 0, 1, Xm, Ym)
Z = Z + epotentialy(rho2y, 1, 2, Xm, Ym)
コード例 #40
0
m_dot_R = m[0] * X_unit + m[1] * Y_unit

m_dot_R.shape

#componente del CM en x y Y
B_x = const * (3 * X_unit * m_dot_R - m[0]) / r**3

B_y = const * (3 * Y_unit * m_dot_R - m[1]) / r**3

#Magnitud total del campo
mag_B = np.sqrt((B_x**2) + (B_y**2))

plt.figure(figsize=(16, 8))

#grafica de vectores
plt.subplot(1, 2, 1)
plt.quiver(x, x, B_x / mag_B, B_y / mag_B)
plt.title('Vectores Unitarios del Campo Magnético')

#grafica de lineas de campo
plt.subplot(1, 2, 2)
plt.streamplot(X, Y, B_x, B_y)
plt.title('Lineas de trayectoria del campo Magnético')

# Grafica de las dos de arriba juntas

plt.figure(figsize=(10, 10))

plt.quiver(x, x, B_x / mag_B, B_y / mag_B)
plt.streamplot(X, Y, B_x, B_y)
plt.title('Vectores Unitarios y líneas de trayectoria del Campo Magnético')
コード例 #41
0
X2 = jac[1, 0] * X + jac[1, 1] * Y

eigw, eigv = np.linalg.eig(jac)
#using tellurium to model time dependent plots
r = te.loada(
    'x\'=' + str(jac[0, 0]) + '*x+' + str(jac[0, 1]) + '*y;\n' +  #dx1/dt
    'y\'=' + str(jac[1, 0]) + '*x+' + str(jac[1, 1]) + '*y;\n' +  #dx2/dt
    'x=4;y=-4;')  #Initial Conditions
m = r.simulate(0, 8, 400)  #running the model

#making a phase plot with streamlines
plt.subplots(1, 2, figsize=(10, 4))
plt.subplot(121)
plt.xlabel('x', fontsize='16')
plt.ylabel('y', fontsize='16')
plt.streamplot(Y, X, X2, X1, density=[1, 1])
plt.ylim((-4, 4))
plt.xlim((-4, 4))
#determine system stability type
if eigw[0].imag == 0 and eigw[1].imag == 0:
    if eigw[0] > 0 and eigw[1] > 0:
        print "System Stability: Unstable System."
    elif eigw[0] < 0 and eigw[1] < 0:
        print "System Stability: Stable system."
    elif eigw[0] == 0 and eigw[1] == 0:
        print "System Stability: Constant valued system."
    else:
        print "System Stability: Saddle Point exists."
elif eigw[0].real == 0 and eigw[1].real == 0:
    print "System Stability: Center exists."
else:
コード例 #42
0
    ux += vx
    uy += vy

#projection of (ux,uy) flow vector along the normal (nx,ny) vector
projection = nx * ux + ny * uy
plt.quiver(xc,
           yc,
           projection * nx,
           projection * ny,
           scale=250,
           scale_units='xy',
           alpha=0.25)

x_ = np.linspace(-.2, 1.2, 50)
y_ = np.linspace(-.2, .2, 50)
X, Y = np.meshgrid(x_, y_)

ux = np.ones_like(X) * 20.0
uy = np.zeros_like(X)

for i, j, k in zip(vortex_x, vortex_y, vortex_i):
    R = ((X - i)**2 + (Y - j)**2)
    vx = -k * (Y - j) / R
    vy = k * (X - i) / R

    ux += vx
    uy += vy

plt.streamplot(X, Y, ux, uy)
コード例 #43
0
def test_colormap():
    X, Y, U, V = velocity_field()
    plt.streamplot(X, Y, U, V, color=U, density=0.6, linewidth=2,
                   cmap=plt.cm.autumn)
    plt.colorbar()
コード例 #44
0
def test_complete():
    fig = plt.figure('Figure with a label?', figsize=(10, 6))

    plt.suptitle('Can you fit any more in a figure?')

    # make some arbitrary data
    x, y = np.arange(8), np.arange(10)
    data = u = v = np.linspace(0, 10, 80).reshape(10, 8)
    v = np.sin(v * -0.6)

    # Ensure lists also pickle correctly.
    plt.subplot(3, 3, 1)
    plt.plot(list(range(10)))

    plt.subplot(3, 3, 2)
    plt.contourf(data, hatches=['//', 'ooo'])
    plt.colorbar()

    plt.subplot(3, 3, 3)
    plt.pcolormesh(data)

    plt.subplot(3, 3, 4)
    plt.imshow(data)

    plt.subplot(3, 3, 5)
    plt.pcolor(data)

    ax = plt.subplot(3, 3, 6)
    ax.set_xlim(0, 7)
    ax.set_ylim(0, 9)
    plt.streamplot(x, y, u, v)

    ax = plt.subplot(3, 3, 7)
    ax.set_xlim(0, 7)
    ax.set_ylim(0, 9)
    plt.quiver(x, y, u, v)

    plt.subplot(3, 3, 8)
    plt.scatter(x, x**2, label='$x^2$')
    plt.legend(loc='upper left')

    plt.subplot(3, 3, 9)
    plt.errorbar(x, x * -0.5, xerr=0.2, yerr=0.4)

    #
    # plotting is done, now test its pickle-ability
    #
    result_fh = BytesIO()
    pickle.dump(fig, result_fh, pickle.HIGHEST_PROTOCOL)

    plt.close('all')

    # make doubly sure that there are no figures left
    assert plt._pylab_helpers.Gcf.figs == {}

    # wind back the fh and load in the figure
    result_fh.seek(0)
    fig = pickle.load(result_fh)

    # make sure there is now a figure manager
    assert plt._pylab_helpers.Gcf.figs != {}

    assert fig.get_label() == 'Figure with a label?'
コード例 #45
0
    # output
    counter += 1   # increment by 1 before writing
    outFile['rho'].resize((NX,NY,counter))
    outFile['Ux'].resize((NX,NY,counter))
    outFile['Uy'].resize((NX,NY,counter))
    outFile['rho'][...,counter-1] = rho
    outFile['Ux'][...,counter-1] = u[0,...]
    outFile['Uy'][...,counter-1] = u[1,...]
    # outFile['Uy'][...,counter-1] = rho

    # Plot solution every NVIS time steps
    if vis and t % NVIS == 0:
        umag = np.sqrt( np.einsum('axy->xy', u*u) ) / u_max
        plt.imshow(umag, extent=[0,1,0,1], vmin=0, vmax=1)
        bar = plt.colorbar()
        plt.streamplot(x/NX, y/NY, u[0,:,:], u[1,:,:], color=[1,1,1])
        plt.xlabel('$x/l_x$')
        plt.ylabel('$y/l_y$')
        bar.set_label('$|\mathbf{u}|/u_\mathrm{max}$')
        td = 1/(nu*(2*np.pi/NX)**2 + (2*np.pi/NY)**2)
        plt.title('flow field at $t/t_d = {0:.2f}$'.format(t/td))
        plt.show()




# Calculate performance information after the simulation is finished
runtime = time.time() - tstart
nodes_updated = NSTEPS*NX*NY
speed = nodes_updated/(1e6*runtime)
outFile.close()
コード例 #46
0
import numpy as np
import matplotlib.pyplot as plt

v1 = [0, 0, 1]

l = 0.0405
dl = 0.005
n = int(l * 2 / dl) + 1
x = [-l + i * dl for i in range(n)]
y = [-l + i * dl for i in range(n)]
u = [[0 for j in range(n)] for i in range(n)]
v = [[0 for j in range(n)] for i in range(n)]

for i in range(n):
    for j in range(n):
        v2 = [x[j], y[i], 0]
        b = np.cross(v1, v2)  #計算v1,v2之外積
        u[i][j] = b[0]
        v[i][j] = b[1]

plt.streamplot(np.array(x), np.array(y), np.array(u), np.array(v))
plt.axis([-l, l, -l, l])  #用以限制繪圖範圍 與xlim,ylim功能相當,但實際使用時可能會有些許差別
plt.show()

plt.quiver(x, y, u, v, color='b',
           width=0.005)  #包含方向與大小之向量圖,color可調整顏色,width調整箭頭寬度
plt.axis([-l, l, -l, l])
plt.show()
コード例 #47
0
ファイル: stratsi_plot.py プロジェクト: minkailin/stratsi
cp = plt.contourf(xaxis, zaxis, data, levels, cmap=cmap)

xfac = np.int(nx/64)
zfac = np.int(nz/128)

#plt.quiver(xaxis[0:nx:xfac], zaxis[0:nz:zfac], U[0:nz:zfac,0:nx:xfac],
#               V[0:nz:zfac,0:nx:xfac], color='deepskyblue',
#               width=0.005, scale=0.2
#               )

speed = np.sqrt(U**2 + V**2)
lw    = 0.7#2*speed/speed.max()

plt.streamplot(xaxis, zaxis, U, V, 
               color='deepskyblue', density=3, 
               linewidth=lw
               )

#plt.gca().set_aspect("equal")
#plt.tight_layout()
plt.subplots_adjust(left=0.2, right=0.9, top=0.9, bottom=0.125)

plt.colorbar(cp,ticks=clevels,format='%.2f')

title=r"$k_xH_g$={0:3.0f}".format(kx)+r", s={0:4.2f}$\Omega$".format(sgrow)
plt.title(title,weight='bold')

plt.xticks(fontsize=fontsize,weight='bold')
plt.xlabel(r'$x/H_g$',fontsize=fontsize)

plt.yticks(fontsize=fontsize,weight='bold')
コード例 #48
0
# Para cada uma das linhas...
for p in range(len(ps)):
    # p1 posição da linha.
    p1 = ps[p]

    # I direção da corrente.
    I = [0, 0, correntes[p]]

    # Iteração espacial no domínio criado.
    for i in range(ns):
        y = domain[i]
        for j in range(ns):
            x = domain[j]
            # Vetor para o ponto atual sendo calculado.
            p2 = array([x, y, 0])
            # Biot-Savart
            H = cross(I, p1 - p2) / (4.0 * pi * (vmod(p1, p2)**3.0))
            # Atribui as componentes para o ponto calculado.
            Hx[i, j] += H[0]
            Hy[i, j] += H[1]

# Calcula o módulo do campo.
H = sqrt(Hx**2 + Hy**2)

# Plota as linhas equipotenciais.
plt.contourf(X, Y, H, 15, cmap="rainbow", alpha=.4)
plt.colorbar(format="%.2f A/m")
# Plota as linhas de campo.
plt.streamplot(X, Y, Hx, Hy, color=H, density=2)
plt.grid(True)
コード例 #49
0
for i in range(len(x)):
	x[i, :] = a*eta

for i in range(len(T)):
	plt.clf()
	# Interpolate using three different methods and plot
	ux = griddata( (x.flatten(),  y.flatten()), u[0,:,:,i].flatten(), (X, Y), method='nearest')
	uy = griddata( (x.flatten(),  y.flatten()), u[1,:,:,i].flatten(), (X, Y), method='nearest')
	ux = ux*epsilon*epsilon 
	uy = uy*epsilon*epsilon
	speed = np.sqrt(np.square(ux) + np.square(uy))

	ux[np.where(np.abs(uy)<1e-5)] = 0
	uy[np.where(np.abs(uy)<1e-5)] = 0

	plt.streamplot(X, Y, ux, uy, density=0.6, color='k')
	CS = plt.contourf(X, Y, speed, levels=np.linspace(0, 1.1, 40))
	cbar = plt.colorbar(CS)
	plt.xlabel(r"Horizontal position $\eta$ $[\kappa^{-1}]$", fontsize=12)
	plt.ylabel(r"Vertical position   $\xi$ ", fontsize=12)
	plt.plot(x[0,:], y[0, :], "k", linewidth=3)
	plt.plot(x[0,:], y[-1,:], "k", linewidth=3)
	plt.fill_between(x[0,:], (-1-epsilon)*np.ones(len(x[0,:])), y[0,:], color="k")
	plt.fill_between(x[0,:], ( 1+epsilon)*np.ones(len(x[0,:])), -y[0,:], color="k")
	plt.draw()
	plt.axis([min(eta), max(eta), -1-epsilon-0.05, 1+epsilon+0.05])
	plt.pause(0.5)
	plt.savefig("figures/streamplot_u2_nr"+str(i)+".pdf")
plt.show()
saves = [6, 16, 43, 57, 58, 59]

fig = plt.figure(4)
for i in range(frames):
    plt.clf()
    u = np.array(list(h5py.File(name, 'r')["VisualisationVector"][str(int(N-skip*i))])) 
    # Interpolate uneven grid onto an even grid

    ux_grid  = np.roll(griddata((geometry[::s,0], geometry[::s,1]), u[::s,0], (X, Y), method='cubic'), 0, axis=1)
    uy_grid  = np.roll(griddata((geometry[::s,0], geometry[::s,1]), u[::s,1], (X, Y), method='cubic'), 0, axis=1)

    x_, y_ = np.meshgrid(kappa, epsilon)
    ax1 = plt.contourf(X,Y, np.sqrt(np.square(ux_grid) + np.square(uy_grid)), cmap=Map, levels=15)
    cbar = fig.colorbar(ax1, format='%1.0f')
    #plt.quiver(x[::s], y[::s], ux_grid[::s, ::s], uy_grid[::s, ::s])
    plt.streamplot(X, Y, ux_grid, uy_grid, color='k',  density=3.25, start_points=stream_points )
    plt.streamplot(X, Y, ux_grid, uy_grid, color='k',  density=3.25, start_points=stream_points2 )
    plt.streamplot(X, Y, ux_grid, uy_grid, color='k',  density=0.75)

    plt.fill_between(x,  1+epsilon*np.ones(len(x)), +1+epsilon*np.cos(kappa*x), color="k")
    plt.fill_between(x, -1-epsilon*np.ones(len(x)), -1-epsilon*np.cos(kappa*x), color="k")
    cbar.ax.set_ylabel(r'Velocity $u$', fontsize=8)
    plt.ylabel(r"Vertical position $y$ [$a$]",    fontsize=8)
    plt.xlabel(r"Horizontal position $x$ [$a$]",    fontsize=8)
    plt.tick_params(axis='both', which='major', labelsize=8)
    plt.tick_params(axis='both', which='minor', labelsize=8)
    plt.axis([0, 6.18, -1.4, 1.4])
    #time = ( ( (t[N-skip*i]-t[N])*omega ) % 2*np.pi )/(2*np.pi)
    #plt.title(str(int(i)))
    #plt.title(r"$t=$ %2.2f $2\pi$ [$\omega$]" % time, fontsize=8)
    #plt.axis("equal")
コード例 #51
0
def plot_traj_vf_1D(model,
                    s_span,
                    traj,
                    device,
                    x_span,
                    n_grid,
                    n_levels=30,
                    contour_alpha=0.7,
                    cmap='winter',
                    traj_color='orange',
                    traj_alpha=0.1):
    """Plots 1D data flows.
    
     :param model: model
     :type model: nn.Module
     :param s_span: number of data flows to visualize
     :type s_span: torch.Tensor
     :param traj: figure size
     :type traj: tuple(int, int)
     :param device: alpha of figure
     :type device: float
     :param x_span: alpha of figure
     :type x_span: float
     :param n_grid: alpha of figure
     :type n_grid: float
     """
    ss = torch.linspace(s_span[0], s_span[-1], n_grid)
    xx = torch.linspace(x_span[0], x_span[-1], n_grid)

    S, X = torch.meshgrid(ss, xx)

    if model.settings['controlled']:
        ax = st['ax']
        u_traj = traj[0, :, 0].repeat(traj.shape[1], 1)
        e = torch.abs(st['y'].T - traj[:, :, 0])
        color = plt.cm.coolwarm(e)
        for i in range(traj.shape[1]):
            tr = ax.scatter(s_span,
                            u_traj[:, i],
                            traj[:, i, 0],
                            c=color[:, i],
                            alpha=1,
                            cmap=color[:, i],
                            zdir='z')
        norm = mpl.colors.Normalize(e.min(), e.max())
        plt.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap='coolwarm'),
                     label='Approximation Error',
                     orientation='horizontal')
        ax.set_xlabel(r"$s$ [depth]")
        ax.set_ylabel(r"$u$")
        ax.set_zlabel(r"$h(s)$")
        # make the panes transparent
        ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
        ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
        ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
        # make the grid lines transparent
        ax.xaxis._axinfo["grid"]['color'] = (1, 1, 1, 0)
        ax.yaxis._axinfo["grid"]['color'] = (1, 1, 1, 0)
        ax.zaxis._axinfo["grid"]['color'] = (1, 1, 1, 0)

    else:
        U, V = torch.ones(n_grid, n_grid), torch.zeros(n_grid, n_grid)
        for i in range(n_grid):
            for j in range(n_grid):
                V[i, j] = model.defunc(S[i, j].reshape(1, -1).to(device),
                                       X[i, j].reshape(
                                           1, -1).to(device)).detach().cpu()
        F = torch.sqrt(U**2 + V**2)

        plt.contourf(S, X, F, n_levels, cmap=cmap, alpha=contour_alpha)
        plt.streamplot(S.T.numpy(),
                       X.T.numpy(),
                       U.T.numpy(),
                       V.T.numpy(),
                       color='black',
                       linewidth=1)
        if not traj == None:
            plt.plot(s_span, traj[:, :, 0], color=traj_color, alpha=traj_alpha)

        plt.xlabel(r"$s$ [Depth]")
        plt.ylabel(r"$h(s)$")

        return (S, X, U, V)
コード例 #52
0
    div()
    phi = ResoLpl(divstar,N,M)
    
    # Troisieme etape
    grad()
    u = ustar - gradphix
    v = vstar - gradphiy     
    
    if (niter%10 == 0):
        print "iteration: %d" %niter
        plotlabel = "t = %1.2f" %(niter * dt)
        plt.pcolormesh(xx,yy,color,shading='flat')
        plt.clim(0,0.5)
        plt.contour(xx,yy,Fe,hold=True,colors='b')
        plt.title(plotlabel)
        plt.axis('image')
#        plt.savefig('image%d.png' %(niter/10))
        plt.draw() 
        if 'qt' in plt.get_backend().lower():
            QtGui.qApp.processEvents()


plt.figure()
u*=Fe
v*=Fe
plt.streamplot(xx,yy,u,v,color='k')
plt.contour(xx,yy,Fe,hold=True,colors='b')
plt.axis('image')
#plt.savefig('stream%d.png' %(niter/10))
plt.show()
コード例 #53
0
# Streamline starting points
numSL = 50  # Number of streamlines
Xsl = -10 * np.ones(numSL)  # Streamline starting X coordinates
Ysl = np.linspace(-10, 10, numSL)  # Streamline starting Y coordinates
XYsl = np.vstack(
    (Xsl.T, Ysl.T)).T  # Concatenate X and Y streamline starting points

# Plot quiver and streamlines
fig = plt.figure(1)  # Create figure
plt.cla()  # Get ready for plotting
plt.quiver(X, Y, Vx, Vy)  # Plot velocity vectors
plt.streamplot(XX,
               YY,
               Vx,
               Vy,
               linewidth=0.5,
               density=10,
               color='r',
               arrowstyle='-',
               start_points=XYsl)  # Plot streamlines
plt.plot(xC, yC, 'b-')  # Plot ellipse
plt.title('Uniform + Source/Sink Flow')  # Set title
plt.xlabel('X-Axis')  # Set X-label
plt.ylabel('Y-Axis')  # Set Y-label
plt.xlim([-6, 6])  # Set X-limits
plt.ylim([-6, 6])  # Set Y-limits
plt.gca().set_aspect('equal')  # Set axes equal
plt.show()  # Display plot

## Save the figure
#saveFlnm = 'Uniform_Source_Flow'
コード例 #54
0
Ex, Ey = E(x, y)[0], E(x, y)[1]

u, v = Ex / np.hypot(Ex, Ey), Ey / np.hypot(Ex, Ey)

plt.figure(1)
plt.title('Interazione dipo fisso-dipolo mobile', fontsize=20)
plt.xlabel('asse x', fontsize=10)
plt.ylabel('asse y', fontsize=10)
plt.plot(xp, yp, "r", label='traiettoria')
plt.errorbar(0, 0, fmt="^", markersize=6)
plt.streamplot(x,
               y,
               u,
               v,
               color="blue",
               density=2.5,
               linewidth=0.3,
               arrowstyle='->',
               arrowsize=1)
plt.legend(loc='best')

plt.figure(2)
plt.errorbar(tp, op, fmt='.', markersize=0.7, color='blue', label='angolo')
plt.errorbar(tp,
             wp,
             fmt='.',
             markersize=0.7,
             color='black',
             label='velocità angolare')
plt.errorbar(tp,
コード例 #55
0
#    precision=0.1,
#    valeur_defaut=0)
#
#for i in range(treillis.nombre_lignes):
#    for j in range(treillis.nombre_colonnes):
#        treillis[base.Case(i, j)] = random.random()

SIZE = 5 * 10**2

x = np.linspace(treillis.position.x + 2 * treillis.precision,
                treillis.position.x + treillis.largeur -
                2 * treillis.precision,
                num=SIZE)

y = np.linspace(treillis.position.y + 2 * treillis.precision,
                treillis.position.y + treillis.hauteur -
                2 * treillis.precision,
                num=SIZE)

X, Y = np.meshgrid(x, y)
z_x = np.zeros((SIZE, SIZE))
z_y = np.zeros((SIZE, SIZE))

for i in range(SIZE):
    for j in range(SIZE):
        z_x[i, j], z_y[i, j] = treillis.avoirGradientParInterpolationBicubic(
            Vec2d(X[i, j], Y[i, j]))

plt.streamplot(x, y, z_x, z_y)
plt.show()
コード例 #56
0
    x' = 1*x + 2*y;
    y' = -2*x - 1*y;
    
    x = -0.3; y = -0.1;
''')

m = r.simulate (0, 25, 200)

U =  1*X + 2*Y
V = -2*X - 1*Y

plt.subplots(1,2, figsize=(10,4))
plt.subplot(121)
plt.xlabel('x', fontsize='16')
plt.ylabel('y', fontsize='16')
plt.streamplot(X, Y, U, V, density=[1, 1])

plt.ylim((-4,4))
plt.xlim((-4,4))

plt.axhline(0, color='black')
plt.axvline(0, color='black')

plt.subplot(122)

plt.ylim((-1,1))
plt.xlim((0,25))
plt.xlabel('Time', fontsize='13')


plt.plot (m[:,0], m[:,1], color='r', linewidth=2, label='x')
コード例 #57
0
ファイル: CP_Graph_streamplot.py プロジェクト: MinTTT/pycode
import numpy as np
import matplotlib.pyplot as plt

Y, X = np.mgrid[0:1:10j, 0:1:10j]
U = Y - X
V = (1 / (1 + X)) - Y
speed = np.sqrt(U * U + V * V)

Protein = np.arange(0, 1, 0.05)

Y_1 = Protein
Y_2 = (1 / (1 + Protein))

plt.figure(figsize=(9, 8))
#  Varying density along a streamline
streamline = plt.streamplot(X,
                            Y,
                            U,
                            V,
                            density=[3, 3],
                            color=U,
                            cmap='coolwarm')
plt.colorbar(streamline.lines)
plt.plot(Protein, Y_1)
plt.plot(Protein, Y_2)
plt.xlim(0, 1)
plt.show()
コード例 #58
0
def test_direction():
    x, y, U, V = swirl_velocity_field()
    plt.streamplot(x, y, U, V, integration_direction='backward',
                   maxlength=1.5, start_points=[[1.5, 0.]],
                   linewidth=2, density=2)
コード例 #59
0
ファイル: vector.py プロジェクト: xela144/testplots
A streamplot, or streamline plot, is used to display 2D vector fields. This
example shows a few features of the stream plot function:

    * Varying the color along a streamline.
    * Varying the density of streamlines.
    * Varying the line width along a stream line.
"""
import numpy as np
import matplotlib.pyplot as plt

Y, X = np.mgrid[-10:10:100j, -10:10:100j]

U = Y
V = -X

#U = -1 - X**2 + Y
#V = 1 + X - Y**2
speed = np.sqrt(U * U + V * V)

plt.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)
plt.colorbar()

f, (ax1, ax2) = plt.subplots(ncols=2)
ax1.streamplot(X, Y, U, V, density=[0.5, 1])

lw = 5 * speed / speed.max()
ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)

plt.show()
コード例 #60
0
ファイル: plots.py プロジェクト: bperry65/mae557
x = np.linspace(0, 1, nx)
y = x
xx, yy = np.meshgrid(x, y)

unit = 0

plt.figure()
plot2 = plt.contourf(xx, yy, U[unit], 50)
plt.colorbar(plot2)
plt.axis([0, 1, 0, 1])
plt.savefig('contour-U.png')

plt.figure()
plot2 = plt.contourf(xx, yy, V[unit], 50)
plt.colorbar(plot2)
plt.axis([0, 1, 0, 1])
plt.savefig('contour-V.png')

plt.figure()
plot2 = plt.contourf(xx, yy, P[unit], 50)
plt.colorbar(plot2)
plt.axis([0, 1, 0, 1])
plt.savefig('contour-P.png')

plt.figure()
plot1 = plt.streamplot(xx, yy, U[unit], V[unit], color=vel[unit])
plt.colorbar(plot2)
plt.axis([0, 1, 0, 1])
plt.savefig('streamplot.png')