Esempio n. 1
0
 def generate_offset_map(self, source, target):
     anchor_pts = [[0, 0], [0, 256], [256, 0], [256, 256], [0, 128],
                   [128, 0], [256, 128], [128, 256], [0, 64], [0, 192],
                   [256, 64], [256, 192], [64, 0], [192, 0], [64, 256],
                   [192, 256]]
     anchor_pts = np.asarray(anchor_pts) / 256
     # print(f"shape of spoof: {source.shape}, shape of live: {target.shape}")
     # print(f"shape of anch: {anchor_pts.shape}")
     xi, yi = np.meshgrid(np.linspace(0, 1, 256), np.linspace(0, 1, 256))
     # print(f"shape of xi: {xi.shape}, shape of yi: {yi.shape}")
     _source = np.concatenate([source, anchor_pts],
                              axis=0).astype(np.float32)
     _target = np.concatenate([target, anchor_pts],
                              axis=0).astype(np.float32)
     # print(f"shape of spoof after meshgrid: {_source.shape}, shape of live: {_target.shape}")
     _offset = _source - _target
     # print(f"shape of offset: {_offset.shape}")
     # interp2d
     _triang = mtri.Triangulation(_target[:, 0], _target[:, 1])
     # print(f"after triangulation: {_triang}")
     _interpx = mtri.LinearTriInterpolator(_triang, _offset[:, 0])
     _interpy = mtri.LinearTriInterpolator(_triang, _offset[:, 1])
     # print(f"shapes interps: {_interpx}, {_interpy}")
     _offsetmapx = _interpx(xi, yi)
     _offsetmapy = _interpy(xi, yi)
     # print(f"x, y offset: {_offsetmapx.shape}, {_offsetmapy.shape}")
     offsetmap = np.stack([_offsetmapy, _offsetmapx, _offsetmapx * 0],
                          axis=2)
     # print(f"final offsetmap: {offsetmap.shape}")
     return offsetmap
Esempio n. 2
0
 def addInterpolator(self, interpolation='cubic', kind='geom'):
     '''
     Add interpolator Object to the vector field.
     
     Arguments:
         *interpolation: string. 'cubic' or 'linear'
     '''
     self.interType = interpolation
     self.interKind = kind
     if self.interType == 'cubic':
         self.vx_i = tri.CubicTriInterpolator(self.triangulation,
                                              self.vx,
                                              kind=self.interKind)
         self.vy_i = tri.CubicTriInterpolator(self.triangulation,
                                              self.vy,
                                              kind=self.interKind)
         self.vz_i = tri.CubicTriInterpolator(self.triangulation,
                                              self.vz,
                                              kind=self.interKind)
     elif self.interType == 'linear':
         self.vx_i = tri.LinearTriInterpolator(self.triangulation, self.vx)
         self.vy_i = tri.LinearTriInterpolator(self.triangulation, self.vy)
         self.vz_i = tri.LinearTriInterpolator(self.triangulation, self.vz)
     else:
         raise ValueError('Interpolation must be "cubic" or "linear".')
Esempio n. 3
0
def streamlines(ax, mesh, umean):
    """
    Plot velocity streamlines.  Interpolate data to background Cartesian grid,
    then use matplotlib's ``streamplot()``.
    """
    Nx, Ny = 1001, 401
    xcart = np.linspace(0, 10, Nx)
    ycart = np.linspace(0, 4, Ny)
    meshcart = np.vstack(map(lambda x: x.flatten(), np.meshgrid(xcart,
                                                                ycart))).T
    interp_u = tri.LinearTriInterpolator(mesh, umean[:, 0])
    interp_v = tri.LinearTriInterpolator(mesh, umean[:, 1])
    ucart = interp_u(meshcart[:, 0], meshcart[:, 1])
    vcart = interp_v(meshcart[:, 0], meshcart[:, 1])
    X = meshcart[:, 0].reshape(Ny, Nx)
    Y = meshcart[:, 1].reshape(Ny, Nx)
    U = ucart.reshape(Ny, Nx)
    V = vcart.reshape(Ny, Nx)
    lw = np.sqrt(U**2 + V**2) * 3
    start_points = np.vstack((np.ones(10) * 0.1, np.linspace(1, 3, 10))).T
    ###ax.streamplot(X, Y, U, V, density=.8, color='k', linewidth=1.)
    strm = ax.streamplot(xcart,
                         ycart,
                         U,
                         V,
                         start_points=[[4, 2]],
                         color='k',
                         linewidth=1.)
    for path in strm.lines.get_paths():
        path.vertices
