def f(x, interp_mode): xgr = xg.ravel() ygr = yg.ravel() if interp_mode == 'linear': interp = LinearTriInterpolator(triang, x) else: interp = CubicTriInterpolator(triang, x) return interp(xgr, ygr).reshape(grid_pts)
def plot_GRAD(UC, nodes, elements, Ngra, plt_type="contourf", levels=12, savefigs=False, title="Solution:"): """Plots the gradient of a user defined scalar field using triangulation. Parameters ---------- UC : ndarray (float) Array with the scalar field. nodes : ndarray (float) Array with number and nodes coordinates: `number coordX coordY` elements : ndarray (int) Array with the node number for the nodes that correspond to each element. """ tri = mesh2tri(nodes, elements) tcu = CubicTriInterpolator(tri, UC) (DuDx, DuDy) = tcu.gradient(tri.x, tri.y) tri_plot(tri, DuDx, Ngra, title=r'$\frac{{\partial }}{{\partial x}}$', figtitle="x gradient", levels=levels, plt_type=plt_type, savefigs=savefigs, filename="dudx.pdf") tri_plot(tri, DuDy, Ngra, title=r'$\frac{{\partial }}{{\partial y}}$', figtitle="y gradient", levels=levels, plt_type=plt_type, savefigs=savefigs, filename="dudy.pdf") return DuDx, DuDy
def _setup_Te_interpolator(self, kind='linear'): """setup interpolator for measured Te :param string kind: default is 'linear', can be 'cubic' or 'linear' """ self._Delaunay = Delaunay(self._points) self._triangulation = triangulation.Triangulation( self._Y, self._X, triangles=self._Delaunay.simplices) self._trifinder = DelaunayTriFinder(self._Delaunay, self._triangulation) if kind == 'linear': self._kind = kind self._Te_interpolator = LinearTriInterpolator( self._triangulation, self._Te, trifinder=self._trifinder) elif kind == 'cubic': self._kind = kind self._Te_interpolator = CubicTriInterpolator( self._triangulation, self._Te, trifinder=self._trifinder) else: raise ValueError('Wrong kind of interpolation: {0}. Available \ options are "linear" and "cubic".'.format(kind))
def __draw_plot(self): freqCentre = self.spinCentre.GetValue() freqBw = self.spinBw.GetValue() freqMin = (freqCentre - freqBw) / 1000. freqMax = (freqCentre + freqBw) / 1000. coords = {} for timeStamp in self.spectrum: spectrum = self.spectrum[timeStamp] sweep = [ yv for xv, yv in spectrum.items() if freqMin <= xv <= freqMax ] if len(sweep): peak = max(sweep) try: location = self.location[timeStamp] except KeyError: continue coord = tuple(location[0:2]) if coord not in coords: coords[coord] = peak else: coords[coord] = (coords[coord] + peak) / 2 x = [] y = [] z = [] for coord, peak in coords.items(): x.append(coord[1]) y.append(coord[0]) z.append(peak) self.extent = (min(x), max(x), min(y), max(y)) self.xyz = (x, y, z) xi, yi = numpy.meshgrid( numpy.linspace(min(x), max(x), self.IMAGE_SIZE), numpy.linspace(min(y), max(y), self.IMAGE_SIZE)) if self.plotMesh or self.plotCont: triangle = Triangulation(x, y) interp = CubicTriInterpolator(triangle, z, kind='geom') zi = interp(xi, yi) if self.plotMesh: self.plot = self.axes.pcolormesh(xi, yi, zi, cmap=self.colourMap) self.plot.set_zorder(1) if self.plotCont: contours = self.axes.contour(xi, yi, zi, linewidths=0.5, colors='k') self.axes.clabel(contours, inline=1, fontsize='x-small', gid='clabel', zorder=3) if self.plotHeat: image = create_heatmap(x, y, self.IMAGE_SIZE, self.IMAGE_SIZE / 10, self.colourHeat) heatMap = self.axes.imshow(image, aspect='auto', extent=self.extent) heatMap.set_zorder(2) if self.plotPoint: self.axes.plot(x, y, 'wo') for posX, posY, posZ in zip(x, y, z): points = self.axes.annotate('{0:.2f}dB'.format(posZ), xy=(posX, posY), xytext=(-5, 5), ha='right', textcoords='offset points') points.set_zorder(3) if matplotlib.__version__ >= '1.3': effect = patheffects.withStroke(linewidth=2, foreground="w", alpha=0.75) for child in self.axes.get_children(): child.set_path_effects([effect]) if self.plotAxes: self.axes.set_axis_on() else: self.axes.set_axis_off() self.canvas.draw()
# Mask off unwanted triangles. triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius) #----------------------------------------------------------------------------- # Refine data - interpolates the electrical potential V #----------------------------------------------------------------------------- refiner = UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3) #----------------------------------------------------------------------------- # Computes the electrical field (Ex, Ey) as gradient of electrical potential #----------------------------------------------------------------------------- tci = CubicTriInterpolator(triang, -V) # Gradient requested here at the mesh nodes but could be anywhere else: (Ex, Ey) = tci.gradient(triang.x, triang.y) E_norm = np.sqrt(Ex**2 + Ey**2) #----------------------------------------------------------------------------- # Plot the triangulation, the potential iso-contours and the vector field #----------------------------------------------------------------------------- fig, ax = plt.subplots() ax.set_aspect('equal') # Enforce the margins, and enlarge them to give room for the vectors. ax.use_sticky_edges = False ax.margins(0.07) ax.triplot(triang, color='0.8')
# Mask off unwanted triangles. triang.set_mask( np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean( axis=1)) < min_radius) #----------------------------------------------------------------------------- # Refine data - interpolates the electrical potential V #----------------------------------------------------------------------------- refiner = UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3) #----------------------------------------------------------------------------- # Computes the electrical field (Ex, Ey) as gradient of electrical potential #----------------------------------------------------------------------------- tci = CubicTriInterpolator(triang, -V) # Gradient requested here at the mesh nodes but could be anywhere else: (Ex, Ey) = tci.gradient(triang.x, triang.y) E_norm = np.sqrt(Ex**2 + Ey**2) #----------------------------------------------------------------------------- # Plot the triangulation, the potential iso-contours and the vector field #----------------------------------------------------------------------------- fig, ax = plt.subplots() ax.set_aspect('equal') # Enforce the margins, and enlarge them to give room for the vectors. ax.use_sticky_edges = False ax.margins(0.07) ax.triplot(triang, color='0.8')
def spatial_autocorr_fft(tri, U, V, N_grid=512, auto=False, transform=False, tree=None, interp='Lanczos'): """ Function to estimate autocorrelation from a single increment in cartesian coordinates(tau, eta) Input: ----- tri - Delaunay triangulation object of unstructured grid. N_grid - Squared, structured grid resolution to apply FFT. U, V - Arrays with cartesian components of wind speed. Output: ------ r_u,r_v - 2D arrays with autocorrelation function rho(tau,eta) for U and V, respectively. """ if transform: U_mean = avetriangles(np.c_[tri.x, tri.y], U, tri) V_mean = avetriangles(np.c_[tri.x, tri.y], V, tri) # Wind direction gamma = np.arctan2(V_mean, U_mean) # Components in matrix of coefficients S11 = np.cos(gamma) S12 = np.sin(gamma) T = np.array([[S11, S12], [-S12, S11]]) vel = np.array(np.c_[U, V]).T vel = np.dot(T, vel) X = np.array(np.c_[tri.x, tri.y]).T X = np.dot(T, X) U = vel[0, :] V = vel[1, :] tri = Triangulation(X[0, :], X[1, :]) mask = TriAnalyzer(tri).get_flat_tri_mask(.05) tri = Triangulation(tri.x, tri.y, triangles=tri.triangles[~mask]) U_mean = avetriangles(np.c_[tri.x, tri.y], U, tri) V_mean = avetriangles(np.c_[tri.x, tri.y], V, tri) else: # Demeaning U_mean = avetriangles(np.c_[tri.x, tri.y], U, tri) V_mean = avetriangles(np.c_[tri.x, tri.y], V, tri) grid = np.meshgrid(np.linspace(np.min(tri.x), np.max(tri.x), N_grid), np.linspace(np.min(tri.y), np.max(tri.y), N_grid)) U = U - U_mean V = V - V_mean # Interpolated values of wind field to a squared structured grid if interp == 'cubic': U_int = CubicTriInterpolator(tri, U)(grid[0].flatten(), grid[1].flatten()).data V_int = CubicTriInterpolator(tri, V)(grid[0].flatten(), grid[1].flatten()).data U_int = np.reshape(U_int, grid[0].shape) V_int = np.reshape(V_int, grid[0].shape) else: # U_int= lanczos_int_sq(grid,tree,U) # V_int= lanczos_int_sq(grid,tree,V) U_int = LinearTriInterpolator(tri, U)(grid[0].flatten(), grid[1].flatten()).data V_int = LinearTriInterpolator(tri, V)(grid[0].flatten(), grid[1].flatten()).data U_int = np.reshape(U_int, grid[0].shape) V_int = np.reshape(V_int, grid[0].shape) #zero padding U_int[np.isnan(U_int)] = 0.0 V_int[np.isnan(V_int)] = 0.0 fftU = np.fft.fft2(U_int) fftV = np.fft.fft2(V_int) if auto: # Autocorrelation r_u = np.real(np.fft.fftshift(np.fft.ifft2(np.absolute(fftU)** 2))) / len(U_int.flatten()) r_v = np.real(np.fft.fftshift(np.fft.ifft2(np.absolute(fftV)** 2))) / len(U_int.flatten()) r_uv = np.real( np.fft.fftshift(np.fft.ifft2(np.real( fftU * np.conj(fftV))))) / len(U_int.flatten()) dx = np.max(np.diff(grid[0].flatten())) dy = np.max(np.diff(grid[1].flatten())) n = grid[0].shape[0] m = grid[1].shape[0] # Spectra fftU = np.fft.fftshift(fftU) fftV = np.fft.fftshift(fftV) fftUV = fftU * np.conj(fftV) Suu = 2 * (np.abs(fftU)**2) * (dx * dy) / (n * m) Svv = 2 * (np.abs(fftV)**2) * (dx * dy) / (n * m) Suv = 2 * np.real(fftUV) * (dx * dy) / (n * m) k1 = np.fft.fftshift((np.fft.fftfreq(n, d=dx))) k2 = np.fft.fftshift((np.fft.fftfreq(m, d=dy))) if auto: return (r_u, r_v, r_uv, Suu, Svv, Suv, k1, k2) else: return (Suu, Svv, Suv, k1, k2)
for line in open('data.1'): row = line.strip().split(" ") x.append(float(row[0])) y.append(float(row[1])) for line in open('data.2'): row = line.strip().split(" ") v.append(float(row[0])) for line in open('data.3'): row = line.strip().split(" ") m.append([int(row[0]) - 1, int(row[1]) - 1, int(row[2]) - 1]) triangles = Triangulation(x, y, m) tci = CubicTriInterpolator(triangles, -numpy.array(v)) (u, v) = tci.gradient(triangles.x, triangles.y) v_norm = numpy.sqrt(u**2, v**2) fig, ax = plt.subplots() ax.set_aspect('equal') ax.use_sticky_edges = False ax.margins(0.07) ax.triplot(triangles, color='0.8', lw=0.5) #tcf = ax.tricontourf(triangles, -numpy.array(v)); #fig.colorbar(tcf); ax.quiver(triangles.x, triangles.y, u / v_norm, v / v_norm, color='blue') plt.savefig('1.svg')