def plotmesh(self, **how): """ Draw a plot of the mesh. Inner edges in blue lines. Boundary edges in magenta lines. Centers as circles. Vertices as squares. x_sigma as x. nKs as arrows. """ ax = plt.gca() ax.set_xlim( (1.1 * self.mx - 0.1 * self.Mx, -0.1 * self.mx + 1.1 * self.Mx)) ax.set_ylim( (1.1 * self.my - 0.1 * self.My, -0.1 * self.my + 1.1 * self.My)) ax.set_aspect('equal') s_i = self.vert[self.inner] s_b = self.vert[self.bnd] X_i = np.stack((s_i[0, :, 0], s_i[1, :, 0])) Y_i = np.stack((s_i[0, :, 1], s_i[1, :, 1])) X_b = np.stack((s_b[0, :, 0], s_b[1, :, 0])) Y_b = np.stack((s_b[0, :, 1], s_b[1, :, 1])) plt.plot(X_i, Y_i, '-b') plt.plot(X_b, Y_b, '-m') plt.plot(self.vert[:, 0], self.vert[:, 1], 's', **how) plt.plot(self.centres[:, 0], self.centres[:, 1], 'go', **how) plt.plot(self.xs_b[:, 0], self.xs_b[:, 1], 'rx', **how) plt.plot(self.xs_i[:, 0], self.xs_i[:, 1], 'rx', **how) plt.quiver(self.xs_i[:, 0], self.xs_i[:, 1], self.nKs_i[:, 0], self.nKs_i[:, 1]) plt.quiver(self.xs_b[:, 0], self.xs_b[:, 1], self.nKs_b[:, 0], self.nKs_b[:, 1])
def main(): F, I = ag.io.load_example('two-faces') t1 = time() imdef, info = ag.stats.image_deformation(F, I, penalty=0.1, rho=2.0, last_level=3, tol=0.00001, maxiter=100, \ start_level=1, wavelet='db8', debug_plot=False) t2 = time() Fdef = imdef.deform(F) print "Time:", t2 - t1 print "Cost:", info['cost'] x, y = imdef.meshgrid() Ux, Uy = imdef.deform_map(x, y) for i in range(Ux.shape[0]): for j in range(Ux.shape[1]): print Ux[i, j], Uy[i, j] print 'mins', Ux.min(), Uy.min() print 'maxs', Ux.max(), Uy.max() import matplotlib.pylab as plt plt.quiver(x, y, Ux, Uy) #, Ux, Uy) plt.show() PLOT = False if PLOT: import matplotlib.pylab as plt ag.plot.deformation(F, I, imdef)
def main(): F, I = ag.io.load_example('two-faces') t1 = time() imdef, info = ag.stats.image_deformation(F, I, penalty=0.1, rho=2.0, last_level=3, tol=0.00001, maxiter=100, \ start_level=1, wavelet='db8', debug_plot=False) t2 = time() Fdef = imdef.deform(F) print "Time:", t2-t1 print "Cost:", info['cost'] x, y = imdef.meshgrid() Ux, Uy = imdef.deform_map(x, y) for i in range(Ux.shape[0]): for j in range(Ux.shape[1]): print Ux[i,j], Uy[i,j] print 'mins', Ux.min(), Uy.min() print 'maxs', Ux.max(), Uy.max() import matplotlib.pylab as plt plt.quiver(x, y, Ux, Uy)#, Ux, Uy) plt.show() PLOT = False if PLOT: import matplotlib.pylab as plt ag.plot.deformation(F, I, imdef)
def plot_electric_field(self,sp=10,scales = 500000,cont_scale=90,savefigs = False): fig = plt.figure(figsize=(7.0, 7.0)) xplot = self.x*1e6 yplot = self.y*1e6 X,Y = np.meshgrid(xplot,yplot) try: plt.contourf(X,Y,self.mode_field,cont_scale) except AttributeError: raise NotImplementedError("interpolate before plotting") plt.quiver(X[::sp,::sp], Y[::sp,::sp], np.real(self.E[::sp,::sp,0]), np.real(self.E[::sp,::sp,1]),scale = scales,headlength=7) plt.xlabel(r'$x(\mu m)$') plt.ylabel(r'$y(\mu m)$') #plt.title(r'mode$=$'+str(self.mode)+', '+' $n_{eff}=$'+str(self.neff.real)+str(self.neff.imag)+'j') if savefigs == True: plt.savefig('mode'+str(self.mode)+'.eps',bbox_inches ='tight') D = {} D['X'] = X D['Y'] = Y D['Z'] = self.mode_field D['u'] = np.real(self.E[::sp,::sp,0]) D['v'] = np.real(self.E[::sp,::sp,1]) D['scale'] = scales D['cont_scale'] = 90 D['sp'] = sp savemat('mode'+str(self.mode)+'.mat',D) return None
def plot_field(self,x,y,u=None,v=None,F=None,contour=False,outdir=None,plot='quiver',figname='_field',format='eps'): outdir = self.set_dir(outdir) p = 64 if F is None: F=self.calc_F(u,v) plt.close('all') plt.figure() #fig, axes = plt.subplots(nrows=1) if contour: plt.hold(True) plt.contourf(x,y,F) if plot=='quiver': plt.quiver(x[::p],y[::p],u[::p],v[::p],scale=0.1) if plot=='pcolor': plt.pcolormesh(x[::4],y[::4],F[::4],cmap=plt.cm.Pastel1) plt.colorbar() if plot=='stream': speed = F[::16] plt.streamplot(x[::16], y[::16], u[::16], v[::16], density=(1,1),color='k') plt.xlabel('$x$ (a.u.)') plt.ylabel('$y$ (a.u.)') plt.savefig(os.path.join(outdir,figname+'.'+format),format=format,dpi=320,bbox_inches='tight') plt.close()
def handle_2d_plot( embedding, kind, color=None, xlabel=None, ylabel=None, title=None, show_operations=False, annot=True, axis_option=None, ): """ Handles the logic to perform a 2d plot in matplotlib. **Input** - embedding.md: a `whatlies.Embedding` object to plot - kind: what kind of plot to make, can be `scatter`, `arrow` or `text` - color: the color to apply, only works for `scatter` and `arrow` - xlabel: manually override the xlabel - ylabel: manually override the ylabel - title: optional title used for the plot - show_operations: setting to also show the applied operations, only works for `text` - axis_option: a string which is passed to `matplotlib.pyplot.axis` function. """ if not isinstance(embedding, list): # It's a single Embedding instance embedding = [embedding] vectors = np.array([e.vector for e in embedding]) names = [e.name if show_operations else e.orig for e in embedding] if kind == "scatter": if color is None: color = "steelblue" plt.scatter(vectors[:, 0], vectors[:, 1], c=color) if kind == "arrow": plt.scatter(vectors[:, 0], vectors[:, 1], c="white", s=0.01) plt.quiver( np.zeros_like(vectors[:, 0]), np.zeros_like(vectors[:, 1]), vectors[:, 0], vectors[:, 1], color=color, angles="xy", scale_units="xy", scale=1, ) if (kind == "text") or annot: for vec, name in zip(vectors, names): plt.text(vec[0] + 0.01, vec[1], name) plt.xlabel("x" if xlabel is None else xlabel) plt.ylabel("y" if ylabel is None else ylabel) if title is not None: plt.title(title) if axis_option is not None: plt.axis(axis_option)
def visualize_momentum(m, step=5): m = m.__array__() u = m[0, 0:-1:step, 0:-1:step] v = m[1, 0:-1:step, 0:-1:step] x = np.linspace(0, 1, u.shape[0]) y = np.linspace(0, 1, u.shape[1]) plt.quiver(x, y, u, v, scale=1)
def potential(x_axis, y_axis, cbar, x_label, y_label, cbar_label, int_pol, colorMap, xmin=None, xmax=None, ymin=None, ymax=None, plot=None): """A general plotter allowing for the plotting of a heatmap(primarily used here for potential function) which takes in relevant data about the graph. It also allows for the option of overlaying either a quiver or a streamline plot, or not! Parameters: x_axis, y_axis : The corresponding x and y axis data lists of a plot cbar: The heatmap list data which usually corresponds to x and y axis x_label, y_label, : The x, y and z label of the graph dtype = string cbar_label : The colourbar label dtype = string int_pol: The colour interpolation of the heatmap dtype = integer colorMap: The style and colour of heatmap dtype = string xmin, xmax: The minimum and maximum value of the x-axis ymin, ymax: The minimum and maximum value of the y-axis plot: "quiver", "stream" allowing for the overlay of quiver or streamline plot Returns: Image : AxesImage """ plt.contourf(x_axis, y_axis, cbar, int_pol, cmap=colorMap) cbar_tag = plt.colorbar() Z = cbar plt.xlabel(x_label) plt.ylabel(y_label) cbar_tag.set_label(cbar_label, rotation=270) cbar_tag.set_clim(-1000.0, 1000.0) E = np.gradient(Z) E = E / np.sqrt(E[0]**2 + E[1]**2) if plot is not None: if plot == "quiver": print("\nQuiver plot:") plt.quiver(x_axis, y_axis, E[1], E[0]) if plot == "stream": print("\nStreamline Plot:") plt.streamplot(x_axis, y_axis, -E[1], -E[0], color='black') if xmin is not None and xmax is not None: plt.xlim(xmin, xmax) if ymin is not None and ymax is not None: plt.ylim(ymin, ymax) plt.show()
def pltShow2d(X, Y, grad): plt.figure() plt.quiver(X, Y, -grad[0], -grad[1], angles="xy", color="#666666") #,headwidth=10,scale=40,color="#444444") plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.xlabel('x0') plt.ylabel('x1') plt.grid() plt.legend() plt.draw() plt.show()
def deformation(F, I, displacement_field, show_diff=False, show=True): """ Plot how a :class:`DisplacementField` applies to a prototype image `F` to qualitatively compare it with `I`. Especially designed to plot the results of :func:`image_deformation`. Parameters ---------- F : ndarray Prototype image. I : ndarray Data image. This is included for comparison. displacement_field : DisplacementField A displacement field that will be applied to `F` and also plotted by itself. show_diff : bool If True, displays the difference map instead of the vector field. show : bool Call `pylab.show()` inside the function. """ import matplotlib.pylab as plt assert isinstance(displacement_field, ag.util.DisplacementField) x, y = displacement_field.meshgrid() Ux, Uy = displacement_field.deform_map(x, y) Fdef = displacement_field.deform(F) d = dict(interpolation='nearest', cmap=plt.cm.gray) plt.figure(figsize=(7, 7)) plt.subplot(221) plt.title("Prototype") plt.imshow(F, **d) plt.subplot(222) plt.title("Data image") plt.imshow(I, **d) plt.subplot(223) plt.title("Deformed prototype") plt.imshow(Fdef, **d) plt.subplot(224) if show_diff: plt.title("Difference") plt.imshow(Fdef - I, interpolation='nearest') plt.colorbar() else: plt.title("Displacement field") plt.quiver(np.asarray(y), np.asarray(-x), np.asarray(Uy), np.asarray(-Ux), linewidth=2.0) if show: plt.show()
def plot_current(GLORYS_path, numday): """ """ # Read data. U_cur, V_cur, xu, xv, yu, yv = read_current(GLORYS_path, numday) # Interpolate V over U grid : V_interp = np.zeros(np.shape(V_cur)) for i in range(np.shape(V_interp)[0]): for j in range(np.shape(V_interp)[1]): V_interp[i, j] = interpolate_var(V_cur, xv, yv, xu[i], yu[j]) xu, U_cur = shift_lon(xu, U_cur) xv, V_interp = shift_lon(xv, V_interp) pl.quiver(xu, yu, U_cur, V_interp) pl.show()
def __call__(self, **params): p = ParamOverrides(self, params) name = p.plot_template.keys().pop(0) plot = make_template_plot(p.plot_template, p.sheet.views.Maps, p.sheet.xdensity, p.sheet.bounds, p.normalize, name=p.plot_template[name]) fig = plt.figure(figsize=(5, 5)) if plot: bitmap = plot.bitmap isint = plt.isinteractive( ) # Temporarily make non-interactive for plotting plt.ioff() # Turn interactive mode off plt.imshow(bitmap.image, origin='lower', interpolation='nearest') plt.axis('off') for (t, pref, sel, c) in p.overlay: v = plt.flipud(p.sheet.views.Maps[pref].view()[0]) if (t == 'contours'): plt.contour(v, [sel, sel], colors=c, linewidths=2) if (t == 'arrows'): s = plt.flipud(p.sheet.views.Maps[sel].view()[0]) scale = int(np.ceil(np.log10(len(v)))) X = np.array([x for x in xrange(len(v) / scale)]) v_sc = np.zeros((len(v) / scale, len(v) / scale)) s_sc = np.zeros((len(v) / scale, len(v) / scale)) for i in X: for j in X: v_sc[i][j] = v[scale * i][scale * j] s_sc[i][j] = s[scale * i][scale * j] plt.quiver(scale * X, scale * X, -np.cos(2 * np.pi * v_sc) * s_sc, -np.sin(2 * np.pi * v_sc) * s_sc, color=c, edgecolors=c, minshaft=3, linewidths=1) p.title = '%s overlaid with %s at time %s' % (plot.name, pref, topo.sim.timestr()) if isint: plt.ion() p.filename_suffix = "_" + p.sheet.name self._generate_figure(p) return fig
def deformation(F, I, displacement_field, show_diff=False, show=True): """ Plot how a :class:`DisplacementField` applies to a prototype image `F` to qualitatively compare it with `I`. Especially designed to plot the results of :func:`image_deformation`. Parameters ---------- F : ndarray Prototype image. I : ndarray Data image. This is included for comparison. displacement_field : DisplacementField A displacement field that will be applied to `F` and also plotted by itself. show_diff : bool If True, displays the difference map instead of the vector field. show : bool Call `pylab.show()` inside the function. """ import matplotlib.pylab as plt assert isinstance(displacement_field, ag.util.DisplacementField) x, y = displacement_field.meshgrid() Ux, Uy = displacement_field.deform_map(x, y) Fdef = displacement_field.deform(F) d = dict(interpolation='nearest', cmap=plt.cm.gray) plt.figure(figsize=(7,7)) plt.subplot(221) plt.title("Prototype") plt.imshow(F, **d) plt.subplot(222) plt.title("Data image") plt.imshow(I, **d) plt.subplot(223) plt.title("Deformed prototype") plt.imshow(Fdef, **d) plt.subplot(224) if show_diff: plt.title("Difference") plt.imshow(Fdef - I, interpolation='nearest') plt.colorbar() else: plt.title("Displacement field") plt.quiver(np.asarray(y), np.asarray(-x), np.asarray(Uy), np.asarray(-Ux), linewidth=2.0) if show: plt.show()
def direction_field(): # get axis limits ymax = plt.ylim(ymin=0)[1] xmax = plt.xlim(xmin=0)[1] nb_points = 30 x = np.linspace(0, xmax, nb_points) y = np.linspace(0, ymax, nb_points) # create a grid with the axis limits X, Y = np.meshgrid(x, y) # compute growth rate on the grid U = 1 V = dp_dt(Y, A, K) # to synchronize the scale of grid between solution plot ft_increase, ft_derease and direction fields # otherwise, the direction of arrows do not look to be tangential to the solution plot. V = V * xmax / ymax # norm of logistics M = np.sqrt(U**2 + V**2, dtype=np.float64) # avoid zero division errors M[M == 0] = 1. # normalize each arrow U /= M V /= M # plot the direction field for the range of parameters # define a grid and compute direction at each point Q = plt.quiver(X, Y, U, V, M, pivot='mid', cmap=plt.cm.jet)
def plot_neuron_arrows(self, colorrange=[0, 2],visualize=False): """ Plot arrows from each neuron center and color with strength """ best_actions = np.argmax(self.weights_, 2) action_strength = np.max(self.weights_, 2) dX = np.cos(2 * np.pi / 8 * best_actions) dY = np.sin(2 * np.pi / 8 * best_actions) plt.figure(figsize=(5.5, 5.5)) plt.subplot(aspect='equal') arrows = plt.quiver(self.centers_[0], self.centers_[1], dX, dY, action_strength, scale=10, headwidth=5, cmap='autumn_r', clim=colorrange) if visualize: positions = np.array(self.pos_history_) plt.plot(positions[:, 0], positions[:, 1], 'ko-', alpha=0.2,markersize=5) plt.xlim(-0.05, 1.05) plt.ylim(-0.05, 1.05) self._plot_dots() from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", "5%", pad="3%") cbar = plt.colorbar(arrows, cax=cax) cbar.ax.set_ylabel('highest weight value') plt.tight_layout() plt.draw()
def gradient_descent(f, init_x, lr=0.01, step_num=100): x = init_x x_history = [] for i in range(step_num): x_history.append(x.copy()) grad = numerical_gradient(f, x) plt.quiver(x[0], x[1], -grad[0], -grad[1], angles="xy", color="#666666") x -= lr * grad return x, np.array(x_history)
def vector_field2d(barycenters, vector_field, N, figure=None): dn = 1. / N N = complex(0, N) xmin, xmax = barycenters[:, 0].min(), barycenters[:, 0].max() ymin, ymax = barycenters[:, 1].min(), barycenters[:, 1].max() vector_field *= dn / sqrt((vector_field ** 2).sum(1).max()) grid = mgrid[xmin + dn*(xmax-xmin):xmax:N, ymin + dn*(ymax-ymin):ymax:N] z1 = [griddata(barycenters, z0, grid.transpose((1,2,0)), method='linear') for z0 in vector_field.T] from matplotlib import pylab X, Y = grid VX, VY = z1 if figure == None: fig = pylab.figure(figsize=(10,10)) pylab.quiver(X, Y, VX, VY, sqrt(VX ** 2 + VY ** 2), scale=1, figure=figure) pylab.axis([xmin, xmax, ymin, ymax])
def plot_quiver(self, n): """ Plot the curve and the vector field at a particular timestep """ self.new_figure() x,y = self.split_array(self.Q[n]) u,v = self.split_array(self.U[n]) mag = [np.sqrt(u[i]**2+v[i]**2) for i in xrange(np.size(u))] norm = plt.normalize(np.min(mag), np.max(mag)) C = [plt.cm.jet(norm(m)) for m in mag] plt.plot(x,y) plt.quiver(x,y,-u,-v,color=C) #plt.plot(*self.split_array(self.qA),color='grey',ls=':') plt.plot(*self.split_array(self.qB),color='grey',ls=':')
def handle_2d_plot( embedding, kind, color=None, xlabel=None, ylabel=None, show_operations=False, annot=False, ): """ Handles the logic to perform a 2d plot in matplotlib. **Input** - embedding.md: a `whatlies.Embedding` object to plot - kind: what kind of plot to make, can be `scatter`, `arrow` or `text` - color: the color to apply, only works for `scatter` and `arrow` - xlabel: manually override the xlabel - ylabel: manually override the ylabel - show_operations: setting to also show the applied operations, only works for `text` """ name = embedding.name if show_operations else embedding.orig if kind == "scatter": if color is None: color = "steelblue" plt.scatter([embedding.vector[0]], [embedding.vector[1]], c=color) if kind == "arrow": plt.scatter([embedding.vector[0]], [embedding.vector[1]], c="white", s=0.01) plt.quiver( [0], [0], [embedding.vector[0]], [embedding.vector[1]], color=color, angles="xy", scale_units="xy", scale=1, ) plt.text(embedding.vector[0] + 0.01, embedding.vector[1], name) if (kind == "text") or annot: plt.text(embedding.vector[0] + 0.01, embedding.vector[1], name) plt.xlabel("x" if not xlabel else xlabel) plt.ylabel("y" if not ylabel else ylabel)
def plot_field(self, x, y, u=None, v=None, F=None, contour=False, outdir=None, plot='quiver', figname='_field', format='eps'): outdir = self.set_dir(outdir) p = 64 if F is None: F = self.calc_F(u, v) plt.close('all') plt.figure() #fig, axes = plt.subplots(nrows=1) if contour: plt.hold(True) plt.contourf(x, y, F) if plot == 'quiver': plt.quiver(x[::p], y[::p], u[::p], v[::p], scale=0.1) if plot == 'pcolor': plt.pcolormesh(x[::4], y[::4], F[::4], cmap=plt.cm.Pastel1) plt.colorbar() if plot == 'stream': speed = F[::16] plt.streamplot(x[::16], y[::16], u[::16], v[::16], density=(1, 1), color='k') plt.xlabel('$x$ (a.u.)') plt.ylabel('$y$ (a.u.)') plt.savefig(os.path.join(outdir, figname + '.' + format), format=format, dpi=320, bbox_inches='tight') plt.close()
def on_means(limits, count, mean_vx, mean_vy): if normalize: length = np.sqrt(mean_vx**2 + mean_vy**2) mean_vx = mean_vx / length mean_vy = mean_vy / length x_centers = self.bin_centers(x, limits[0], shape=shape[0]) y_centers = self.bin_centers(y, limits[1], shape=shape[1]) Y, X = np.meshgrid(x_centers, y_centers) # , indexing='ij') count = count.flatten() mask = count >= min_count kwargs['alpha'] = kwargs.get('alpha', 0.7) plt.quiver(X.flatten()[mask], Y.flatten()[mask], mean_vx.flatten()[mask], mean_vy.flatten()[mask], **kwargs) if show: plt.show() return
def navigation_map(self, K=25): plt.figure(figsize=(5.5, 5.5)) plt.subplot(aspect='equal') X, Y = np.meshgrid(np.linspace(0, 1, K + 1), np.linspace(0, 1, K + 1)) best_actions = np.zeros((K + 1, K + 1)) for i in range(K + 1): for j in range(K + 1): best_actions[i, j] = np.argmax(self.get_Qvalue_(X[i, j], Y[i, j])) dX = np.cos(2 * np.pi / self.n_actions_ * best_actions) dY = np.sin(2 * np.pi / self.n_actions_ * best_actions) plt.quiver(X, Y, dX, dY, scale=20) self._plot_dots() plt.draw()
def quiver(self,coordinate,attribute): ''' Quiver plot the attribute of the body.chord Input ----- coordinates - the coordinates of the quiver plot. Standard coordinates of the body: 'geometry'. attribute - body parameter that needs to plotted. Ex. 'geometry' Returns ------- quiver plot with attributes plotted at given coordinates. Figure not configured. ''' plt.quiver(self.__dict__[coordinate][0], self.__dict__[coordinate][1], self.__dict__[attribute][0], self.__dict__[attribute][1])
def on_means(limits, count, mean_vx, mean_vy): if normalize: length = np.sqrt(mean_vx**2 + mean_vy**2) mean_vx = mean_vx / length mean_vy = mean_vy / length x_centers = self.bin_centers(x, limits[0], shape=shape[0]) y_centers = self.bin_centers(y, limits[1], shape=shape[1]) Y, X = np.meshgrid(y_centers, x_centers) # , indexing='ij') count = count.flatten() mask = count >= min_count kwargs['alpha'] = kwargs.get('alpha', 0.7) plt.quiver(X.flatten()[mask], Y.flatten()[mask], mean_vx.flatten()[mask], mean_vy.flatten()[mask], **kwargs) if show: plt.show() return
def _plot_vector_field(self, resolution): """ Plot vector field. Arguments resolution Resolution of plot """ x_mesh, y_mesh, ode_x, ode_y = self._get_ode_values(resolution) # scale vector field hyp = np.hypot(ode_x, ode_y) hyp[hyp==0] = 1. ode_x /= hyp ode_y /= hyp plt.quiver( x_mesh, y_mesh, ode_x, ode_y, pivot='mid', color='lightgray')
def draw_gradient_2d(): x0 = np.arange(-2, 2.5, 0.25) x1 = np.arange(-2, 2.5, 0.25) X, Y = np.meshgrid(x0, x1) X = X.flatten() Y = Y.flatten() grad = numerical_gradient(function_2, np.array([X, Y])) plt.figure() plt.quiver(X, Y, -grad[0], -grad[1], angles="xy", color="#666666") plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.xlabel('x0') plt.ylabel('x1') plt.grid() plt.legend() plt.draw() plt.show()
def vector_field2d(barycenters, vector_field, N, figure=None): dn = 1. / N N = complex(0, N) xmin, xmax = barycenters[:, 0].min(), barycenters[:, 0].max() ymin, ymax = barycenters[:, 1].min(), barycenters[:, 1].max() vector_field *= dn / sqrt((vector_field**2).sum(1).max()) grid = mgrid[xmin + dn * (xmax - xmin):xmax:N, ymin + dn * (ymax - ymin):ymax:N] z1 = [ griddata(barycenters, z0, grid.transpose((1, 2, 0)), method='linear') for z0 in vector_field.T ] from matplotlib import pylab X, Y = grid VX, VY = z1 if figure == None: fig = pylab.figure(figsize=(10, 10)) pylab.quiver(X, Y, VX, VY, sqrt(VX**2 + VY**2), scale=1, figure=figure) pylab.axis([xmin, xmax, ymin, ymax])
def __call__(self, **params): p=ParamOverrides(self,params) name=p.plot_template.keys().pop(0) plot=make_template_plot(p.plot_template, p.sheet.views.Maps, p.sheet.xdensity,p.sheet.bounds, p.normalize,name=p.plot_template[name]) fig = plt.figure(figsize=(5,5)) if plot: bitmap=plot.bitmap isint=plt.isinteractive() # Temporarily make non-interactive for plotting plt.ioff() # Turn interactive mode off plt.imshow(bitmap.image,origin='lower',interpolation='nearest') plt.axis('off') for (t,pref,sel,c) in p.overlay: v = plt.flipud(p.sheet.views.Maps[pref].view()[0]) if (t=='contours'): plt.contour(v,[sel,sel],colors=c,linewidths=2) if (t=='arrows'): s = plt.flipud(p.sheet.views.Maps[sel].view()[0]) scale = int(np.ceil(np.log10(len(v)))) X = np.array([x for x in xrange(len(v)/scale)]) v_sc = np.zeros((len(v)/scale,len(v)/scale)) s_sc = np.zeros((len(v)/scale,len(v)/scale)) for i in X: for j in X: v_sc[i][j] = v[scale*i][scale*j] s_sc[i][j] = s[scale*i][scale*j] plt.quiver(scale*X, scale*X, -np.cos(2*np.pi*v_sc)*s_sc, -np.sin(2*np.pi*v_sc)*s_sc, color=c, edgecolors=c, minshaft=3, linewidths=1) p.title='%s overlaid with %s at time %s' %(plot.name,pref,topo.sim.timestr()) if isint: plt.ion() p.filename_suffix="_"+p.sheet.name self._generate_figure(p) return fig
def plot_motion_field_quiver(UV, geodata=None, step=15): """Function to plot a precipitation field witha a colorbar. Parameters ---------- UV : array-like Array of shape (2, m,n) containing the input motion field. geodata : dictionary step : int Returns: ---------- ax : fig axes Figure axes. Needed if one wants to add e.g. text inside the plot. """ # prepare X Y coordinates if geodata is not None: X, Y = np.meshgrid( np.arange(geodata['x1'] / 1000, geodata['x2'] / 1000), np.arange(geodata['y1'] / 1000, geodata['y2'] / 1000)) else: X, Y = np.meshgrid(np.arange(UV.shape[2]), np.arange(UV.shape[1])) # reduce number of vectors to plot UV_ = UV[:, 0:UV.shape[1]:step, 0:UV.shape[2]:step] X_ = X[0:UV.shape[1]:step, 0:UV.shape[2]:step] Y_ = Y[0:UV.shape[1]:step, 0:UV.shape[2]:step] plt.quiver(X_, Y_, UV_[0, :, :], -UV_[1, :, :], pivot='tip') axes = plt.gca() if geodata is None: axes.xaxis.set_ticklabels([]) axes.yaxis.set_ticklabels([]) return axes
def _plot_vector_field(self, resolution): """ Plot vector field. Arguments resolution Resolution of plot """ x_mesh, y_mesh, ode_x, ode_y = self._get_ode_values(resolution) # scale vector field hyp = np.hypot(ode_x, ode_y) hyp[hyp == 0] = 1. ode_x /= hyp ode_y /= hyp plt.quiver(x_mesh, y_mesh, ode_x, ode_y, pivot='mid', color='lightgray')
def test_east_w1_lonlat(grid, target_points, connectivity): """ Test computation of edge integrals using an eastward vector field """ nedge = grid.getNumberOfEdges() ntarget = target_points.shape[0] lon = connectivity['lon'] lat = connectivity['lat'] edge_node_connect = connectivity['edge_node_connect'] # set the components u1 = numpy.ones((nedge, ), numpy.float64) # east u2 = numpy.zeros((nedge, ), numpy.float64) ue_integrated = getIntegralsInLonLat(lon, lat, edge_node_connect, u1, u2, w1=True) vi = VectorInterp() vi.setGrid(grid) vi.buildLocator(numCellsPerBucket=100) vi.findPoints(target_points, tol2=1.e-10) vects = vi.getEdgeVectors(ue_integrated, placement=1) error = numpy.sum(numpy.fabs(vects[:, 1] / (vects[:, 0] + EPS))) / ntarget print(f'test_east_w1_lonlat: error = {error}') assert (error < 0.06) if False: from matplotlib import pylab pylab.quiver(target_points[:, 0], target_points[:, 1], vects[:, 0], vects[:, 1]) pylab.title('test_east_w1_lonlat') pylab.show()
def gradient( func, x0_max=2.5, x0_min=-2., x0_step=0.25, x1_max=2.5, x1_min=-2., x1_step=0.25, x_max=2., x_min=-2., y_max=2., y_min=-2.): x0_elements = np.arange(x0_min, x0_max, x0_step) x1_elements = np.arange(x1_min, x1_max, x1_step) X, Y = np.meshgrid(x0_elements, x1_elements) X = X.flatten() Y = Y.flatten() y = differentiations.numerical_gradient(func, np.array([X, Y])) plt.figure() plt.quiver(X, Y, y[0], y[1], angles="xy",color="#666666") plt.xlim([x_min, x_max]) plt.ylim([y_min, y_max]) plt.xlabel('x0') plt.ylabel('x1') plt.grid() plt.legend() plt.draw() plt.show()
def quiver(grid, u_field_name, v_field_name, **kwargs): fig = plt.figure() plt.axes().set_aspect('equal') u, v = grid.get_cell_fields(u_field_name, v_field_name) cell_nodes = grid.cell_nodes plt.quiver(cell_nodes[:, :, 0], cell_nodes[:, :, 1], u, v) if kwargs.get('show_grid', False): plt.plot(cell_nodes[:, :, 0], cell_nodes[:, :, 1], '-', color='black') plt.plot(np.transpose(cell_nodes[:, :, 0]), np.transpose(cell_nodes[:, :, 1]), '-', color='black') if kwargs.get('mark_cell_centers', False): plt.plot(cell_nodes[:, :, 0], cell_nodes[:, :, 1], 'o', color='black') if kwargs.get('show', False): plt.show() f = BytesIO() plt.savefig(f) return f
def main(): F = np.load("faces.npz")['F'] F = F[:, :, ::-1] testing = ag.io.load_example('mnist') testing = testing[:, ::-1] settings = dict(origin='lower', interpolation='nearest', cmap=plt.cm.gray) for d in [9]: print("Digit:", d) imdef, info = ag.ml.bernoulli_model(testing[0], F[d], calc_costs=True) print(info['iterations_per_level']) print(-info['loglikelihoods'][-1] - info['logpriors'][-1]) subject = testing[1] #imdef = ag.util.DisplacementFieldWavelet(testing[0].shape) #imdef.u[0][0,0] = 0.6 x, y = imdef.get_x(subject.shape) Ux, Uy = imdef.deform_map(x, y) print('U-max:', Ux.max(), Uy.max()) #print(imdef.u) im = imdef.deform(subject) plt.figure(figsize=(7, 7)) plt.subplot(221) plt.imshow(subject, **settings) plt.subplot(222) plt.imshow(im, **settings) plt.subplot(223) plt.imshow(F[d].sum(axis=0), **settings) plt.subplot(224) plt.quiver(y, x, Uy, Ux) #plt.plot(-(info['loglikelihoods']+info['logpriors'])) plt.show()
def visualize(): x = np.arange(3, 7., 0.15) y = np.arange(3, 7., 0.5) xx, yy = np.meshgrid(x, y) d = 1. start = np.array([4.75, 4.75]) # Location of points # 1 2 # 0 3 loc = np.array(([start[0], start[1]], [start[0], start[1] + d], [start[0] + d, start[1] + d], [start[0] + d, start[1]])) psi = np.zeros_like(xx) vxx = np.zeros_like(xx) vyy = np.zeros_like(xx) gamma = np.array([1., -1., -1., 1.]) for i in np.arange(0, 4): p, vx, vy = vortex_flow(xx, yy, loc[i, 0], loc[i, 1], gamma=gamma[i]) psi += p vxx += vx vyy += vy # plt.contour(xx, yy, vxx, 100) # plt.contourf(xx, yy, vyy, 100) # plt.contourf(xx, yy, psi, 100) plt.contour(xx, yy, np.sqrt(vxx**2 + vyy**2), 100) plt.quiver(xx, yy, vxx, vyy) plt.scatter(loc[:, 0], loc[:, 1]) plt.show() return
def __init__(self, cells, t, **kwargs): """ Creates a new flux map :param cells: The cells to be used :param t: The current time step :param kwargs: Keyword arguments for plt.quiver """ self.cells = cells # get position vector p = cmf.cell_positions(cells) # get flux vector f = cmf.cell_flux_directions(cells, t) self.t = t a = numpy.array self.quiver = plt.quiver(a(p.X), a(p.Y), a(f.X), a(f.Y), **kwargs)
def main(): F = np.load("faces.npz")['F'] F = F[:,:,::-1] testing = ag.io.load_example('mnist') testing = testing[:,::-1] settings = dict(origin='lower', interpolation='nearest', cmap=plt.cm.gray) for d in [9]: print("Digit:", d) imdef, info = ag.ml.bernoulli_model(testing[0], F[d], calc_costs=True) print(info['iterations_per_level']) print(-info['loglikelihoods'][-1] - info['logpriors'][-1]) subject = testing[1] #imdef = ag.util.DisplacementFieldWavelet(testing[0].shape) #imdef.u[0][0,0] = 0.6 x, y = imdef.get_x(subject.shape) Ux, Uy = imdef.deform_map(x, y) print('U-max:',Ux.max(), Uy.max()) #print(imdef.u) im = imdef.deform(subject) plt.figure(figsize=(7,7)) plt.subplot(221) plt.imshow(subject, **settings) plt.subplot(222) plt.imshow(im, **settings) plt.subplot(223) plt.imshow(F[d].sum(axis=0), **settings) plt.subplot(224) plt.quiver(y, x, Uy, Ux) #plt.plot(-(info['loglikelihoods']+info['logpriors'])) plt.show()
def twoD_ArrayQuiver(X, Y, Z): """ Represent a 2D array with arrows Parameters ---------- X : numpy.ndarray メッシュのX座標 Y : numpy.ndarray メッシュのY座標 Z : numpy.ndarray メッシュのZ座標 """ plt.figure() plt.quiver(X, Y, -Z[0], -Z[1], angles='xy', color='#666666') plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.xlabel('x0') plt.ylabel('x1') plt.grid() plt.legend() plt.draw() plt.show()
def main(F, coef, filename=None, test_index=1): #Fmax = F.max() #F *= 1.0 #F = np.clip(F, 0.01, 1.0 - 0.01) #print("Normalizing with {0}".format(Fmax)) #testing = ag.io.load_example('mnist') testing = np.load('digits.npz')['nines'] testing = testing[:,::-1] settings = dict(origin='lower', interpolation='nearest', cmap=None, vmin=0.0, vmax=1.0) feat = int(sys.argv[1]) costs = [] for d in [9]: print("Digit:", d) imdef, info = ag.ml.bernoulli_model(F[d], testing[test_index], calc_costs=True, tol=1e-4) #imdef, info = ag.ml.imagedef(F[d], testing[test_index], coef=1e-2, stepsize=0.3, calc_costs=True) print(info['iterations_per_level']) print("Cost:", -info['loglikelihoods'][-1] - info['logpriors'][-1]) subject = ag.features.bedges(testing[test_index])[:,:,feat].astype(np.float64) #subject = testing[1] #imdef = ag.util.DisplacementFieldWavelet(testing[0].shape) #imdef.u[0][0,0] = 0.6 x, y = imdef.get_x(subject.shape) Ux, Uy = imdef.deform_map(x, y) print('U-max:',Ux.max(), Uy.max()) #print(imdef.u) imf = imdef.deform(subject) canon_nine = np.load('canonical-digits.npz')['F'][9] #im = imdef.deform(F[d,feat]) im = imdef.deform(canon_nine) costs.append(-info['loglikelihoods'][-1] - info['loglikelihoods'][-1]) if PLOT: plt.figure(figsize=(11,7)) plt.subplot(231) plt.imshow(subject, **settings) plt.subplot(232) plt.imshow(imf, **settings) plt.subplot(233) #plt.imshow(F[d,feat], **settings) plt.imshow(F[d,feat], **settings) plt.subplot(234) plt.quiver(y, x, Uy, Ux, scale=1.0) plt.subplot(235) plt.imshow(testing[test_index], **settings) plt.subplot(236) plt.imshow(im, **settings) plt.colorbar() #plt.plot(-(info['loglikelihoods']+info['logpriors'])) print("RESULT Digit: {0}".format(np.argmin(costs))) if PLOT: if filename: plt.savefig(filename) else: plt.show()
g = lambda y: -(y - W/2.) #f = lambda x: np.sin(x/175. + 100) for i in xrange(0,N): for j in xrange(0,N): U[i,j] = f(p*i) V[i,j] = g(p*j) X[i,j] = p*i Y[i,j] = p*j im.new_figure() #plt.figure() #plt.axis("equal") plt.quiver(X,Y,U,V,color='k',scale_units='inches', scale=3000) qx,qy = im.split_array(q) plt.plot(qx,qy,color="k", lw=3) plt.axis((0,W,0,W)) plt.savefig("misc/outer_field.pdf",bbox_inches='tight') #no build the quiver for the inner metric plot u = [f(x) for x in qx] v = [g(y) for y in qy] ut = [] vt = [] xt = [] yt = [] for i in np.arange(0,201,2):
def tangent_line(f, x): d = numerical_gradient(f, x) print(d) y = f(x) - d * x return lambda t: d * t + y if __name__ == '__main__': x0 = np.arange(-2, 2.5, 0.25) x1 = np.arange(-2, 2.5, 0.25) X, Y = np.meshgrid(x0, x1) X = X.flatten() Y = Y.flatten() grad = numerical_gradient(function_2, np.array([X, Y])) plt.figure() plt.quiver(X, Y, -grad[0], -grad[1], angles="xy", color="#666666") #,headwidth=10,scale=40,color="#444444") plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.xlabel('x0') plt.ylabel('x1') plt.grid() plt.legend() plt.draw() plt.show()
import numpy as np import matplotlib.pylab as plt images = np.load('nines.npz')['images'] im = images[0] im = im[::-1,:] plt.figure(figsize=(14,6)) plt.subplot(121) plt.xlabel('x') plt.ylabel('y') plt.imshow(im, interpolation='nearest', origin='lower') plt.subplot(122) plt.quiver(im, np.zeros(im.shape)) plt.show()
def symimage(*args,**kwargs): I = plp.Image() T = plp.Tools() #fig = plt.figure() Dmhd = plp.pload(319,w_dir='/Users/bhargavvaidya/pyPLUTO-wdir/M30a055b5_data/') Data = args[0] sclf = kwargs.get('scalefact',1.0) if kwargs.get('log',False)==True: var = np.log10(sclf*Data.__getattribute__(args[1])) else: var = sclf*Data.__getattribute__(args[1]) x1 = Data.x1 x2 = Data.x2 plt.axis([-x1.max(),x1.max(),0.0,x2.max()]) plt.title(kwargs.get('title',"Title"),size=kwargs.get('size')) plt.xlabel(kwargs.get('label1',"Xlabel"),size=kwargs.get('size'),labelpad=6) plt.ylabel(kwargs.get('label2',"Ylabel"),size=kwargs.get('size'),labelpad=6) xm,ym = np.meshgrid(x1.T,x2.T) xmc = T.congrid(xm,2*([kwargs.get('arrows')[1]]),method='linear') ymc = T.congrid(ym,2*([kwargs.get('arrows')[1]]),method='linear') v1c = T.congrid(Data.v1.T,2*([kwargs.get('arrows')[1]]),method='linear') v2c = T.congrid(Data.v2.T,2*([kwargs.get('arrows')[1]]),method='linear') v1cn,v2cn = v1c/np.sqrt(v1c**2+v2c**2),v2c/np.sqrt(v1c**2+v2c**2) if kwargs.get('ysym',False) == True: ysymvar = np.flipud(var) plc1=plt.pcolormesh(-x1[::-1],x2,ysymvar.T,vmin=kwargs.get('vmin',np.min(var)),vmax=kwargs.get('vmax',np.max(var))) plc2=plt.pcolormesh(x1,x2,var.T,vmin=kwargs.get('vmin',np.min(var)),vmax=kwargs.get('vmax',np.max(var))) if kwargs.get('cbar',(False,''))[0] == True: plcol=plt.colorbar(orientation=kwargs.get('cbar')[1]) if kwargs.get('arrows',(False,20))[0]==True: plq1=plt.quiver(xmc,ymc,v1cn,v2cn,color='k') plq2=plt.quiver(-xmc,ymc,-v1cn,v2cn,color='k') if kwargs.get('flines',(False,[3.0,6.0,10.0,15.0],[0.001,0.001,0.001,0.001]))[0]==True: x0arr = kwargs.get('flines')[1] y0arr = kwargs.get('flines')[2] for i in range(np.size(x0arr)): flmhd = I.field_line(Dmhd.b1,Dmhd.b2,Dmhd.x1,Dmhd.x2,Dmhd.dx1,Dmhd.dx2,x0arr[i],y0arr[i]) Qxmhd = flmhd.get('qx') Qymhd = flmhd.get('qy') fl =I.field_line(Data.b1,Data.b2,Data.x1,Data.x2,Data.dx1,Data.dx2,x0arr[i],y0arr[i]) Qx= fl.get('qx') Qy= fl.get('qy') plfl1=plt.plot(Qx,Qy,color=kwargs.get('colors','r'),ls=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plfl2=plt.plot(-Qx,Qy,color=kwargs.get('colors','r'),ls=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plfl3=plt.plot(Qxmhd,Qymhd,color=kwargs.get('colors','w'),ls=kwargs.get('ls','--'),lw=kwargs.get('lw',2.0)) plfl4=plt.plot(-Qxmhd,Qymhd,color=kwargs.get('colors','w'),ls=kwargs.get('ls','--'),lw=kwargs.get('lw',2.0)) if kwargs.get('xsym',False) == True: xsymvar = np.fliplr(var) plc1=plt.pcolormesh(x1,-x2[::-1],xsymvar.T,vmin=kwargs.get('vmin',np.min(var)),vmax=kwargs.get('vmax',np.max(var))) plc2=plt.pcolormesh(x1,x2,var.T,vmin=kwargs.get('vmin',np.min(var)),vmax=kwargs.get('vmax',np.max(var))) if kwargs.get('cbar',(False,''))[0] == True: plcol=plt.colorbar(orientation=kwargs.get('cbar')[1]) if kwargs.get('arrows',(False,20))[0]==True: plq1=plt.quiver(xmc,ymc,v1cn,v2cn,color='g') plq2=plt.quiver(xmc,-ymc,v1cn,-v2cn,color='g') if kwargs.get('flines',(False,[3.0,6.0,10.0,15.0],[0.001,0.001,0.001,0.001]))[0]==True: x0arr = kwargs.get('flines')[1] y0arr = kwargs.get('flines')[2] for i in range(np.size(x0arr)): flmhd = I.field_line(Dmhd.b1,Dmhd.b2,Dmhd.x1,Dmhd.x2,Dmhd.dx1,Dmhd.dx2,x0arr[i],y0arr[i]) Qxmhd = flmhd.get('qx') Qymhd = flmhd.get('qy') fl =I.field_line(Data.b1,Data.b2,Data.x1,Data.x2,Data.dx1,Data.dx2,x0arr[i],y0arr[i]) Qx= fl.get('qx') Qy= fl.get('qy') plfl1= plt.plot(Qx,Qy,color=kwargs.get('colors','r'),ls=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plfl2= plt.plot(Qx,-Qy,color=kwargs.get('colors','r'),ls=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plfl1= plt.plot(Qxmhd,Qymhd,color=kwargs.get('colors','w'),ls=kwargs.get('ls','--'),lw=kwargs.get('lw',2.0)) plfl2= plt.plot(Qxmhd,-Qymhd,color=kwargs.get('colors','w'),ls=kwargs.get('ls','--'),lw=kwargs.get('lw',2.0)) if kwargs.get('fullsym',False) == True: ysymvar = np.flipud(var) plc1=plt.pcolormesh(-x1[::-1],x2,ysymvar.T,vmin=kwargs.get('vmin',np.min(var)),vmax=kwargs.get('vmax',np.max(var))) xsymvar = np.fliplr(var) plc2=plt.pcolormesh(x1,-x2[::-1],xsymvar.T,vmin=kwargs.get('vmin',np.min(var)),vmax=kwargs.get('vmax',np.max(var))) plc3=plt.pcolormesh(-x1,-x2,var.T,vmin=kwargs.get('vmin',np.min(var)),vmax=kwargs.get('vmax',np.max(var))) plc4=plt.pcolormesh(x1,x2,var.T,vmin=kwargs.get('vmin',np.min(var)),vmax=kwargs.get('vmax',np.max(var))) if kwargs.get('cbar',(False,''))[0] == True: plcol=plt.colorbar(orientation=kwargs.get('cbar')[1]) if kwargs.get('arrows',(False,20))[0]==True: plq1=plt.quiver(-xmc,ymc,-v1cn,v2cn,color='w') plq2=plt.quiver(xmc,-ymc,v1cn,-v2cn,color='w') plq3=plt.quiver(xmc,ymc,v1cn,v2cn,color='w') plq4=plt.quiver(-xmc,-ymc,-v1cn,-v2cn,color='w') if kwargs.get('flines',(False,[2.0,4.0,7.0,13.0],[0.001,0.001,0.001,0.001]))[0]==True: x0arr = kwargs.get('flines')[1] y0arr = kwargs.get('flines')[2] for i in range(np.size(x0arr)): fl =I.field_line(Data.b1,Data.b2,Data.x1,Data.x2,Data.dx1,Data.dx2,x0arr[i],y0arr[i]) Qx= fl.get('qx') Qy= fl.get('qy') plfl1=plt.plot(Qx,Qy,color=kwargs.get('colors','r'),ls=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plfl2=plt.plot(-Qx,Qy,color=kwargs.get('colors','r'),ls=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plfl3=plt.plot(Qx,-Qy,color=kwargs.get('colors','r'),ls=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plfl4=plt.plot(-Qx,-Qy,color=kwargs.get('colors','r'),ls=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) return [plc1,plc2,plcol,plq1,plq2,plfl1,plfl2,plfl3,plfl4]
def interpolate_sparse_vectors(x, y, u, v, domain_size, function="inverse", k=20, epsilon=None, nchunks=5): """Interpolation of sparse motion vectors to produce a dense field of motion vectors. Parameters ---------- x : array-like x coordinates of the sparse motion vectors y : array-like y coordinates of the sparse motion vectors u : array_like u components of the sparse motion vectors v : array_like v components of the sparse motion vectors domain_size : tuple size of the domain of the dense motion field [px] function : string the radial basis function, based on the Euclidian norm, d. default : inverse available : nearest, inverse, gaussian k : int or "all" the number of nearest neighbors used to speed-up the interpolation If set equal to "all", it employs all the sparse vectors default : 20 epsilon : float adjustable constant for gaussian or inverse functions default : median distance between sparse vectors nchunks : int split the grid points in n chunks to limit the memory usage during the interpolation default : 5 Returns ------- X : array-like grid Y : array-like grid UV : array-like Three-dimensional array (2,domain_size[0],domain_size[1]) containing the dense U, V motion fields. """ testinterpolation = False # make sure these are vertical arrays x = x[:,None] y = y[:,None] u = u[:,None] v = v[:,None] points = np.column_stack((x, y)) if len(domain_size)==1: domain_size = (domain_size, domain_size) # generate the grid xgrid = np.arange(domain_size[1]) ygrid = np.arange(domain_size[0]) X, Y = np.meshgrid(xgrid, ygrid) grid = np.column_stack((X.ravel(), Y.ravel())) U = np.zeros(grid.shape[0]) V = np.zeros(grid.shape[0]) # create cKDTree object to represent source grid if k is not "all": k = np.min((k, points.shape[0])) tree = scipy.spatial.cKDTree(points) # split grid points in n chunks subgrids = np.array_split(grid, nchunks, 0) subgrids = [x for x in subgrids if x.size > 0] # loop subgrids i0=0 for i,subgrid in enumerate(subgrids): idelta = subgrid.shape[0] if function.lower() == "nearest": # find indices of the nearest neighbors _, inds = tree.query(subgrid, k=1) U[i0:(i0+idelta)] = u.flatten()[inds] V[i0:(i0+idelta)] = v.flatten()[inds] else: if k == "all": d = scipy.spatial.distance.cdist(points, subgrid, 'euclidean').transpose() inds = np.arange(u.size)[None,:]*np.ones((subgrid.shape[0],u.size)).astype(int) else: # find indices of the k-nearest neighbors d, inds = tree.query(subgrid, k=k) # the bandwidth if epsilon is None: dpoints = scipy.spatial.distance.pdist(points, 'euclidean') epsilon = np.median(dpoints) # the interpolation weights if function.lower() == "inverse": w = 1.0/np.sqrt((d/epsilon)**2 + 1) elif function.lower() == "gaussian": w = np.exp(-0.5*(d/epsilon)**2) else: raise ValueError("unknown radial fucntion %s" % function) U[i0:(i0+idelta)] = np.sum(w * u.flatten()[inds], axis=1) / np.sum(w, axis=1) V[i0:(i0+idelta)] = np.sum(w * v.flatten()[inds], axis=1) / np.sum(w, axis=1) i0 += idelta # reshape back to original size U = U.reshape(domain_size[0], domain_size[1]) V = V.reshape(domain_size[0], domain_size[1]) UV = np.stack([U, V]) if testinterpolation: import matplotlib.pylab as plt step=15 UV_ = UV[:, 0:UV.shape[1]:step, 0:UV.shape[2]:step] X_ = X[0:UV.shape[1]:step, 0:UV.shape[2]:step] Y_ = Y[0:UV.shape[1]:step, 0:UV.shape[2]:step] plt.quiver(X_, np.flipud(Y_), UV_[0,:,:], -UV_[1,:,:]) plt.quiver(x, np.flipud(y), u, -v, color="red") plt.show() return X, Y, UV
def drainage_plot( mg, surface="topographic__elevation", receivers=None, proportions=None, surf_cmap="gray", quiver_cmap="viridis", title="Drainage Plot", ): if isinstance(surface, six.string_types): colorbar_label = surface else: colorbar_label = "topographic_elevation" imshow_grid(mg, surface, cmap=surf_cmap, colorbar_label=colorbar_label) if receivers is None: receivers = mg.at_node["flow__receiver_node"] if proportions is None: if "flow__receiver_proportions" in mg.at_node: proportions = mg.at_node["flow__receiver_proportions"] else: receivers = np.asarray(receivers) if receivers.ndim == 1: receivers = np.expand_dims(receivers, axis=1) nreceievers = receivers.shape[-1] propColor = plt.get_cmap(quiver_cmap) for j in range(nreceievers): rec = receivers[:, j] is_bad = rec == -1 xdist = -0.8 * (mg.x_of_node - mg.x_of_node[rec]) ydist = -0.8 * (mg.y_of_node - mg.y_of_node[rec]) if proportions is None: proportions = np.ones_like(receivers, dtype=float) is_bad[proportions[:, j] == 0.0] = True xdist[is_bad] = np.nan ydist[is_bad] = np.nan prop = proportions[:, j] * 256.0 lu = np.floor(prop) colors = propColor(lu.astype(int)) shape = (mg.number_of_nodes, 1) plt.quiver( mg.x_of_node.reshape(shape), mg.y_of_node.reshape(shape), xdist.reshape(shape), ydist.reshape(shape), color=colors, angles="xy", scale_units="xy", scale=1, zorder=3, ) # Plot differen types of nodes: o, = plt.plot( mg.x_of_node[mg.status_at_node == CORE_NODE], mg.y_of_node[mg.status_at_node == CORE_NODE], "b.", label="Core Nodes", zorder=4, ) fg, = plt.plot( mg.x_of_node[mg.status_at_node == FIXED_VALUE_BOUNDARY], mg.y_of_node[mg.status_at_node == FIXED_VALUE_BOUNDARY], "c.", label="Fixed Gradient Nodes", zorder=5, ) fv, = plt.plot( mg.x_of_node[mg.status_at_node == FIXED_GRADIENT_BOUNDARY], mg.y_of_node[mg.status_at_node == FIXED_GRADIENT_BOUNDARY], "g.", label="Fixed Value Nodes", zorder=6, ) c, = plt.plot( mg.x_of_node[mg.status_at_node == CLOSED_BOUNDARY], mg.y_of_node[mg.status_at_node == CLOSED_BOUNDARY], "r.", label="Closed Nodes", zorder=7, ) node_id = np.arange(mg.number_of_nodes) flow_to_self = receivers[:, 0] == node_id fts, = plt.plot( mg.x_of_node[flow_to_self], mg.y_of_node[flow_to_self], "kx", markersize=6, label="Flows To Self", zorder=8, ) ax = plt.gca() ax.legend( labels=[ "Core Nodes", "Fixed Gradient Nodes", "Fixed Value Nodes", "Closed Nodes", "Flows To Self", ], handles=[o, fg, fv, c, fts], numpoints=1, loc="center left", bbox_to_anchor=(1.7, 0.5), ) sm = plt.cm.ScalarMappable(cmap=propColor, norm=plt.Normalize(vmin=0, vmax=1)) sm._A = [] cx = plt.colorbar(sm) cx.set_label("Proportion of Flow") plt.title(title)
U[j,-1] = UVP[loc_glob[j*Nx+Nx-1,N]] V[j,-1] = UVP[loc_glob[j*Nx+Nx-1,N]+dofs] for i in range(Nx): #Leftmost point: U[-1,i] = UVP[loc_glob[Nx*(Ny-1)+i, N*(N-1)]] V[-1,i] = UVP[loc_glob[Nx*(Ny-1)+i, N*(N-1)]+dofs] #General point: U[j,i] = UVP[loc_glob[Nx*j+i,0]] V[j,i] = UVP[loc_glob[Nx*j+i,0]+dofs] #Right- and topmost corner: U[-1,-1] = UVP[loc_glob[-1,-1]] V[-1,-1] = UVP[loc_glob[-1,-1]+dofs] pl.quiver(X_el, Y_el, U, V, scale=10.0) plt.plot( X_el[0, patches:(idim-patches)], Y_el[0, patches:(idim-patches)], 'b') pl.xlabel('$x$') pl.ylabel('$y$') pl.axis('image') ''' # PRESSURE PLOT: plt.subplot(122) ax = fig.add_subplot(122, projection='3d') for K in range(num_el): ax.plot_wireframe( X[K, 1:-1, 1:-1], Y[K, 1:-1, 1:-1], UVP[loc_glob_p[K]+2*dofs].reshape((N-2,N-2))) ''' pl.show()
""" Plot of wind speed, wind vectors and surface pressure By Richard Essery """ import numpy as np import matplotlib.pylab as plt plt.figure(figsize=(10, 10)) P = np.loadtxt('Psurf.txt') U = np.loadtxt('Uwind.txt') V = np.loadtxt('Vwind.txt') W = np.sqrt(U**2 + V**2) # wind speed as an image with a colour bar plt.imshow(W, cmap='PuBu', origin='lower') cbar = plt.colorbar(shrink=0.6) cbar.set_label('wind speed (m s$^{-1}$)', fontsize=16, rotation=270) # surface pressure as a contour plot with 4 hPa spacing levels = 960 + 4*np.arange(20) cs = plt.contour(P, colors='black', levels=levels) plt.clabel(cs, fmt='%d') # wind vectors plt.quiver(U,V) plt.xticks([]) plt.yticks([]) plt.show()
# TIME TO SOLVE: #################### print "Done solving..." P = UVP[2*N**2:] P = np.reshape ( P, (N-2,N-2) ) U1 = np.reshape ( U1, (N,N) ) U2 = np.reshape ( U2, (N,N) ) t2 = time.time()-t1 print "Total time: ", t2 ############################ # PLOTTING THE SHIT: ############################ # Quiverplot fig = plt.figure(1) plt.subplot(121) pl.quiver(X, Y, U1, U2, pivot='middle', headwidth=4, headlength=6) pl.xlabel('$x$') pl.ylabel('$y$') pl.axis('image') # Pressureplot plt.subplot(122) ax = fig.add_subplot(122, projection='3d') ax.plot_wireframe(X_p, Y_p, P)#-np.sin(2*np.pi*(X**2 + Y**2))) plt.xlabel('$x$') plt.ylabel('$y$') plt.show()
break print "Time to solve: ", time.time()-t1 counter += 1 print "error : ", error ################################ # PLOTTING: ################################ # Making global X and Y coordinates fig = plt.figure(1) # QUIVERPLOT # P = UVP[2*dofs:] for i in range(num_el): X,Y = gh.gordon_hall_grid(gm.gammas(i,1),gm.gammas(i,2),gm.gammas(i,3),gm.gammas(i,4), xis, xis) plt.subplot(121) pl.quiver(X,Y, U1[loc_glob[i]].reshape( (N,N) ), U2[loc_glob[i]].reshape( (N,N) )) pl.xlabel('$x$') pl.ylabel('$y$') pl.axis('image') # PRESSURE PLOT: plt.subplot(122) ax = fig.add_subplot(122, projection='3d') for i in range(num_el): X,Y = gh.gordon_hall_grid(gm.gammas(i,1),gm.gammas(i,2),gm.gammas(i,3),gm.gammas(i,4), xis, xis) ax.plot_wireframe(X[1:-1,1:-1],Y[1:-1,1:-1], P[loc_glob_p[i]].reshape( (N-2,N-2))) pl.show()
else: return np.sum(x**2, axis=1) def tangent_line(f, x): d = numerical_gradient(f, x) print(d) y = f(x) - d*x return lambda t: d*t + y if __name__ == '__main__': x0 = np.arange(-2, 2.5, 0.25) x1 = np.arange(-2, 2.5, 0.25) X, Y = np.meshgrid(x0, x1) X = X.flatten() Y = Y.flatten() grad = numerical_gradient(function_2, np.array([X, Y]) ) plt.figure() plt.quiver(X, Y, -grad[0], -grad[1], angles="xy",color="#666666")#,headwidth=10,scale=40,color="#444444") plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.xlabel('x0') plt.ylabel('x1') plt.grid() plt.legend() plt.draw() plt.show()
y = f(x) - d * x return lambda t: d * t + y #lambda:引数で関数を返す if __name__ == '__main__': #気にしない x0 = np.arange(-2, 2, 0.25) x1 = np.arange(-2, 2, 0.25) X, Y = np.meshgrid(x0, x1) X = X.flatten() #flatten:多次元配列を一次元に Y = Y.flatten() grad = numerical_gradient(function_2, np.array([X, Y]).T).T plt.figure() plt.quiver(X, Y, -grad[0], -grad[1], angles="xy", color="#666666") plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.xlabel('x0') plt.ylabel('x1') plt.grid() plt.draw() plt.show() _______________________________________________________________________________ #勾配法 #勾配が最も小さくなる方向に少しずつ移動する:勾配降下法 #x=x-η*(∂f/∂x) #η:学習率 #勾配降下法の実装
for i in range(len(u[q])): if i == 0: levcoefs[i] += (u[q][i]**2 ).sum() else: for alpha in range(3): levcoefs[i] += (u[q][i][alpha]**2 ).sum() #print levcoefs from itertools import product shape = im1.shape xs = np.empty(shape + (2,)) for x0, x1 in product(range(shape[0]), range(shape[1])): xs[x0,x1] = np.array([float(x0)/(shape[0]), float(x1)/shape[1]]) defmap = ag.ml.imagedefw.deform_map(xs, u) face2 = ag.ml.imagedefw.deform(face, u) d = dict(origin='lower', interpolation='nearest', cmap=plt.cm.gray) plt.figure(figsize=(9,9)) plt.subplot(221) plt.imshow(face, **d) plt.subplot(222) plt.imshow(face2, **d) plt.subplot(223) plt.plot(levcoefs) #plt.pcolor(u[1][0]) #plt.colorbar() plt.subplot(224) plt.quiver(xs[:,:,1], xs[:,:,0], defmap[:,:,1], defmap[:,:,0]) plt.show()
def singleVector(): dx = 0.05 x = np.arange(-1,1+dx,dx) y = np.arange(-1,1+dx,dx) X,Y = np.meshgrid(x,y) x2 = np.reshape(X,[-1]) y2 = np.reshape(Y,[-1]) xo = np.array([0.]) yo = np.array([0.]) uo = np.array([1.]) vo = np.array([0.]) ob = np.concatenate([uo,vo]) ob = np.reshape(ob,[ob.size,1]) K1 = sqExp(xo,xo,xo,xo,0.1) Ki1 = np.linalg.inv(K1) Ks1 = sqExp(x2,y2,xo,yo,0.1) u1 = np.dot(Ks1,np.dot(Ki1,uo)) u1 = np.reshape(u1,[x.size,-1]) v1 = np.dot(Ks1,np.dot(Ki1,vo)) v1 = np.reshape(v1,[x.size,-1]) K2 = compute_K(xo,xo,0.1,1) Ks2 = compute_Ks(xo,xo,x2,y2,0.1,1) Ki2 = np.linalg.inv(K2) f2 = getMean(Ks2,Ki2,ob) u2 = np.reshape(f2[0:f2.size/2],[x.size,-1]) v2 = np.reshape(f2[f2.size/2:],[x.size,-1]) K3 = compute_K(xo,xo,0.1,2) Ks3 = compute_Ks(xo,xo,x2,y2,0.1,2) Ki3 = np.linalg.inv(K3) f3 = getMean(Ks3,Ki3,ob) u3 = np.reshape(f3[0:f3.size/2],[x.size,-1]) v3 = np.reshape(f3[f3.size/2:],[x.size,-1]) figH = 20 figW = 9.5 bottom = [0.69,0.36,0.03] height = 0.27 left = 0.085 width = 0.88 FS = 38 FS2 = 32 scal = 15. fig = pl.figure(figsize=(figW,figH)) plot=fig.add_axes([left,bottom[0],width,height]) cs=plot.quiver(x,y,u1,v1,scale=scal) pl.quiver(xo,yo,uo,vo,scale=scal,color='r') plot.tick_params(axis='both',which='major',labelsize=FS2) plot.set_title('Isotropic kernel',fontsize = FS) plot.set_xlim([-0.3,0.3]) plot.set_ylim([-0.3,0.3]) plot.set_xticks([-0.3,-0.2,-0.1,0.,0.1,0.2,0.3]) plot.set_yticks([-0.2,-0.1,0.0,0.1,0.2]) plot=fig.add_axes([left,bottom[1],width,height]) cs=plot.quiver(x,y,u2,v2,scale=scal) pl.quiver(xo,yo,uo,vo,scale=scal,color='r') plot.tick_params(axis='both',which='major',labelsize=FS2) plot.set_title('Divergence-free kernel',fontsize = FS) plot.set_xlim([-0.3,0.3]) plot.set_ylim([-0.3,0.3]) plot.set_xticks([-0.3,-0.2,-0.1,0.,0.1,0.2,0.3]) plot.set_yticks([-0.2,-0.1,0.0,0.1,0.2]) plot=fig.add_axes([left,bottom[2],width,height]) cs=plot.quiver(x,y,u3,v3,scale=scal) pl.quiver(xo,yo,uo,vo,scale=scal,color='r') plot.tick_params(axis='both',which='major',labelsize=FS2) plot.set_title('Curl-free kernel',fontsize = FS) plot.set_xlim([-0.3,0.3]) plot.set_ylim([-0.3,0.3]) plot.set_xticks([-0.3,-0.2,-0.1,0.,0.1,0.2,0.3]) plot.set_yticks([-0.2,-0.1,0.0,0.1,0.2]) pl.savefig('plots/one_obs.png', bbox_inches=0)
for i in xrange(Nres): for j in xrange(Nres): r = np.array([Xarray[i], Yarray[j]]) phi2[i, j] = Phi(r, rp2, q2) E = Electric(r, rp2, q2) E2x[i, j], E2y[i, j] = E / np.linalg.norm(E) # CONSTRUCCION DE CAMPO E Y POTENCIAL PHI, TOTAL phi_tot = phi1 + phi2 # Incializacion Campo Electrico Ex_tot = np.ones((Nres, Nres)) Ey_tot = np.ones((Nres, Nres)) # Calculo Potencial Electrico y Campo Electrico Total for i in xrange(Nres): for j in xrange(Nres): E = np.array([E1x[i, j] + E2x[i, j], E1y[i, j] + E2y[i, j]]) E = E / np.linalg.norm(E) Ex_tot[i, j], Ey_tot[i, j] = E # Grafica de equipotenciales plt.contour(X, Y, phi_tot, 100) # Grafica de lineas de campo plt.quiver(X, Y, Ey_tot, Ex_tot) # Limites del eje X plt.xlim((0, 10)) # Limites del eje Y plt.ylim((0, 10)) plt.legend() plt.show()
help='Which velocity field to plot.', choices=['obstacle', 'goal', 'all']) args, unknown = parser.parse_known_args() fig, ax = plt.subplots() # Plot field. X, Y = np.meshgrid(np.linspace(-WALL_OFFSET, WALL_OFFSET, 30), np.linspace(-WALL_OFFSET, WALL_OFFSET, 30)) U = np.zeros_like(X) V = np.zeros_like(X) for i in range(len(X)): for j in range(len(X[0])): velocity = get_velocity(np.array([X[i, j], Y[i, j]]), args.mode) U[i, j] = velocity[0] V[i, j] = velocity[1] plt.quiver(X, Y, U, V, units='width') # Plot environment. ax.add_artist(plt.Circle(CYLINDER_POSITION1, CYLINDER_RADIUS, color='gray')) ax.add_artist(plt.Circle(CYLINDER_POSITION2, CYLINDER_RADIUS, color='gray')) plt.plot([-WALL_OFFSET, WALL_OFFSET], [-WALL_OFFSET, -WALL_OFFSET], 'k') plt.plot([-WALL_OFFSET, WALL_OFFSET], [WALL_OFFSET, WALL_OFFSET], 'k') plt.plot([-WALL_OFFSET, -WALL_OFFSET], [-WALL_OFFSET, WALL_OFFSET], 'k') plt.plot([WALL_OFFSET, WALL_OFFSET], [-WALL_OFFSET, WALL_OFFSET], 'k') # Plot a simple trajectory from the start position. # Uses Euler integration. dt = 0.01 x = START_POSITION
def main(): #import amitgroup.io.mnist #images, _ = read('training', '/local/mnist', [9]) #shifted = np.zeros(images[0].shape) #shifted[:-3,:] = images[0,3:,:] im1, im2 = np.zeros((32, 32)), np.zeros((32, 32)) wl_name = "db2" levels = len(pywt.wavedec(range(32), wl_name)) - 1 scriptNs = map(len, pywt.wavedec(range(32), wl_name, level=levels)) if 0: images = np.load("data/nines.npz")['images'] im1[:28,:28] = images[0] im2[:28,:28] = images[2] else: im1 = ag.io.load_image('data/Images_0', 45) im2 = ag.io.load_image('data/Images_1', 23) im1 = im1[::-1,:] im2 = im2[::-1,:] A = 2 if 1: # Blur images im1b = im1#ag.math.blur_image(im1, 2) im2b = im2#ag.math.blur_image(im2, 2) show_costs = True imgdef, info = ag.ml.imagedef(im1b, im2b, rho=3.0, calc_costs=show_costs) print info['iterations_per_level'] if PLOT and show_costs: logpriors = -info['logpriors'] loglikelihoods = -info['loglikelihoods'] np.savez('logs', logpriors=logpriors, loglikelihoods=loglikelihoods) plotfunc = plt.semilogy plt.figure(figsize=(8,12)) plt.subplot(211) costs = logpriors + loglikelihoods plotfunc(costs, label="J") plotfunc(loglikelihoods, label="log likelihood") plt.legend() plt.subplot(212) plotfunc(logpriors, label="log prior") plt.legend() plt.show() im3 = imgdef.deform(im1) if PLOT: d = dict(origin='lower', interpolation='nearest', cmap=plt.cm.gray) plt.figure(figsize=(9,9)) plt.subplot(221) plt.title("Prototype") plt.imshow(im1, **d) plt.subplot(222) plt.title("Original") plt.imshow(im2, **d) plt.subplot(223) plt.title("Deformed") plt.imshow(im3, **d) plt.subplot(224) if 0: plt.title("Deformed") plt.imshow(im2-im3, **d) plt.colorbar() else: plt.title("Deformation map") x, y = imgdef.get_x(im1.shape) Ux, Uy = imgdef.deform_map(x, y) plt.quiver(y, x, Uy, Ux) plt.show() elif 1: plt.figure(figsize=(14,6)) plt.subplot(121) plt.title("F") plt.imshow(im1, origin='lower') plt.subplot(122) plt.title("I") plt.imshow(im2, origin='lower') plt.show() import pickle if TEST: im3correct = pickle.load(open('im3.p', 'rb')) passed = (im3 == im3correct).all() print "PASSED:", ['NO', 'YES'][passed] print ((im3 - im3correct)**2).sum() else: pickle.dump(im3, open('im3.p', 'wb'))
def drainage_plot(mg, surface='topographic__elevation', receivers=None, proportions=None, surf_cmap='gray', quiver_cmap='viridis', title = 'Drainage Plot'): if isinstance(surface, six.string_types): colorbar_label = surface else: colorbar_label = 'topographic_elevation' imshow_node_grid(mg, surface, cmap=surf_cmap, colorbar_label=colorbar_label) if receivers is None: try: receivers = mg.at_node['flow__receiver_nodes'] if proportions is None: try: proportions = mg.at_node['flow__receiver_proportions'] except: pass except: receivers = np.reshape(mg.at_node['flow__receiver_node'],(mg.number_of_nodes,1)) nreceievers = int(receivers.size/receivers.shape[0]) propColor=plt.get_cmap(quiver_cmap) for j in range(nreceievers): rec = receivers[:,j] is_bad = rec == -1 xdist = -0.8*(mg.node_x-mg.node_x[rec]) ydist = -0.8*(mg.node_y-mg.node_y[rec]) if proportions is None: proportions = np.ones_like(receivers, dtype=float) is_bad[proportions[:,j]==0.]=True xdist[is_bad] = np.nan ydist[is_bad] = np.nan prop = proportions[:,j]*256. lu = np.floor(prop) colors = propColor(lu.astype(int)) shape = (mg.number_of_nodes, 1) plt.quiver(mg.node_x.reshape(shape), mg.node_y.reshape(shape), xdist.reshape(shape), ydist.reshape(shape), color=colors, angles='xy', scale_units='xy', scale=1, zorder=3) # Plot differen types of nodes: o, = plt.plot(mg.node_x[mg.status_at_node == CORE_NODE], mg.node_y[mg.status_at_node == CORE_NODE], 'b.', label='Core Nodes', zorder=4) fg, = plt.plot(mg.node_x[mg.status_at_node == FIXED_VALUE_BOUNDARY], mg.node_y[mg.status_at_node == FIXED_VALUE_BOUNDARY], 'c.', label='Fixed Gradient Nodes', zorder=5) fv, = plt.plot(mg.node_x[mg.status_at_node == FIXED_GRADIENT_BOUNDARY], mg.node_y[mg.status_at_node ==FIXED_GRADIENT_BOUNDARY], 'g.', label='Fixed Value Nodes', zorder=6) c, = plt.plot(mg.node_x[mg.status_at_node == CLOSED_BOUNDARY], mg.node_y[mg.status_at_node ==CLOSED_BOUNDARY], 'r.', label='Closed Nodes', zorder=7) node_id = np.arange(mg.number_of_nodes) flow_to_self = receivers[:,0]==node_id fts, = plt.plot(mg.node_x[flow_to_self], mg.node_y[flow_to_self], 'kx', markersize=6, label = 'Flows To Self', zorder=8) ax = plt.gca() ax.legend(labels = ['Core Nodes', 'Fixed Gradient Nodes', 'Fixed Value Nodes', 'Closed Nodes', 'Flows To Self'], handles = [o, fg, fv, c, fts], numpoints=1, loc='center left', bbox_to_anchor=(1.7, 0.5)) sm = plt.cm.ScalarMappable(cmap=propColor, norm=plt.Normalize(vmin=0, vmax=1)) sm._A = [] cx = plt.colorbar(sm) cx.set_label('Proportion of Flow') plt.title(title) plt.show()
import sympy as sp import numpy as np import matplotlib.pylab as plt x, v = sp.symbols('x v') f = sp.Function('f')(x, v) expr = -x - v f = sp.lambdify((x, v), expr) x = np.linspace(-1, 1, 10) v = np.linspace(-1, 1, 10) x, v = np.meshgrid(x, v) result = f(x, v) scale = np.sqrt(1 / (v ** 2 + result ** 2)) plt.quiver(x, v, v * scale, result * scale) plt.show()
def twoVectors(sigma = 0.2): # figH = 18 figW = 13 bottom = [0.68,0.35,0.02] height = 0.3 left = [0.07,0.56] width = 0.4 FS = 42 FS2 = 32 scal = 25. # dx = 0.05 x = np.arange(-1,1+dx,dx) y = np.arange(-1,1+dx,dx) X,Y = np.meshgrid(x,y) Xs = np.reshape(X,[X.size]) Ys = np.reshape(Y,[Y.size]) # observation 1, at origin xo1 = 0. yo1 = 0. uo1 = 1. vo1 = 0. # observation 2, varying direction, intensity and location # xo2 = np.array([0.07,0.14,0.28]) # yo2 = np.array([0.07,0.14,0.28]) xo2 = np.array([0.07,0.28]) yo2 = np.array([0.07,0.28]) angle = np.array([45,90,180]) absVel = np.array([0.5,1,2]) # for i in range(angle.size): fig = pl.figure(figsize=(figW,figH)) jk=1 filename = 'plots/2_vectors_angle_'+str(angle[i])+'.png' for j in range(absVel.size): uo2 = absVel[j]*np.cos(np.deg2rad(angle[i])) vo2 = absVel[j]*np.sin(np.deg2rad(angle[i])) uo = np.array([uo1,uo2]) vo = np.array([vo1,vo2]) ob = np.concatenate([uo,vo]) ob = np.reshape(ob,[ob.size,1]) for k in range(xo2.size): xo = np.array([xo1,xo2[k]]) yo = np.array([yo1,yo2[k]]) # compute kernel K = compute_K(xo,yo,sigma) Ki = np.linalg.inv(K) Ks = compute_Ks(xo,yo,Xs,Ys,sigma) f = getMean(Ks,Ki,ob) uf = np.reshape(f[:f.size/2],[y.size,-1]) vf = np.reshape(f[f.size/2:],[y.size,-1]) # plot print jk print i,j,k # plot = fig.add_subplot(3,3,jk) plot=fig.add_axes([left[k],bottom[j],width,height]) plot.quiver(X,Y,uf,vf,scale=scal) pl.quiver(xo,yo,uo,vo,scale=scal,color='r') plot.set_xlim([-0.6,0.8]) plot.set_ylim([-0.6,0.8]) plot.set_xticks([-0.6,-0.3,0.,0.3,0.6]) plot.set_yticks([-0.5,-0.2,0.1,0.4,0.7]) # titleText = plot.text(0.7, 1.05, '',transform=plot.transAxes, # fontsize=FS,fontweight='bold') titleText1 = plot.text(0.05, 0.9, '',transform=plot.transAxes, fontsize=FS2,fontweight='bold',color='b') titleText2 = plot.text(0.03, 0.03, '',transform=plot.transAxes, fontsize=FS2,fontweight='bold',color='b') titleText3 = plot.text(0.7, 0.03, '',transform=plot.transAxes, fontsize=FS2,fontweight='bold',color='b') titleText3.set_text('$\Theta='+str(angle[i])+'$') titleText2.set_text('$|v_2|='+str(absVel[j])+'$') dx2= np.round(np.sqrt(np.square(xo1-xo2[k])+np.square(yo1-yo2[k])),decimals=2) titleText1.set_text('$|x_2-x_1|='+str(dx2)+'$') plot.tick_params(axis='both',which='major',labelsize=FS2) jk+=1 pl.savefig(filename, bbox_inches=0)
def mag_forces(*args,**kwargs): Tool = plp.Tools() Fc = jana.Force() I = plp.Image() D = args[0] #Lorentz_Force_Dict = Fc.Lorentz(D) StForce_Dict = Fc.Pressure(D) Flr = StForce_Dict['Fp_r'] Flz = StForce_Dict['Fp_z'] #Flr = Lorentz_Force_Dict['Fl_r'] #Flz = Lorentz_Force_Dict['Fl_z'] spx= kwargs.get('spacingx',40) spy= kwargs.get('spacingx',80) nxr = D.n1/spx nyr = D.n2/spy nshape = ([nxr,nyr]) b1new = Tool.congrid(D.b1,nshape) b2new = Tool.congrid(D.b2,nshape) x1new = Tool.congrid(D.x1,([nxr])) x2new = Tool.congrid(D.x2,([nyr])) Flr_p = Tool.congrid(Flr,nshape) Flz_p = Tool.congrid(Flz,nshape) magpol_p = np.sqrt(Flr_p*Flr_p + Flz_p*Flz_p) #plt.quiver(x1new,x2new,(Flr_p/magpol_p).T,(Flz_p/magpol_p).T,color=kwargs.get('color','k'),headwidth=kwargs.get('hw',3)) #FOR THE PARALLEL FORCES WE HAVE TO PROJECT THE Fl TO THE Bp if kwargs.get('Para',False)==True: phi = np.arctan2(b2new,b1new) f2 = plt.figure(num=2) theta = np.zeros(phi.shape) alpha = np.arctan2(Flz_p,Flr_p) for i in range(phi.shape[0]): for j in range(phi.shape[1]): if (alpha[i,j] > phi[i,j]): theta[i,j] = (alpha[i,j] - phi[i,j]) else: theta[i,j] = 2.0*np.pi + (alpha[i,j] - phi[i,j]) magFlpara = magpol_p*np.cos(theta) Flpara_r_p = magFlpara*np.cos(phi) Flpara_z_p = magFlpara*np.sin(phi) magFlpara_p = np.sqrt(Flpara_r_p*Flpara_r_p + Flpara_z_p*Flpara_z_p) f1 = plt.figure(num=1) ax1 = f1.add_subplot(111) ax1.set_aspect(1.0) plt.quiver(x1new,x2new,(Flpara_r_p/magFlpara_p).T,(Flpara_z_p/magFlpara_p).T,color=kwargs.get('color','k'),headwidth=kwargs.get('hw',5),width=kwargs.get('width',0.001),scale_units='xy') I.myfieldlines(D,[3.0,6.0,10.0,15.0],[0.01,0.01,0.01,0.01],stream=True,colors='k') #FOR THE PERPENDICULAR FORCES WE HAVE TO PROJECT THE Fl TO THE Bp if kwargs.get('Perp',False)==True: phi = np.arctan2(b2new,b1new) theta = np.zeros(phi.shape) Flper_r_p=np.zeros(phi.shape) Flper_z_p=np.zeros(phi.shape) magFlper=np.zeros(phi.shape) alpha = np.arctan2(Flz_p,Flr_p) for i in range(phi.shape[0]): for j in range(phi.shape[1]): if (alpha[i,j] > phi[i,j]): theta[i,j] = (alpha[i,j] - phi[i,j]) magFlper[i,j] = magpol_p[i,j]*np.sin(theta[i,j]) Flper_r_p[i,j] = -1.0*magFlper[i,j]*np.sin(phi[i,j]) Flper_z_p[i,j] = magFlper[i,j]*np.cos(phi[i,j]) else: theta[i,j] = 2.0*np.pi + (alpha[i,j] - phi[i,j]) magFlper[i,j] = magpol_p[i,j]*np.sin(theta[i,j]) Flper_r_p[i,j] = -1.0*magFlper[i,j]*np.sin(phi[i,j]) Flper_z_p[i,j] = magFlper[i,j]*np.cos(phi[i,j]) magFlper_p = np.sqrt(Flper_r_p*Flper_r_p + Flper_z_p*Flper_z_p) f1 = plt.figure(num=1) ax2 = f1.add_subplot(111) ax2.set_aspect(1.0) plt.quiver(x1new,x2new,(Flper_r_p/magFlper_p).T,(Flper_z_p/magFlper_p).T,color=kwargs.get('color','k'),headwidth=kwargs.get('hw',5),width=kwargs.get('width',0.001),scale_units='xy') I.myfieldlines(D,[3.0,6.0,10.0,15.0],[0.01,0.01,0.01,0.01],stream=True,colors='k')