Esempio n. 4
0
def CreateFig(dt_output=0.1):
    from tables import  open_file
    archive = open_file('dambreak.h5','r')
    import dambreak
    dambreak.outputStepping.dt_output=dt_output
    dambreak.outputStepping.nDTout=None
    dambreak.outputStepping.setOutputStepping()
    dambreak.myTpFlowProblem.initializeAll()
    import matplotlib.tri as mtri
    from matplotlib import pyplot as  plt
    import numpy as np
    domain = dambreak.domain
    domain.L = dambreak.tank_dim
    domain.x = (0.,0.,0.)
    nodes = archive.get_node("/nodesSpatial_Domain0")
    x=nodes[:,0]
    y=nodes[:,1]
    elements = archive.get_node("/elementsSpatial_Domain0")
    triang = mtri.Triangulation(x, y, elements)
    xg = np.linspace(0, domain.L[0], 20)
    yg = np.linspace(0, domain.L[1], 20)
    xi, yi = np.meshgrid(xg,yg)
    plt.figure()
    for it,t in enumerate(dambreak.myTpFlowProblem.so.tnList[:]):
        phi = archive.get_node("/phi_t{0:d}".format(it))
        vof = archive.get_node("/vof_t{0:d}".format(it))
        wvof = np.ones(vof.shape,'d')
        wvof -= vof
        u = archive.get_node("/u_t{0:d}".format(it))
        v = archive.get_node("/v_t{0:d}".format(it))
        plt.clf()
        plt.xlabel(r'z[m]')
        plt.ylabel(r'x[m]')
        colors = ['w','b', 'g','r','c','m','y','k']*(max(domain.segmentFlags)//8 + 1)
        plt.xlim(domain.x[0]-0.1*domain.L[0],domain.x[0]+domain.L[0]+0.1*domain.L[0])    
        for si,s in enumerate(domain.segments):
            plt.plot([domain.vertices[s[0]][0],
                     domain.vertices[s[1]][0]],
                    [domain.vertices[s[0]][1],
                     domain.vertices[s[1]][1]],
                    color=colors[domain.segmentFlags[si]-1],
                    linewidth=2,
                    marker='o')
        plt.tricontourf(x,y,elements,wvof*np.sqrt(u[:]**2 + v[:]**2))
        plt.tricontour(x,y,elements,phi,[0], linewidths=4)
        u_interp_lin = mtri.LinearTriInterpolator(triang, u[:])
        v_interp_lin = mtri.LinearTriInterpolator(triang, v[:])
        u_lin = u_interp_lin(xi, yi)
        v_lin = v_interp_lin(xi, yi)
        plt.streamplot(xg, yg, u_lin, v_lin,color='k')
        plt.title('T={0:2.2f}'.format(t))
        plt.axis('equal')
        plt.xlim((0,domain.L[0]))
        plt.savefig('phi{0:04d}.png'.format(it))
Esempio n. 5
0
def extract(var,triangles,sol):
    s = sol[var][1:]
    unit = sol[var][0]
    mask = triangles.mask
    triangles.set_mask(mask=None)
    if(unit=='cm^{-3}' and var != 'Net_Doping'):
        f = np.vectorize(mtri.LinearTriInterpolator(triangles,np.log(s)))
        def g(x,y):
            return np.exp(f(x,y))
        return s,g
    f = mtri.LinearTriInterpolator(triangles,s)
    triangles.set_mask(mask=mask)
    return np.array(s),np.vectorize(f)
Esempio n. 6
0
def CreateFig():
    from tables import  openFile
    archive = openFile('linear_waves.h5','r')
    import linear_waves
    import linear_waves_so
    import matplotlib.tri as mtri
    from matplotlib import pyplot as  plt
    import numpy as np
    domain = linear_waves.domain
    nodes = archive.getNode("/nodesSpatial_Domain0")
    x=nodes[:,0]
    y=nodes[:,1]
    elements = archive.getNode("/elementsSpatial_Domain0")
    triang = mtri.Triangulation(x, y, elements)
    domain.L=linear_waves.tank_dim
    domain.x=[0.,0.]
    xg = np.linspace(0, domain.L[0], 20)
    yg = np.linspace(0, domain.L[1], 20)
    xi, yi = np.meshgrid(xg,yg)
    plt.figure()
    for it,t in enumerate(linear_waves_so.tnList[:]):
        phi = archive.getNode("/phi_t"+`it`)
        vof = archive.getNode("/vof_t"+`it`)
        wvof = np.ones(vof.shape,'d')
        wvof -= vof
        u = archive.getNode("/u_t"+`it`)
        v = archive.getNode("/v_t"+`it`)
        plt.clf()
        plt.xlabel(r'z[m]')
        plt.ylabel(r'x[m]')
        colors = ['b','g','r','c','m','y','k','w']
        plt.xlim(domain.x[0]-0.1*domain.L[0],domain.x[0]+domain.L[0]+0.1*domain.L[0])    
        for si,s in enumerate(domain.segments):
            plt.plot([domain.vertices[s[0]][0],
                     domain.vertices[s[1]][0]],
                    [domain.vertices[s[0]][1],
                     domain.vertices[s[1]][1]],
                    color=colors[domain.segmentFlags[si]-1],
                    linewidth=2,
                    marker='o')
        plt.tricontourf(x,y,elements,wvof*np.sqrt(u[:]**2 + v[:]**2))
        plt.tricontour(x,y,elements,phi,[0], linewidth=4)
        u_interp_lin = mtri.LinearTriInterpolator(triang, u[:])
        v_interp_lin = mtri.LinearTriInterpolator(triang, v[:])
        u_lin = u_interp_lin(xi, yi)
        v_lin = v_interp_lin(xi, yi)
        plt.streamplot(xg, yg, u_lin, v_lin,color='k')
        plt.title('T=%2.2f' % (t,))
        plt.xlim((0,domain.L[0]))
        plt.ylim(0,domain.L[1])
        plt.savefig('phi%4.4d.png' % (it,))
Esempio n. 7
0
def setup(ds, whichgrids=None):
    '''Set up for using ll2xe().
    
    Set up Delaunay triangulation by calculating triangulation and functions for 
    calculating grid coords from lon/lat pairs and save into and return ds object.
    
    Create a separate triangulation setup for each grid since otherwise it impacts 
    the performance, especially at edges. Can input keyword whichgrids to only 
    calculate for particular grids — this is intended for testing purposes to save time.
    
    Usage is demonstrated in ll2xe().
    '''    
    tris = {}
    # Set up Delaunay triangulation of grid space in lon/lat coordinates
    
    if whichgrids is None:
        whichgrids = ['rho', 'u', 'v', 'psi']
        
    for whichgrid in whichgrids:
        lonkey = 'lon_' + whichgrid
        latkey = 'lat_' + whichgrid

        # Triangulation for curvilinear space to grid space
        # Have to use SciPy's Triangulation to be more robust.
        # http://matveichev.blogspot.com/2014/02/matplotlibs-tricontour-interesting.html
        lon = ds[lonkey].values.flatten()
        lat = ds[latkey].values.flatten()
        pts = np.column_stack((lon, lat))
        tess = Delaunay(pts)
        tri = mtri.Triangulation(lon, lat, tess.simplices.copy())
        # For the triangulation, need to preprocess the mask to get rid of potential 
        # flat triangles at the boundaries.
        # http://matplotlib.org/1.3.1/api/tri_api.html#matplotlib.tri.TriAnalyzer
        mask = mtri.TriAnalyzer(tri).get_flat_tri_mask(0.01, rescale=False)
        tri.set_mask(mask)

        # Next set up the grid (or index) space grids: integer arrays that are the
        # shape of the horizontal model grid.
        J, I = ds[lonkey].shape
        X, Y = np.meshgrid(np.arange(I), np.arange(J))

        # these are the functions for interpolating X and Y (the grid arrays) onto
        # lon/lat coordinates. That is, the functions for calculating grid space coords
        # corresponding to input lon/lat coordinates.
        fx = mtri.LinearTriInterpolator(tri, X.flatten())
        fy = mtri.LinearTriInterpolator(tri, Y.flatten())

        tris[whichgrid] = {'name': whichgrid, 'tri': tri, 'fx': fx, 'fy': fy}
    
    return tris
Esempio n. 8
0
    def get_data_on_vertical_segment(self, var_name, record, point):
        """
        Extract values for each plane of a 2d points in telemac-3d result file
        for the given variable

        @param point (numpy.array) Point of extraction
        @param varname (string) Name of variable for which to extract data
        @param record (int) Number of desired record

        @returns (numpy.array)

        """
        if self.get_mesh_dimension() != 3:
            raise TelemacException("Action possible only on 3d mesh")

        if len(point) != 2:
            raise TelemacException('Warning the extraction point '\
                                   'must be 2d')
        nplan = self.nplan
        res = np.zeros(nplan)
        for plan in range(self.nplan):
            values = self.get_data_on_horizontal_plane(\
                               var_name, record, plan)
            data_interp = mtri.LinearTriInterpolator(self.tri, values)
            res[plan] = data_interp(point[0], point[1])
        return res
Esempio n. 9
0
  def visualize_wafer(mini_wafer_map):
    
    # Interpolation 실행
    data = mini_wafer_map
    x = data['x'].tolist()
    y = data['y'].tolist()
    value = data['value'].tolist()
    
    xx = np.array(x)
    yy = np.array(y)
    zz = np.array(value)
    
    npts = len(xx)            # 현재 PT 개수 (490개)
    ngridx, ngridy = 300,300  # 보간하고자 하는 PT 개수
    
    # Create grid values first.
    xi = np.linspace(-137, 137, ngridx)
    yi = np.linspace(-137, 137, ngridy)
    
    # Linearly interpolate the data (x, y) on a grid defined by (xi, yi).
    triang = tri.Triangulation(xx, yy)
    interpolator = tri.LinearTriInterpolator(triang, zz)  # LinearTriInterpolator
    Xi, Yi = np.meshgrid(xi, yi)
    zi = interpolator(Xi, Yi)
    
    fig = plt.figure(figsize = (10,10))
    ax = plt.axes(projection='3d')
    ax.axes.set_zlim3d(bottom=40000, top=50000) 
    contour = ax.contour3D(Xi, Yi, zi,levels = 100, cmap='jet')
    ax.view_init(35, 50)  # 보는 각도 변경

    fig.colorbar(contour, shrink=0.5, aspect=5)
    
    fig.savefig("3d graph.png")
Esempio n. 10
0
    def interpolate(self, z, x, y, kind='linear'):
        """
        Interpolate data in 'z' on current grid onto points 'x' and 'y'

        kind = 'linear', 'cubic', 'barycentric' (default), 'nearest'
        """
        if kind == 'linear':
            self.build_tri_voronoi()
            F = tri.LinearTriInterpolator(self._triv, z)
            return F(x, y)

        elif kind == 'cubic':
            self.build_tri_voronoi()
            F = tri.CubicTriInterpolator(self._triv, z)
            return F(x, y)

        elif kind == 'barycentric':
            self.build_tri_voronoi()
            xyin = np.vstack([self.xv, self.yv]).T
            xyout = np.vstack([x, y]).T
            F = BarycentricInterp(xyin, xyout)
            return F(z)

        elif kind == 'nearest':
            if isinstance(x, float):
                dist, idx = self.find_nearest([x, y])
                return z[idx]
            elif isinstance(x, np.ndarray):
                sz = x.shape
                xy = np.array([x.ravel(), y.ravel()]).T
                dist, idx = self.find_nearest(xy)
                return z[idx].reshape(sz)
Esempio n. 11
0
def PlotADCP(ax,atd,depths,V,levels=levels,levels2=levels2,cmap=cmap,norm=norm):
    """
    Still unfinished with flexibility of reg and filt
    TODO adapt to filtered and regular data
    Returns km
    levels can be
    """
    X = []
    Z = []
    for i in range(len(atd)):
        for j in range(len(depths)):
            X.append(atd[i])
            Z.append(depths[j])
    X = np.array(X)
    Z = np.array(Z)
    Vf = V.flatten()
    # Regular grid
    xi = np.linspace(min(atd),max(atd), len(atd))
    zi = np.linspace(min(depths), max(depths), len(depths))
    # Perform linear interpolation of the data (x,y)
    # on a grid defined by (xi,yi)
    triang = tri.Triangulation(X, Z)
    interpolator = tri.LinearTriInterpolator(triang, Vf)
    Xi, Zi = np.meshgrid(xi, zi)
    Vi = interpolator(Xi, Zi)
    ax.contourf(Xi,Zi,Vi,levels=levels,cmap=cmap,norm=norm)
    cont = ax.contour(Xi,Zi,Vi,levels = levels2,linewidths=0.5,colors='black',linestyles='dashed')
    ax.clabel(cont,cont.levels,fmt='%1.2f',fontsize=8, inline=1,colors='k')
    lvl0 = [0]
    ax.contour(Xi,Zi,Vi,levels=lvl0,colors='black',linewidths=2)
Esempio n. 12
0
def test_triinterp_colinear():
    # Tests interpolating inside a triangulation with horizontal colinear
    # points (refer also to the tests :func:`test_trifinder` ).
    #
    # These are not valid triangulations, but we try to deal with the
    # simplest violations (i. e. those handled by default TriFinder).
    #
    # Note that the LinearTriInterpolator and the CubicTriInterpolator with
    # kind='min_E' or 'geom' still pass a linear patch test.
    # We also test interpolation inside a  flat triangle, by forcing
    # *tri_index* in a call to :meth:`_interpolate_multikeys`.

    delta = 0.  # If +ve, triangulation is OK, if -ve triangulation invalid,
    # if zero have colinear points but should pass tests anyway.
    x0 = np.array([1.5, 0, 1, 2, 3, 1.5, 1.5])
    y0 = np.array([-1, 0, 0, 0, 0, delta, 1])

    # We test different affine transformations of the initial figure ; to
    # avoid issues related to round-off errors we only use integer
    # coefficients (otherwise the Triangulation might become invalid even with
    # delta == 0).
    transformations = [[1, 0], [0, 1], [1, 1], [1, 2], [-2, -1], [-2, 1]]
    for transformation in transformations:
        x_rot = transformation[0] * x0 + transformation[1] * y0
        y_rot = -transformation[1] * x0 + transformation[0] * y0
        (x, y) = (x_rot, y_rot)
        z = 1.23 * x - 4.79 * y
        triangles = [[0, 2, 1], [0, 3, 2], [0, 4, 3], [1, 2, 5], [2, 3, 5],
                     [3, 4, 5], [1, 5, 6], [4, 6, 5]]
        triang = mtri.Triangulation(x, y, triangles)
        xs = np.linspace(np.min(triang.x), np.max(triang.x), 20)
        ys = np.linspace(np.min(triang.y), np.max(triang.y), 20)
        xs, ys = np.meshgrid(xs, ys)
        xs = xs.ravel()
        ys = ys.ravel()
        mask_out = (triang.get_trifinder()(xs, ys) == -1)
        zs_target = np.ma.array(1.23 * xs - 4.79 * ys, mask=mask_out)

        linear_interp = mtri.LinearTriInterpolator(triang, z)
        cubic_min_E = mtri.CubicTriInterpolator(triang, z)
        cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')

        for interp in (linear_interp, cubic_min_E, cubic_geom):
            zs = interp(xs, ys)
            assert_array_almost_equal(zs_target, zs)

        # Testing interpolation inside the flat triangle number 4: [2, 3, 5]
        # by imposing *tri_index* in a call to :meth:`_interpolate_multikeys`
        itri = 4
        pt1 = triang.triangles[itri, 0]
        pt2 = triang.triangles[itri, 1]
        xs = np.linspace(triang.x[pt1], triang.x[pt2], 10)
        ys = np.linspace(triang.y[pt1], triang.y[pt2], 10)
        zs_target = 1.23 * xs - 4.79 * ys
        for interp in (linear_interp, cubic_min_E, cubic_geom):
            zs, = interp._interpolate_multikeys(xs,
                                                ys,
                                                tri_index=itri *
                                                np.ones(10, dtype=np.int32))
            assert_array_almost_equal(zs_target, zs)
Esempio n. 13
0
    def interpolate_mesh_on_points(self, points, values):
        """

        Interpolate mesh on points given value

        @param points (list) List og points for which to interpolate
        @param values (np.darray) values for each mesh points
        @param method (string) Interpolation methof to use

        """
        if self.interp_method == "scipy.LinearND":
            grid_pt = np.column_stack(
                (self.meshx[:self.npoin2], self.meshy[:self.npoin2]))
            data_interp = interpolate.LinearNDInterpolator(grid_pt, values)
            pts = np.asarray([(pt[0], pt[1]) for pt in points])
            res = data_interp(pts)
        elif self.interp_method == "matplotlib.LinearTri":
            data_interp = mtri.LinearTriInterpolator(self.tri, values)
            pt_x = [pt[0] for pt in points]
            pt_y = [pt[1] for pt in points]
            res = data_interp(pt_x, pt_y)
        else:
            raise TelemacException(\
               "Unknown interpolation method: {}\n"
               "Avaialable methods: matplotlib.LinearTri, scipy.LinearND"\
               .format(self.interp_method))

        return res
Esempio n. 14
0
def add_bands_surface_plot(axes3d: Axes3D,
                           kpoints: numpy.ndarray,
                           eigenvalues: numpy.ndarray,
                           axis: int,
                           layer: int,
                           resolution: int,
                           band_indices: Union[List[int], range,
                                               numpy.ndarray],
                           offset: Union[List[float], numpy.ndarray] = None):
    x, y, zs = get_x_y_zs(kpoints, eigenvalues, axis, layer)
    if offset is not None:
        x += offset[0]
        y += offset[1]
        zs += offset[2]
    triang = tri.Triangulation(x, y)

    x_linspace = numpy.linspace(min(x), max(x), resolution)
    y_linspace = numpy.linspace(min(y), max(y), resolution)

    for b in band_indices:
        interpolator = tri.LinearTriInterpolator(triang, zs[:, b])
        x_meshgrid, y_meshgrid = numpy.meshgrid(x_linspace, y_linspace)
        z_mesggrid = interpolator(x_meshgrid, y_meshgrid)
        axes3d.plot_surface(x_meshgrid,
                            y_meshgrid,
                            z_mesggrid,
                            cmap=pyplot.get_cmap("terrain"),
                            vmin=numpy.min(z_mesggrid),
                            vmax=numpy.max(z_mesggrid))
Esempio n. 15
0
def add_bands_wireframe_plot(axes3d: Axes3D,
                             kpoints: numpy.ndarray,
                             eigenvalues: numpy.ndarray,
                             axis: int,
                             layer: int,
                             resolution: int,
                             band_indices: Union[List[int], range,
                                                 numpy.ndarray],
                             offset: Union[List[float], numpy.ndarray] = None):
    x, y, zs = get_x_y_zs(kpoints, eigenvalues, axis, layer)
    if offset is not None:
        x += offset[0]
        y += offset[1]
        zs += offset[2]
    triang = tri.Triangulation(x, y)

    x_linspace = numpy.linspace(min(x), max(x), resolution)
    y_linspace = numpy.linspace(min(y), max(y), resolution)

    b_range = max(band_indices) - min(band_indices) if len(
        band_indices) > 1 else 1
    for b in band_indices:
        interpolator = tri.LinearTriInterpolator(triang, zs[:, b])
        x_meshgrid, y_meshgrid = numpy.meshgrid(x_linspace, y_linspace)
        z_mesggrid = interpolator(x_meshgrid, y_meshgrid)
        color = (max(band_indices) - b) / b_range / 1.5
        axes3d.plot_wireframe(x_meshgrid,
                              y_meshgrid,
                              z_mesggrid,
                              colors=(color, color, color))
Esempio n. 16
0
def interpolate_2D_soln_to_points(physics, x, var, xpoints):
	'''
	This function interpolates a variable to an arbitrary set of points.
	2D only.

	Inputs:
	-------
	    physics: physics object
	    x: xy-coordinates at which variable is already evaluated [num_x, 2]
	    var: values of variable evaluated at x [num_x, 1]
	    xpoints: xy-coordinates to interpolate variable to [num_pts, 2]

	Outputs:
	--------
		var_points: values of variable interpolated to xpoints [num_pts, 2]
		x: xy-coordinates at which variable is already evaluated (duplicates
			removed and reshaped)
	    var: values of variable evaluated at x (duplicates removed and
	    	reshaped)
	'''
	if physics.NDIMS != 2:
		raise ValueError
	tris, utri = triangulate(physics, x, var)
	interpolator = tri.LinearTriInterpolator(tris, utri)

	var_points = interpolator(xpoints[:,0], xpoints[:,1])

	return var_points
Esempio n. 17
0
 def contour(xy, z):
     xi, yi = np.meshgrid(np.linspace(-1, 1, 101), np.linspace(-1, 1, 101))
     triang = tri.Triangulation(xy[:, 0], xy[:, 1])
     interp_lin = tri.LinearTriInterpolator(triang, z.ravel())
     zi = interp_lin(xi, yi)
     plt.contourf(xi, yi, zi, cmap=plt.cm.seismic)
     plt.colorbar()
Esempio n. 18
0
def get_switchline():
    r1s, r2s, phis = [], [], []
    r0s = np.linspace(0.2 * r, 8 * r, 66)
    for r0 in r0s:
        r1l, r1u = (r0 - r) / 2, (r0 + r) / 2
        for r1 in np.linspace(r1l + 0.06, r1u - 0.06, 66):
            r2 = r0 - r1
            if abs((r1**2 + r2**2 - r**2) / (2 * r1 * r2)) < 1:
                r1s.append(r1)
                r2s.append(r2)
                phis.append(get_phi_max(r1, r2)[0])

    r1s = np.asarray(r1s)
    r2s = np.asarray(r2s)
    phis = np.asarray(phis)

    xi, yi = np.linspace(1., 10., 50), np.linspace(1., 10., 50)
    triang = tri.Triangulation(r1s, r2s)
    interpolator = tri.LinearTriInterpolator(triang, phis)
    Xi, Yi = np.meshgrid(xi, yi)
    zi = interpolator(Xi, Yi)

    fig, ax = plt.subplots()
    cs = ax.contour(xi, yi, zi, levels=14, linewidths=2, colors='r')

    line = []
    for p in cs.collections[1].get_paths()[0].vertices:
        if p[0] > r1_min and p[1] > r2_min:
            line.append(p)
            with open('switch.csv', 'a') as f:
                f.write(','.join(list(map(str, p))) + '\n')
    plt.close()

    return np.asarray(line)
Esempio n. 19
0
def process_fenics_function(mesh,fenics_function, x_axis=np.linspace(0,1,100), y_axis=np.linspace(0,1,100)\
                                 ,to_plot=True):
    """
    Method in order to convert fenics functions into np arrays, in order to be able to deal with objects of arbitrary dimension
    the outputs will be masked Fenics Functions. This will only apply to 2D functions that need to be interpolated.
    This is build on top of the matplotlib.tri module and is effective at interpolating from non-uniform meshs.

    Args:
        param1: mesh that the fenics function is defined on
        param2: fenics function that needs to be converted into a
        param3: x_axis (np.array) needs to be a 1-D array which represents the units of the x-axis
        param4: y_axis (np.array) needs to be a 1-D array which represents the units of the y-axis
        param5: to_plot (bool) determines if the image of the interpolated function should be plotted
    Returns:
        Masked Numpy Array with the required eigenfunction
    """
    V = FunctionSpace(mesh, 'CG', 1)
    fenics_function.set_allow_extrapolation(True)
    fenics_function = interpolate(fenics_function, V)

    C = fenics_function.compute_vertex_values(mesh)

    xv, yv = np.meshgrid(x_axis, y_axis)

    test = tri.LinearTriInterpolator(mesh2triang(mesh), C)(xv, yv)

    if to_plot:
        plt.imshow(test, cmap='seismic', origin="lower")
        plt.show()

    return test
Esempio n. 20
0
def plot_tricon(x, y, z):
    ngridx = 41
    ngridy = 41
    xi = np.linspace(-10, 10, ngridx)
    yi = np.linspace(-10, 10, ngridy)

    triang = tri.Triangulation(x, y)
    interpolator = tri.LinearTriInterpolator(triang, z)
    Xi, Yi = np.meshgrid(xi, yi)
    zi = interpolator(Xi, Yi)
    plt.figure()
    ax1 = plt.subplot(111)
    ax1.contour(xi, yi, zi, levels=14, linewidths=0.5, colors='k')
    cntr1 = ax1.contourf(xi, yi, zi, levels=14, cmap="RdBu_r")
    plt.colorbar(cntr1, ax=ax1)
    # ax1.plot(x, y, 'ko', ms=3)
    ax1.set(xlim=(-10, 10), ylim=(-10, 10))
    ax1.set_title('grad and contour')
    plt.savefig('testgradcont.pdf')
    plt.close()

    plt.figure()
    ax2 = plt.subplot(111)
    ax2.tricontour(x, y, z, levels=14, linewidths=0.5, colors='k')
    cntr2 = ax2.tricontourf(x, y, z, levels=14, cmap="RdBu_r")
    plt.colorbar(cntr2, ax=ax2)
    # ax2.plot(x, y, 'ko', ms=3)
    ax2.set(xlim=(-10, 10), ylim=(-10, 10))
    ax2.set_title('tricontour')
    plt.savefig('testtricont.pdf')
    plt.close()
    return
Esempio n. 21
0
def plot_cross_section(function_space,
                       parameter, mean, cov,
                       x_axis_limits, cross_section_y,
                       title,
                       filepath,
                       y_axis_limits):

    #=== Convert array to dolfin function ===#
    parameter_fe = convert_array_to_dolfin_function(function_space, parameter)
    mean_fe = convert_array_to_dolfin_function(function_space, mean)
    cov_fe = convert_array_to_dolfin_function(function_space, cov)

    #=== Extract mesh and triangulate ===#
    mesh = parameter_fe.function_space().mesh()
    coords = mesh.coordinates()
    elements = mesh.cells()
    triangulation = tri.Triangulation(coords[:, 0], coords[:, 1], elements)

    #=== Linear Interpolators ===#
    interp_parameter = tri.LinearTriInterpolator(triangulation, parameter.flatten())
    interp_mean = tri.LinearTriInterpolator(triangulation, mean.flatten())
    interp_cov = tri.LinearTriInterpolator(triangulation, cov.flatten())

    #=== Interpolate values of cross section ===#
    x = np.linspace(x_axis_limits[0], x_axis_limits[1], 100, endpoint=True)
    parameter_cross = np.zeros(len(x))
    mean_cross = np.zeros(len(x))
    std_cross = np.zeros(len(x))
    for i in range(0,len(x)):
        parameter_cross[i] = interp_parameter(x[i], cross_section_y)
        mean_cross[i] = interp_mean(x[i], cross_section_y)
        std_cross[i] = np.exp(interp_cov(x[i], cross_section_y)/2)

    #=== Plotting ===#
    plt.plot(x, parameter_cross, 'r-', label='True Parameter')
    plt.plot(x, mean_cross, 'k-', label='Posterior Mean')
    plt.fill_between(x, mean_cross - 3*std_cross, mean_cross + 3*std_cross)
    plt.xlim(x_axis_limits)
    plt.ylim(y_axis_limits)
    plt.title(title)
    plt.legend(loc="upper left")
    plt.xlabel('x-coordinate')
    plt.ylabel('Parameter Value')

    #=== Save Figure ===#
    plt.savefig(filepath, dpi=100, bbox_inches = 'tight', pad_inches = 0)
    plt.close()
Esempio n. 22
0
def interpolate_data_on_sphere(sampling,
                               data,
                               overlap=np.pi * 0.25,
                               refine=False):
    """Linear interpolator for data on a spherical surface. The interpolator
    exploits that the data on the sphere is periodic with regard to the
    elevation and azimuth angle. The data is periodically extended to a
    specified overlap angle before interpolation.

    Parameters
    ----------
    sampling : Coordinates
        The coordinates at which the data is sampled.
    data : ndarray, double
        The sampled data points.

    Returns
    -------
    interp : LinearTriInterpolator
        The interpolator object.

    """
    lats = sampling.latitude
    lons = sampling.longitude

    mask = lons > np.pi - overlap
    lons = np.concatenate((lons, lons[mask] - np.pi * 2))
    lats = np.concatenate((lats, lats[mask]))
    data = np.concatenate((data, data[mask]))

    mask = lons < -np.pi + overlap
    lons = np.concatenate((lons, lons[mask] + np.pi * 2))
    lats = np.concatenate((lats, lats[mask]))
    data = np.concatenate((data, data[mask]))

    tri = mtri.Triangulation(lons, lats)

    if refine:
        refiner = mtri.UniformTriRefiner(tri)
        tri, data = refiner.refine_field(
            data,
            triinterpolator=mtri.LinearTriInterpolator(tri, data),
            subdiv=3)

    interpolator = mtri.LinearTriInterpolator(tri, data)

    return interpolator
def interpolate_on_grid(tri,
                        data,
                        grid=None,
                        grid_xlim=None,
                        grid_ylim=None,
                        grid_resolution=(500, 500)):
    """
    Interpolation on regular grid (matplotlib.mtri.LinearTriInterpolator)
    @param tri (matplotlib.tri.Triangulation) triangular mesh
    @param data (list(numpy.array) or numpy.array) list of scalar
    data or scalar data
    @param grid(tuple) x and y of interpolation grid
    @param grid_xlim (list(float)) grid limit in x
    @param grid_ylim (list(float)) grid limit in y
    @param grid_resolution (list(float)) number of grid point on x and y
    (default: (500, 500))
    @return: interpolated data(list(numpy.array) or numpy.array)
    and grid (tuple)
    """
    if grid is None:
        if grid_xlim is None:
            grid_xlim = [np.min(tri.x), np.max(tri.x)]
        if grid_ylim is None:
            grid_ylim = [np.min(tri.y), np.max(tri.y)]

    if grid is None:
        m_xi, m_yi = np.meshgrid(np.linspace(grid_xlim[0],
                                             grid_xlim[1],
                                             grid_resolution[0]),
                                 np.linspace(grid_ylim[0],
                                             grid_ylim[1],
                                             grid_resolution[1]))
    else:
        m_xi, m_yi = grid

    # Interpolate data x,y on cartesian grid
    if isinstance(data, list):
        data_x_i = []
        for data_x in data:
            data_x_interp = mtri.LinearTriInterpolator(tri, data_x)
            data_x_i.append(data_x_interp(m_xi, m_yi))
    else:
        data_x_interp = mtri.LinearTriInterpolator(tri, data)
        data_x_i = data_x_interp(m_xi, m_yi)

    return data_x_i, (m_xi, m_yi)
Esempio n. 24
0
def triangulate_rho(X):

    se = X['se']
    rho = X['rho']
    pval = X['pval']
    Hc = X['Hc']
    Hb = X['Hb']
    dH = X['dH']

    #PERFORM GRIDDING AND INTERPOLATION FOR FORC PLOT
    X['Hc1'], X['Hc2'], X['Hb1'], X['Hb2'] = ut.measurement_limts(X)
    Hc1 = 0 - 3 * dH
    Hc2 = X['Hc2']
    Hb1 = X['Hb1'] - X['Hc2']
    Hb2 = X['Hb2']

    #create grid for interpolation
    Nx = np.ceil((Hc2 - Hc1) / dH) + 1  #number of points along x
    Ny = np.ceil((Hb2 - Hb1) / dH) + 1  #number of points along y
    xi = np.linspace(Hc1, Hc2, int(Nx))
    yi = np.linspace(Hb1, Hb2, int(Ny))

    #perform triangluation and interpolation
    triang = tri.Triangulation(Hc, Hb)
    interpolator = tri.LinearTriInterpolator(triang, rho)
    Xi, Yi = np.meshgrid(xi, yi)
    Zi = interpolator(Xi, Yi)

    interpolator1 = tri.LinearTriInterpolator(triang, se)
    SEi = interpolator1(Xi, Yi)

    interpolator2 = tri.LinearTriInterpolator(triang, pval * len(pval))
    Pi = interpolator2(Xi, Yi)

    X['Hc1'] = Hc1
    X['Xi'] = Xi
    X['Yi'] = Yi
    X['Zi'] = Zi
    X['SEi'] = SEi
    X['Pi'] = Pi
    X['SEint'] = interpolator1
    X['Zint'] = interpolator
    X['Pint'] = interpolator2

    return X
Esempio n. 25
0
def plot_streamlines(nodes, elems, vals, title=None, clabel=None,
                     save=None, show=True, num_intp=200, density=0.8):
    """ Plots streamlines with contour in the background.
    Values given at nodes. """
    fig = Figure(title=title, subplots=True, clabel=clabel,
                 save=save, show=show)

    vals_norm = np.sqrt(vals[:, 0]**2 + vals[:, 1]**2) + 1e-10
    # vals_norm_max = np.max(vals_norm)
    fig.colorbar_ax = fig.ax.tricontourf(nodes[:, 0], nodes[:, 1], elems,
                                         vals_norm)

    Lx = nodes[:, 0].max()-nodes[:, 0].min()
    Ly = nodes[:, 1].max()-nodes[:, 1].min()
    dx = max(Lx, Ly)/num_intp
    Nx = int(Lx/dx)
    Ny = int(Ly/dx)

    x_i, y_i = np.meshgrid(
        np.linspace(dx+nodes[:, 0].min(),
                    nodes[:, 0].max()-dx, Nx),
        np.linspace(dx+nodes[:, 1].min(),
                    nodes[:, 1].max()-dx, Ny))
    triang = mtri.Triangulation(nodes[:, 0], nodes[:, 1], elems)
    ux_interp = mtri.LinearTriInterpolator(triang, vals[:, 0])
    uy_interp = mtri.LinearTriInterpolator(triang, vals[:, 1])
    ux_i = ux_interp(x_i, y_i)
    uy_i = uy_interp(x_i, y_i)

    ux_i = np.array(ux_i.filled(0.))
    uy_i = np.array(uy_i.filled(0.))

    u_norm = np.sqrt(ux_i**2 + uy_i**2)

    lw = np.zeros_like(ux_i)
    lw[:] += 5*u_norm/(u_norm.max() + 1e-10)

    mask = np.zeros(ux_i.shape, dtype=bool)
    ux_i_2 = np.ma.array(ux_i, mask=mask)

    fig.ax.streamplot(x_i, y_i,
                      ux_i_2, uy_i,
                      color="k",
                      density=density,
                      linewidth=lw)
Esempio n. 26
0
 def phi_at_gauss_nodes(self, triang, phi_prev, g_nodes):
     num_groups = np.shape(phi_prev)[0]
     num_nodes = np.shape(g_nodes)[0]
     phi_vals = np.zeros((num_groups, num_nodes))
     for g in range(num_groups):
         interp = tri.LinearTriInterpolator(triang, phi_prev[g])
         for i in range(num_nodes):
             phi_vals[g, i] = interp(g_nodes[i, 0], g_nodes[i, 1])
     return phi_vals
Esempio n. 27
0
def __interpolate_flowfront(Xi, Yi, ignore_list, current_index, triang, values):
    ones = np.ones_like(values)
    filling_perc = np.sum(values) / np.sum(ones)
    if filling_perc >= 1.0:
        ignore_list.append(int(str(current_index).replace("state", "0")))
    interpolator = tri.LinearTriInterpolator(triang, values)
    # the PAM-RTM uses a triangle grid for filling states. Interpolate values over triangle grid with matplotlib
    zi = interpolator(Xi, Yi)
    return zi
Esempio n. 28
0
    def plot_contour_interpolate(self, vec_x, vec_y, vec_z, contour_resolution, contour_resolution_y=None, flush=True):
        """ create a 2D contour plot
        :param vec_x:
        :param vec_y:
        :param contour_resolution:
        :param flush:
        :return:
        """
        # check for vec x and vec y for non-contour case
        if vec_x.min() == vec_x.max() or vec_y.min() == vec_y.max():
            # TODO - 20180906 - Propagate this situation
            return False

        # Create grid values first.
        ngridx = contour_resolution
        if contour_resolution_y is None:
            ngridy = contour_resolution
        else:
            ngridy = contour_resolution_y

        xi = np.linspace(vec_x.min(), vec_x.max(), ngridx)
        yi = np.linspace(vec_y.min(), vec_y.max(), ngridy)

        # Perform linear interpolation of the data (x,y)
        # on a grid defined by (xi,yi)
        try:
            triang = tri.Triangulation(vec_x, vec_y)
        except RuntimeError as run_err:
            print('[ERROR] vec X: {}'.format(vec_x))
            print(vec_y)
            raise run_err
        interpolator = tri.LinearTriInterpolator(triang, vec_z)
        Xi, Yi = np.meshgrid(xi, yi)
        zi = interpolator(Xi, Yi)

        # self.main_canvas.plot_contour(xi, yi, zi, flush=False)
        # self. .plot_scatter(vec_x, vec_y, flush=True)

        self._xi = xi
        self._yi = yi
        self._zmatrix = zi

        self._is_setup = True
        contour_plot = self.main_canvas.add_contour_plot(xi, yi, zi)
        print('[DB...BAT] Contour plot: {} of type {}'.format(contour_plot, type(contour_plot)))
        # self.ui.widget.main_canvas.add_scatter(vec_x, vec_y)
        # self.ui.widget.main_canvas._flush()

        if flush:
            self.main_canvas._flush()

        # self.ui.widget.main_canvas.add_contour_plot(xi, yi, zi)
        # self.ui.widget.main_canvas.add_scatter(vec_x, vec_y)
        # self.ui.widget.main_canvas._flush()

        return
Esempio n. 29
0
def generate_offset_map(source, target):
    anchor_pts = [[0, 0], [0, 256], [256, 0], [256, 256], [0, 128], [128, 0],
                  [256, 128], [128, 256], [0, 64], [0, 192], [256, 64],
                  [256, 192], [64, 0], [192, 0], [64, 256], [192, 256]]
    anchor_pts = np.asarray(anchor_pts) / 256
    xi, yi = np.meshgrid(np.linspace(0, 1, 256), np.linspace(0, 1, 256))
    _source = np.concatenate([source, anchor_pts], axis=0).astype(np.float32)
    _target = np.concatenate([target, anchor_pts], axis=0).astype(np.float32)
    _offset = _source - _target

    # interp2d
    _triang = mtri.Triangulation(_target[:, 0], _target[:, 1])
    _interpx = mtri.LinearTriInterpolator(_triang, _offset[:, 0])
    _interpy = mtri.LinearTriInterpolator(_triang, _offset[:, 1])
    _offsetmapx = _interpx(xi, yi)
    _offsetmapy = _interpy(xi, yi)

    offsetmap = np.stack([_offsetmapy, _offsetmapx, _offsetmapx * 0], axis=2)
    return offsetmap
Esempio n. 30
0
    def interpTri(triVerts, triInd):

        from matplotlib import pyplot as plt

        import matplotlib.pyplot as plt
        import matplotlib.tri as mtri
        import numpy as np

        x = triVerts[:, 0]
        y = triVerts[:, 1]
        triang = mtri.Triangulation(triVerts[:, 0], triVerts[:, 1], triInd)

        # Interpolate to regularly-spaced quad grid.
        z = np.cos(1.5 * x) * np.cos(1.5 * y)
        xi, yi = np.meshgrid(np.linspace(0, 3, 20), np.linspace(0, 3, 20))

        interp_lin = mtri.LinearTriInterpolator(triang, z)
        zi_lin = interp_lin(xi, yi)

        interp_cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')
        zi_cubic_geom = interp_cubic_geom(xi, yi)

        interp_cubic_min_E = mtri.CubicTriInterpolator(triang, z, kind='min_E')
        zi_cubic_min_E = interp_cubic_min_E(xi, yi)

        # Set up the figure
        fig, axs = plt.subplots(nrows=2, ncols=2)
        axs = axs.flatten()

        # Plot the triangulation.
        axs[0].tricontourf(triang, z)
        axs[0].triplot(triang, 'ko-')
        axs[0].set_title('Triangular grid')

        # Plot linear interpolation to quad grid.
        axs[1].contourf(xi, yi, zi_lin)
        axs[1].plot(xi, yi, 'k-', lw=0.5, alpha=0.5)
        axs[1].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5)
        axs[1].set_title("Linear interpolation")

        # Plot cubic interpolation to quad grid, kind=geom
        axs[2].contourf(xi, yi, zi_cubic_geom)
        axs[2].plot(xi, yi, 'k-', lw=0.5, alpha=0.5)
        axs[2].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5)
        axs[2].set_title("Cubic interpolation,\nkind='geom'")

        # Plot cubic interpolation to quad grid, kind=min_E
        axs[3].contourf(xi, yi, zi_cubic_min_E)
        axs[3].plot(xi, yi, 'k-', lw=0.5, alpha=0.5)
        axs[3].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5)
        axs[3].set_title("Cubic interpolation,\nkind='min_E'")

        fig.tight_layout()
        plt.show()