Example #1
0
def test_trirefine():
    # test subdiv=2 refinement
    n = 3
    subdiv = 2
    x = np.linspace(-1., 1., n+1)
    x, y = np.meshgrid(x, x)
    x = x.ravel()
    y = y.ravel()
    mask = np.zeros(2*n**2, dtype=np.bool)
    mask[n**2:] = True
    triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1),
                                mask=mask)
    refiner = mtri.UniformTriRefiner(triang)
    refi_triang = refiner.refine_triangulation(subdiv=subdiv)
    x_refi = refi_triang.x
    y_refi = refi_triang.y

    n_refi = n * subdiv**2
    x_verif = np.linspace(-1., 1., n_refi+1)
    x_verif, y_verif = np.meshgrid(x_verif, x_verif)
    x_verif = x_verif.ravel()
    y_verif = y_verif.ravel()
    ind1d = np.in1d(np.around(x_verif*(2.5+y_verif), 8),
                    np.around(x_refi*(2.5+y_refi), 8))
    assert_array_equal(ind1d, True)

    # tests the mask of the refined triangulation
    refi_mask = refi_triang.mask
    refi_tri_barycenter_x = np.sum(refi_triang.x[refi_triang.triangles],
                                   axis=1)/3.
    refi_tri_barycenter_y = np.sum(refi_triang.y[refi_triang.triangles],
                                   axis=1)/3.
    tri_finder = triang.get_trifinder()
    refi_tri_indices = tri_finder(refi_tri_barycenter_x,
                                  refi_tri_barycenter_y)
    refi_tri_mask = triang.mask[refi_tri_indices]
    assert_array_equal(refi_mask, refi_tri_mask)
def test_tri_smooth_contouring():
    # Image comparison based on example tricontour_smooth_user.
    n_angles = 20
    n_radii = 10
    min_radius = 0.15

    def z(x, y):
        r1 = np.sqrt((0.5-x)**2 + (0.5-y)**2)
        theta1 = np.arctan2(0.5-x, 0.5-y)
        r2 = np.sqrt((-x-0.2)**2 + (-y-0.2)**2)
        theta2 = np.arctan2(-x-0.2, -y-0.2)
        z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
              (np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
              0.7*(x**2 + y**2))
        return (np.max(z)-z)/(np.max(z)-np.min(z))

    # First create the x and y coordinates of the points.
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0 + n_angles, 2*np.pi + n_angles,
                         n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi/n_angles
    x0 = (radii*np.cos(angles)).flatten()
    y0 = (radii*np.sin(angles)).flatten()
    triang0 = mtri.Triangulation(x0, y0)  # Delaunay triangulation
    z0 = z(x0, y0)
    xmid = x0[triang0.triangles].mean(axis=1)
    ymid = y0[triang0.triangles].mean(axis=1)
    mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0)
    triang0.set_mask(mask)

    # Then the plot
    refiner = mtri.UniformTriRefiner(triang0)
    tri_refi, z_test_refi = refiner.refine_field(z0, subdiv=4)
    levels = np.arange(0., 1., 0.025)
    plt.triplot(triang0, lw=0.5, color='0.5')
    plt.tricontour(tri_refi, z_test_refi, levels=levels, colors="black")
Example #3
0
def plot_1profile_onMesh(X1, Y1, Vel1, z_min, z_max, filename):

  #fig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharex=True, sharey=True, subplot_kw={'projection':'3d'}, 
                                 #figsize=plt.figaspect(0.5)*1.5)
  #fig.tight_layout()
  fig = plt.figure()
  ax = fig.gca(projection='3d')
  triang = tri.Triangulation(X1, Y1)

 #-----------------------------------------------------------------------------
  # Refine data
  #-----------------------------------------------------------------------------
  refiner = tri.UniformTriRefiner(triang)
  tri_refi, Vel1_refi = refiner.refine_field(Vel1, subdiv=3)
  

  #-----------------------------------------------------------------------------
  # Plot the triangulation and the high-res iso-contours
  #-----------------------------------------------------------------------------

  ax.triplot(triang, lw=0.5, color='black')
  ax.set_zlim(z_min, z_max)

  levels = np.arange(z_min, z_max, 0.025)
  cmap = cm.get_cmap(name='terrain', lut=None)
  #plt.tricontourf(tri_refi, Vel3_refi.flatten(), levels=levels, cmap=cmap)
  ax.plot_trisurf(X1, Y1, Vel1, cmap=cm.jet, linewidth=0.2)
 
  ax.zaxis.set_major_locator(LinearLocator(10))
  ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
  
  #fig.colorbar(surf, shrink=0.5, aspect=5)


  #plt.show()
  fig.savefig(filename)
  plt.close()
Example #4
0
def draw_pdf_contours(axis, dist, nlevels=32, subdiv=5, **kwargs):
    """ 重心座標系での三角メッシュ上にpdfをheatmap表示 """
    import math

    refiner = tri.UniformTriRefiner(triangle)
    trimesh = refiner.refine_triangulation(subdiv=subdiv)
    #pvals = [dist.pdf(xy2bc(xy)) for xy in zip(trimesh.x, trimesh.y)]
    xy = np.array([trimesh.x, trimesh.y])
    pvals = dist.pdf(xy2bc(xy))

    # 分布の最大箇所を探索
    max_idx = np.argmax(pvals)
    xy_max = np.array(xy[:, max_idx])
    #print('xy_max.shape = ', xy_max.shape)
    lambda_max = xy2bc(xy_max.reshape(2, 1))
    lambda_max = np.array(lambda_max).flatten()
    #print('max_idx=', max_idx, 'xy_max = ', xy_max, 'lambda=', lambda_max )

    axis.tricontourf(trimesh, pvals, nlevels, **kwargs, cmap=plt.cm.hot)
    axis.scatter(xy_max[0], xy_max[1], c='red', marker='o')
    axis.axis('equal')
    axis.set_xlim(0, 1)
    axis.set_ylim(0, 0.75**0.5)
    axis.axis('off')
Example #5
0
    def mesh(self, fold_under_base=True):
        mesh = mtri.UniformTriRefiner(
            self.triangle).refine_triangulation(subdiv=self.subdiv)
        verticies, counts = np.unique(mesh.edges, return_counts=True)
        l1 = verticies[np.where(counts <= 4)]  # the outer layer of verticies
        l2, outer = inner(l1, mesh.edges)  # one layer in from the edge
        l3, outer = inner(l2, mesh.edges, outer)  # two layers in from the edge
        scale_x = MinMaxScaler1D()
        scale_x.fit(mesh.x[l3])
        scale_y = MinMaxScaler1D(0, 0.75**0.5)
        scale_y.fit(mesh.y[l3])
        mesh.x = scale_x.transform(mesh.x)
        mesh.y = scale_y.transform(mesh.y)

        if fold_under_base:
            mesh.x[l2] = scale_x.fit(mesh.x[l2]).transform(mesh.x[l2])
            mesh.y[l2] = scale_y.fit(mesh.y[l2]).transform(mesh.y[l2])
            mesh.x[l1] = .5
            mesh.y[l1] = .5

        self._surface_verts = np.isin(verticies, outer, invert=True)
        self._outer_base = l2
        self._inner_base = l1
        return mesh
Example #6
0
def draw_pdf_contours(dist, border=False, nlevels=200, subdiv=8, **kwargs):
    '''Draws pdf contours over an equilateral triangle (2-simplex).
    Arguments:
        `dist`: A distribution instance with a `pdf` method.
        `border` (bool): If True, the simplex border is drawn.
        `nlevels` (int): Number of contours to draw.
        `subdiv` (int): Number of recursive mesh subdivisions to create.
        kwargs: Keyword args passed on to `plt.triplot`.
    '''
    from matplotlib import ticker, cm
    import math

    refiner = tri.UniformTriRefiner(_triangle)
    trimesh = refiner.refine_triangulation(subdiv=subdiv)
    pvals = [dist.pdf(xy2bc(xy)) for xy in zip(trimesh.x, trimesh.y)]

    plt.tricontourf(trimesh, pvals, nlevels, **kwargs)
    plt.axis('equal')
    plt.xlim(0, 1)
    plt.ylim(0, 0.75**0.5)
    plt.axis('off')
    if border is True:
        #        plt.hold(1)
        plt.triplot(_triangle, linewidth=1)
Example #7
0
class simplex_dynamics:
    '''draws dynamics of given function and 
    corresponding fixed points into triangle'''
    #corners of triangle and calculation of points
    r0 = np.array([0, 0])
    r1 = np.array([1, 0])
    r2 = np.array([1 / 2., np.sqrt(3) / 2.])
    corners = np.array([r0, r1, r2])
    triangle = tri.Triangulation(corners[:, 0], corners[:, 1])
    refiner = tri.UniformTriRefiner(triangle)
    trimesh = refiner.refine_triangulation(subdiv=5)
    trimesh_fine = refiner.refine_triangulation(subdiv=5)

    def __init__(self, fun):
        self.f = fun
        # self.calculate_stationary_points()
        self.calc_direction_and_strength()

    #barycentric coordinates
    def xy2ba(self, x, y):
        corner_x = self.corners.T[0]
        corner_y = self.corners.T[1]
        x_1 = corner_x[0]
        x_2 = corner_x[1]
        x_3 = corner_x[2]
        y_1 = corner_y[0]
        y_2 = corner_y[1]
        y_3 = corner_y[2]
        l1 = ((y_2 - y_3) * (x - x_3) + (x_3 - x_2) *
              (y - y_3)) / ((y_2 - y_3) * (x_1 - x_3) + (x_3 - x_2) *
                            (y_1 - y_3))
        l2 = ((y_3 - y_1) * (x - x_3) + (x_1 - x_3) *
              (y - y_3)) / ((y_2 - y_3) * (x_1 - x_3) + (x_3 - x_2) *
                            (y_1 - y_3))
        l3 = 1 - l1 - l2
        return np.array([l1, l2, l3])

    def ba2xy(self, x):
        ### x: array of 3-dim ba coordinates
        ### corners: coordinates of corners of ba coordinate system
        x = np.array(x)
        # print(self.corners.shape)
        # print(self.corners.T)
        # print(x)
        return self.corners.T.dot(x.T).T

    def calc_direction_and_strength(self):
        direction = [
            self.f(self.xy2ba(x, y), 0)
            for x, y in zip(self.trimesh.x, self.trimesh.y)
        ]
        self.direction_norm = np.array([
            self.ba2xy(v) /
            np.linalg.norm(v) if np.linalg.norm(v) > 0 else np.array([0, 0])
            for v in direction
        ])
        self.direction_norm = self.direction_norm
        #print(direction_ba_norm)
        self.pvals = [np.linalg.norm(v) for v in direction]
        self.direction = np.array([self.ba2xy(v) for v in direction])

    def plot_simplex(self,
                     ax,
                     cmap='viridis',
                     typelabels=["A", "B", "C"],
                     **kwargs):

        ax.triplot(self.triangle, linewidth=0.8, color="black")
        ax.tricontourf(self.trimesh,
                       self.pvals,
                       alpha=0.8,
                       cmap=cmap,
                       **kwargs)

        #arrow plot options:
        # Q = ax.quiver(self.trimesh.x, self.trimesh.y, self.direction_norm.T[0],self.direction_norm.T[1],self.pvals,angles='xy',pivot='mid',  cmap=cmap)#pivot='tail',
        Q = ax.quiver(self.trimesh.x,
                      self.trimesh.y,
                      self.direction_norm.T[0],
                      self.direction_norm.T[1],
                      angles='xy',
                      pivot='mid')  #pivot='tail')#
        # Q = ax.quiver(self.trimesh.x, self.trimesh.y, self.direction.T[0],self.direction.T[1],angles='xy',pivot='mid')#pivot='tail')#

        ax.axis('equal')
        ax.axis('off')
        margin = 0.01
        ax.set_ylim(ymin=-margin, ymax=self.r2[1] + margin)
        ax.set_xlim(xmin=-margin, xmax=1. + margin)

        #timescatter=ax.scatter(points[::5,0],points[::5,1],c=t[::5],linewidth=0.0,cmap='viridis',alpha=.5)
        # if self.fixpoints.shape[0]>0:
        #     ax.scatter(self.fixpoints[:,0],self.fixpoints[:,1],c="black",s=70,linewidth=0.3)
        #fig.colorbar(timescatter,label="time")
        ax.annotate(typelabels[0], (0, 0),
                    xytext=(-0.0, -0.02),
                    horizontalalignment='center',
                    va='top')
        ax.annotate(typelabels[1], (1, 0),
                    xytext=(1.0, -0.02),
                    horizontalalignment='center',
                    va='top')
        ax.annotate(typelabels[2],
                    self.corners[2],
                    xytext=self.corners[2] + np.array([0.0, 0.02]),
                    horizontalalignment='center',
                    va='bottom')
def plot_to_file_3profiles(X1, Y1, X2, Y2, Vel1, Vel2, Vel3, z_min, z_max,
                           filename):
    #ax1 = fig.gca(projection='3d')
    #ax2 = fig.gca(projection='3d')
    #fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True, projection='3d')

    #fig = plt.figure()
    # figaspect(0.5) makes the figure twice as wide as it is tall.
    # Then the *1.5 increases the size of the figure.
    # The labels etc won't increase so this is a way to make the graph look less cluttered by the labels.
    #fig = plt.figure(figsize=plt.figaspect(0.5)*1.5)
    #ax1 = fig.add_subplot(121, projection='3d')
    #ax2 = fig.add_subplot(122, projection='3d')

    fig, (ax1, ax2, ax3) = plt.subplots(1,
                                        3,
                                        sharex=True,
                                        sharey=True,
                                        subplot_kw={'projection': '3d'},
                                        figsize=plt.figaspect(0.5) * 1.5)
    fig.tight_layout()

    Xtmp1, Ytmp1 = np.meshgrid(X1, Y1)
    surf = ax1.plot_surface(Xtmp1,
                            Ytmp1,
                            Vel1,
                            rstride=1,
                            cstride=1,
                            cmap=cm.coolwarm,
                            linewidth=0,
                            antialiased=False)
    surf = ax2.plot_surface(Xtmp1,
                            Ytmp1,
                            Vel2,
                            rstride=1,
                            cstride=1,
                            cmap=cm.coolwarm,
                            linewidth=0,
                            antialiased=False)
    ax1.set_zlim(z_min, z_max)
    ax2.set_zlim(z_min, z_max)

    triang = tri.Triangulation(X2, Y2)

    #-----------------------------------------------------------------------------
    # Refine data
    #-----------------------------------------------------------------------------
    refiner = tri.UniformTriRefiner(triang)
    tri_refi, Vel3_refi = refiner.refine_field(Vel3, subdiv=3)

    #print(X2.shape)
    #print(Y2.shape)
    #print(Vel3.shape)

    #-----------------------------------------------------------------------------
    # Plot the triangulation and the high-res iso-contours
    #-----------------------------------------------------------------------------
    #plt.figure()
    #plt.gca().set_aspect('equal')
    ax3.triplot(triang, lw=0.5, color='black')

    levels = np.arange(z_min, z_max, 0.025)
    cmap = cm.get_cmap(name='terrain', lut=None)
    #plt.tricontourf(tri_refi, Vel3_refi.flatten(), levels=levels, cmap=cmap)
    ax3.plot_trisurf(X2, Y2, Vel3, cmap=cm.jet, linewidth=0.2)
    #print(Vel3)
    #plt.tricontourf(tri_refi, Vel3_refi, levels=levels, cmap=cmap)
    #plt.tricontour(tri_refi, z_test_refi, levels=levels,
    #colors=['0.25', '0.5', '0.5', '0.5', '0.5'],
    #linewidths=[1.0, 0.5, 0.5, 0.5, 0.5])

    ax1.zaxis.set_major_locator(LinearLocator(10))
    ax1.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    ax2.zaxis.set_major_locator(LinearLocator(10))
    ax2.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    ax3.zaxis.set_major_locator(LinearLocator(10))
    ax3.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    fig.colorbar(surf, shrink=0.5, aspect=5)

    #plt.show()
    fig.savefig(filename)
    plt.close()
Example #9
0
import matplotlib.tri as pytri
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from math import sqrt

fig = plt.figure()


tri = pytri.Triangulation([1, -sqrt(3)/2, -sqrt(3)/2], [0, 0.5, -0.5])
ref = pytri.UniformTriRefiner(tri)

phi0 = [1, 0, 0]
phi1 = [0, 1, 0]
phi2 = [0, 0, 1]
shadow = [0, 0, 0]

rtri, rphi0 = ref.refine_field(phi0, subdiv=4)
rtri, rphi1 = ref.refine_field(phi1, subdiv=4)
rtri, rphi2 = ref.refine_field(phi2, subdiv=4)

ax = fig.add_subplot(131, projection='3d')
ax.plot_trisurf(rtri, rphi0, cmap=cm.coolwarm)
ax.plot_trisurf(tri, shadow)
ax = fig.add_subplot(132, projection='3d')
ax.plot_trisurf(rtri, rphi1, cmap=cm.coolwarm)
ax.plot_trisurf(tri, shadow)
ax = fig.add_subplot(133, projection='3d')
ax.plot_trisurf(rtri, rphi2, cmap=cm.coolwarm)
ax.plot_trisurf(tri, shadow)
plt.show()
Example #10
0
def plot(distribution,
         method='stick',
         short=False,
         lingrid=None,
         bins=100,
         subdiv=6,
         levels=100):
    """
    Visualizes a distribution on the 1D or 2D probability simplex. The distribution can be either provided
    parametrically as a Gaussian or in form of a collection of samples.

    Parameters
    ----------
    distribution:   Either an [N x M] array representing N samples from the distribution or a tuple (mean, cov)
        containing the parameters of the Gaussian. The dimensionality of the Gaussian / the value M depend on the number
        of categories and/or the specified transformation method, see 'gaussian2simplex' and 'realsamples2simplex'.

    method: Either 'stick', 'logistic', 'softmax' or 'direct'. If 'direct', the methods are assumed to be provided
        directly on the simplex. For the other options, see 'realsamples2simplex'. If the distribution is specified
        parametrically, 'stick' is assumed.

    short: Only relevant for method='direct'. If true it is assumed that the last (dependent) entry of each sample
        has already been dropped.

    lingrid: grid for plotting 1D densities computed from parametric Gaussians

    bins: number of bins for plotting 1D densities computed from samples

    subdiv: grid granularity for plotting 2D densities

    levels: value granularity for plotting 2D densities
    """
    method = method.lower()

    if isinstance(distribution, tuple):
        parametric = True
        mean, cov = map(lambda x: np.array(x), distribution)
        dim = mean.shape[0] + 1
        assert method == 'stick'
    else:
        parametric = False
        samples = np.array(distribution)

        # type of samples
        if method == 'direct':
            # samples are directly provided on probability simplex
            if short:
                p = np.c_[samples, 1 - samples.sum(axis=1)]
            else:
                p = samples
        else:
            # map samples to probability simplex
            p = realsamples2simplex(samples, method)
        dim = p.shape[1]

    # two categories
    if dim == 2:
        # if distribution is parametrized as Gaussian
        if parametric:
            # plotting grid
            if lingrid is None:
                lingrid = np.linspace(0, 1, 100)

            # corresponding points on two-dimensional simplex (last entry dropped)
            pshort = lingrid[:, None]

            # evaluate density on simplex points
            density = gaussian2simplex(mean, cov, pshort, short=True)

            # visualization
            plt.plot(lingrid, density)

        # otherwise (distribution given in form of samples)
        else:
            # visualization
            plt.hist(p[:, 0], bins=bins, range=(0, 1), density=True)

    # three categories
    elif dim == 3:
        # define simplex triangle
        corners = np.array([[0, 0], [1, 0], [0.5, np.sin(np.pi / 3)]])
        triangle = tri.Triangulation(*corners.T)

        # get simplex grid
        refiner = tri.UniformTriRefiner(triangle)
        trimesh = refiner.refine_triangulation(subdiv=subdiv)
        grid = np.c_[trimesh.x, trimesh.y]

        # compute Delaunay triangulation
        D = spa.Delaunay(grid)

        # if distribution is parametrized as Gaussian
        if parametric:
            p = xy2bc(grid, corners)
            density = gaussian2simplex(mean, cov, p)
            visualizationMesh = trimesh

        # otherwise (distribution given in form of samples)
        else:
            # get xy-Cartesian coordinates of simplex points
            xy = bc2xy(p, corners)

            # compute histogram on the triangulation simplexes
            simplexInds = D.find_simplex(xy)
            density = np.bincount(simplexInds,
                                  minlength=D.nsimplex) / samples.shape[0]

            # compute center points of triangulation
            centerPoints = np.zeros((D.nsimplex, 2))
            for vInd, v in enumerate(D.vertices):
                centerPoints[vInd] = D.points[D.vertices[vInd]].mean(axis=0)

            # mesh for visualization, defined on the center points of the original triangulation
            visualizationMesh = tri.Triangulation(centerPoints[:, 0],
                                                  centerPoints[:, 1])

        # visualization
        plt.tricontourf(visualizationMesh, density, levels)
        plt.text(*corners[0],
                 '(1,0,0)',
                 verticalalignment='top',
                 horizontalalignment='right')
        plt.text(*corners[1],
                 '(0,1,0)',
                 verticalalignment='top',
                 horizontalalignment='left')
        plt.text(*corners[2],
                 '(0,0,1)',
                 verticalalignment='bottom',
                 horizontalalignment='center')
        plt.title(method, loc='right')

    else:
        raise ValueError('wrong input dimension')
Example #11
0
def triangleplot(surf_points, surf_data, norm, surf_axis_scale = 1, cmap = 'RdBu_r',
                 cbar_label = '', saveas = None, surf_levels = None,
                 scatter_points=None, scatter_color = None, cbar_spacing = None,
                 cbar_ticks = None):


    mpl.rcParams.update({'font.size': 8})
    mpl.rcParams.update({'font.sans-serif': 'Arial', 'font.family': 'sans-serif'})
    
    
    b=surf_points[:,0]
    c=surf_points[:,1]
    a=surf_points[:,2]
    # values stored in the last column
    v = np.squeeze(surf_data)/surf_axis_scale#[:,-1]/surf_axis_scale
    # translate the data to cartesian
    x = 0.5 * ( 2.*b+c ) / ( a+b+c )
    y = 0.5*np.sqrt(3) * c / (a+b+c)
    # create a triangulation
    T = tri.Triangulation(x,y)
    
    fig, ax = plt.subplots(nrows=1, ncols=1)
    fig.set_figheight(3.6/2.54)
    fig.set_figwidth(5/2.54)
    plt.subplots_adjust(left=0.05, right=0.85, bottom=0.14, top=0.91)

    if scatter_points is not None:
        #Triangulation for the points suggested by BO.
        b_p = scatter_points[:,0]
        c_p = scatter_points[:,1]
        a_p = scatter_points[:,2]
        x_p = 0.5 * ( 2.*b_p+c_p ) / ( a_p+b_p+c_p)
        y_p = 0.5*np.sqrt(3) * c_p / (a_p+b_p+c_p)
        
        im3 = ax.scatter(x_p, y_p, s=8, c=scatter_color, cmap=cmap, edgecolors='black', linewidths=.5, alpha=1, zorder=2, norm=norm)
    # plot the contour
    if surf_levels is None:
    #    im=ax.tricontourf(x,y,T.triangles,v, cmap=cmap, levels=surf_levels)
    #else:
        nlevels = 8
        minvalue = 0
        if norm.vmin < minvalue:
            minvalue = norm.vmin
        if norm.vmin > (minvalue + ((norm.vmax-minvalue)/nlevels)):
            minvalue = norm.vmin
        surf_levels = np.arange(minvalue, norm.vmax, (norm.vmax-minvalue)/nlevels)
        surf_levels = np.round(surf_levels, -int(np.floor(np.log10(norm.vmax))-1))#2))
        surf_levels = np.append(surf_levels, 2*surf_levels[-1] - surf_levels[-2])
    im=ax.tricontourf(x,y,T.triangles,v, cmap=cmap, levels=surf_levels)
    
    myformatter=matplotlib.ticker.ScalarFormatter()
    myformatter.set_powerlimits((0,2))
    if cbar_spacing is not None:
        cbar=plt.colorbar(im, ax=ax, spacing=cbar_spacing, ticks=cbar_ticks)
    else:
        cbar=plt.colorbar(im, ax=ax, format=myformatter, spacing=surf_levels, ticks=surf_levels)
    cbar.set_label(cbar_label)#, labelpad = -0.5)
    plt.axis('off')
    plt.text(0.35,-0.1,'Cs (%)')
    plt.text(0.10,0.54,'FA (%)', rotation=61)
    plt.text(0.71,0.51,'MA (%)', rotation=-61)
    plt.text(-0.0, -0.1, '0')
    plt.text(0.87, -0.1, '100')
    plt.text(-0.07, 0.13, '100', rotation=61)
    plt.text(0.39, 0.83, '0', rotation=61)
    plt.text(0.96, 0.05, '0', rotation=-61)
    plt.text(0.52, 0.82, '100', rotation=-61)
    
    # create the grid
    corners = np.array([[0, 0], [1, 0], [0.5,  np.sqrt(3)*0.5]])
    triangle = tri.Triangulation(corners[:, 0], corners[:, 1])
    # creating the grid
    refiner = tri.UniformTriRefiner(triangle)
    trimesh = refiner.refine_triangulation(subdiv=0)
    #plotting the mesh
    im2=ax.triplot(trimesh,'k-', linewidth=0.5)
    
    
    if saveas:
        fig.savefig(results_dir + saveas + '.pdf', transparent = True)
        fig.savefig(results_dir + saveas + '.svg', transparent = True)
        fig.savefig(results_dir + saveas + '.png', dpi=300)
    plt.show()
    return fig, ax
Example #12
0
def plot_energies_contour(sites,
                          e_seg,
                          figname,
                          r,
                          cmtype='viridis',
                          refine=False,
                          units='eV',
                          figformat='tif',
                          levels=100,
                          nticks=4,
                          vmin=np.nan,
                          vmax=np.nan):
    '''Produces a contour plot of the segregation energy at sites around a 
    dislocation. Use <levels> to control the number of contours.
    '''

    # create contour plot of segregation energies using a Delauney triangulation
    # scheme
    x = sites[:, 1]
    y = sites[:, 2]
    triang = tri.Triangulation(x, y)

    fig = plt.figure()
    plt.gca().set_aspect('equal')

    if not (vmin is np.nan) and not (vmax is np.nan):
        # both vmin and vmax are defined
        ticks = np.linspace(vmin, vmax, nticks, endpoint=True)
        normalize = colors.Normalize(vmin=vmin, vmax=vmax)
        levels = np.linspace(vmin, vmax, levels)
    elif vmin is np.nan and not (vmax is np.nan):
        # only vmax is defined => use minimum value of e_seg for vmin
        ticks = np.linspace(min(e_seg), vmax, nticks, endpoint=True)
        normalize = colors.Normalize(vmin=min(e_seg), vmax=vmax)
        levels = np.linspace(min(e_seg), vmax, levels)
    elif not (vmin is np.nan) and vmax is np.nan:
        # only vmin is defined => use maximum value of e_seg for vmax
        ticks = np.linspace(vmin, max(e_seg), nticks, endpoint=True)
        normalize = colors.Normalize(vmin=vmin, vmax=max(e_seg))
        levels = np.linspace(vmin, max(e_seg), levels)
    else:
        ticks = np.linspace(min(e_seg), max(e_seg), nticks, endpoint=True)
        normalize = colors.Normalize(vmin=min(e_seg), vmax=max(e_seg))
        levels = np.linspace(min(e_seg), max(e_seg), levels)

    # plot energy contours
    if refine:
        # refine data for improved high-res plot
        refiner = tri.UniformTriRefiner(triang)
        points, values = refiner.refine_field(e_seg, subdiv=3)
    else:
        # use raw data to produce contours
        points, values = triang, e_seg

    #if vmin != vmin and vmax != vmax:
    #    plt.tricontourf(points, values, levels, cmap=plt.get_cmap(cmtype))
    #else:
    plt.tricontourf(points,
                    values,
                    levels,
                    cmap=plt.get_cmap(cmtype),
                    norm=normalize)

    plt.xlabel('x ($\AA$)', size='x-large', family='serif')
    plt.ylabel('y ($\AA$)', size='x-large', family='serif')

    cb = plt.colorbar(format='%.2f', ticks=ticks)
    cb.set_label('E ({})'.format(units),
                 size='x-large',
                 family='serif',
                 weight='semibold')

    # add points to mark the locations of the atomic sites
    plt.scatter(x, y, s=60, linewidth='2', facecolors='none', edgecolors='k')

    plt.xlim(-r - 1, r + 1)
    plt.ylim(-r - 1, r + 1)

    plt.tight_layout()

    plt.savefig('{}.{}'.format(figname, figformat), dpi=400)
    plt.close()

    return
Example #13
0
def example7():
    #-----------------------------------------------------------------------------
    # Analytical test function
    #-----------------------------------------------------------------------------
    def function_z(x, y):
        r1 = np.sqrt((0.5 - x)**2 + (0.5 - y)**2)
        theta1 = np.arctan2(0.5 - x, 0.5 - y)
        r2 = np.sqrt((-x - 0.2)**2 + (-y - 0.2)**2)
        theta2 = np.arctan2(-x - 0.2, -y - 0.2)
        z = -(2 * (np.exp(
            (r1 / 10)**2) - 1) * 30. * np.cos(7. * theta1) + (np.exp(
                (r2 / 10)**2) - 1) * 30. * np.cos(11. * theta2) + 0.7 *
              (x**2 + y**2))
        return (np.max(z) - z) / (np.max(z) - np.min(z))

    #-----------------------------------------------------------------------------
    # Creating a Triangulation
    #-----------------------------------------------------------------------------
    # First create the x and y coordinates of the points.
    n_angles = 20
    n_radii = 10
    min_radius = 0.15
    radii = np.linspace(min_radius, 0.95, n_radii)

    angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi / n_angles

    x = (radii * np.cos(angles)).flatten()
    y = (radii * np.sin(angles)).flatten()
    z = function_z(x, y)

    # Now create the Triangulation.
    # (Creating a Triangulation without specifying the triangles results in the
    # Delaunay triangulation of the points.)
    triang = tri.Triangulation(x, y)

    # 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
    #-----------------------------------------------------------------------------
    refiner = tri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(z, subdiv=3)

    #-----------------------------------------------------------------------------
    # Plot the triangulation and the high-res iso-contours
    #-----------------------------------------------------------------------------
    fig, ax = plt.subplots()
    ax.set_aspect('equal')
    ax.triplot(triang, lw=0.5, color='white')

    levels = np.arange(0., 1., 0.025)
    cmap = cm.get_cmap(name='terrain', lut=None)
    ax.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap)
    ax.tricontour(tri_refi,
                  z_test_refi,
                  levels=levels,
                  colors=['0.25', '0.5', '0.5', '0.5', '0.5'],
                  linewidths=[1.0, 0.5, 0.5, 0.5, 0.5])

    ax.set_title("High-resolution tricontouring")

    return getSVG(plt)
Example #14
0
def plotzero():
    handles = []

    plt.rcParams["font.family"] = "Times New Roman"
     
    with sqlite3.connect('negativec_zero_cols_2.db') as conn:
        c = conn.cursor()
        
        query = '''select distinct primary_parameters.pnum from primary_parameters order by pnum;'''
        c.execute(query)
        query_result = c.fetchall()
        sigma = list(query_result)

        query = '''select primary_parameters.pnum, secondary_parameters.Ftotal
                from primary_parameters inner join secondary_parameters on primary_parameters.secondary_id=secondary_parameters.id;'''
        c.execute(query)
        query_result = c.fetchall()
        
        with open('box20x20.msh') as msh:
            get_line = lambda msh=msh: msh.readline().strip()
            
            while get_line() != '$Nodes': pass

            num_of_nodes = int(get_line())
            nodes = [get_line().split(' ') for i in range(num_of_nodes)]
            node_coords = {n[0].strip() : n[1:] for n in nodes}
            
        node_numbers_energies = [(str(v[0]),v[1]) for v in query_result]
        
        node_coords_energies = [(float(node_coords[n[0]][0]), float(node_coords[n[0]][1]), n[1]) for n in node_numbers_energies]
         
        x = np.array([n[0] for n in node_coords_energies])
        y = np.array([n[1] for n in node_coords_energies])
        z = np.array([n[2] for n in node_coords_energies])

        enmean = np.sum(z) / z.size
        z = (z - enmean) / enmean

        zfull = z.max() - z.min()
        zlow = z.min() + zfull*0.0
        zhigh = z.max() - zfull*0.5
        zmin = z.min()
        zmax = z.max()

        triang = tri.Triangulation(x, y)
        refiner = tri.UniformTriRefiner(triang)
        tri_refi, z_refi = refiner.refine_field(z, subdiv=3)
        
        coordinates = extractor_str.get_coords('unscos_pview/')

        sigmas = np.loadtxt('B10Q')
        polars = np.loadtxt('B10P')
        fieldv = sigmas[:len(coordinates)]
        field_min = fieldv.min()
        field_max = fieldv.max()

        for i,pack in enumerate(zip(coordinates[:], fieldv[:])):
            c, fv = pack
            coord = [(x,y,z) for x,y,z in zip(c[0][0::5], c[1][0::5], c[2][0::5])]
            
            x1 = np.array([v[0] for v in coord])
            y1 = np.array([v[1] for v in coord])
            z1 = np.array([v[2] for v in coord])

            z1 = (z1 - z1.min()) / (z1.max() - z1.min())

            fig = plt.figure(figsize=(12,11))
            spec = gridspec.GridSpec(ncols=2, nrows=1, wspace=0.1, hspace=0.1, width_ratios=[9, 0.5])
            mainplot = fig.add_subplot(spec[:, 0])
            energyplot = fig.add_subplot(spec[:, 1])

            from matplotlib.colors import LinearSegmentedColormap
            colors = [(0.0, 0.0, 1.0), (0.0, 1.0, 0.0), (1.0, 0.0, 0.0)]
            cmap_name = 'domwall_map'
            mycm = LinearSegmentedColormap.from_list(cmap_name, colors, N=13)

            cf = mainplot.tricontourf(tri_refi, z_refi, cmap=cm.seismic, levels=np.linspace(zlow, zhigh, 271, endpoint=True))
            cf_ = mainplot.tricontourf(x1, y1, z1, cmap=mycm, alpha=0.4, levels=[0.0, 0.35, 0.65, 1.0])

            from matplotlib.collections import PatchCollection
            from matplotlib.patches import Rectangle

            rect = Rectangle((-50, 0), 100, fv)
            pc = PatchCollection([rect])
            energyplot.add_collection(pc)

            x0m,x1m = mainplot.get_xlim()
            y0m,y1m = mainplot.get_ylim()
            mainplot.set_aspect(abs(x1m-x0m)/abs(y1m-y0m))

            mainplot.set(xlabel=r'Side length (nm)', ylabel=r'Side length (nm)')

            energyplot.set_xlim(0,1)
            energyplot.set_ylim(field_min, field_max)
            energyplot.set_xticks([])
            energyplot.tick_params(axis='y', left=False, right=True, labelleft=False, labelright=True)
            energyplot.yaxis.set_label_position('right')

            energyplot.set(ylabel=r'Surface charge, Q/S (C/m$^{2}$)')

            divider = make_axes_locatable(mainplot)
            cax = divider.new_vertical(size="5%", pad=0.9, pack_start=True)
            fig.add_axes(cax) 
            cb = fig.colorbar(cf, cax=cax, orientation="horizontal", label='Normalized domain wall pinning relief', ticks=[zlow + (zhigh-zlow)/5*i for i in range(6)], format=matplotlib.ticker.FuncFormatter(lambda x, p: '{:.2f}'.format(x*1000)))
            cf.set_clim(zlow, zhigh)

            plt.figtext(0.25, 0.9, 'Domain wall displacement as a responce\n          to the charge at the electrodes', fontsize=24)
            plt.figtext(0.78, 0.1175, 'x 10$^{-3}$', fontsize=20)

            for axv in [mainplot, energyplot, cax]:
                for item in ([axv.title, axv.xaxis.label, axv.yaxis.label]):
                    item.set_fontsize(24)
                for item in (axv.get_xticklabels() + axv.get_yticklabels()):
                    item.set_fontsize(20)

            fig.tight_layout()

            plt.savefig('{}.png'.format(i))
            plt.close()
Example #15
0
def plot_asymmetries_3_dimensions(dist, title=None, nlevels=200, subdiv=4):

    # define the simplex (an equilateral triangle with vertices (0,1), (1,0), and (0.5, 0.5 * tan(60 degrees)
    corners = np.array([[0, 0], [1, 0], [0.5, 0.5 * np.tan(np.pi / 3)]])
    triangle = tri.Triangulation(corners[:, 0], corners[:, 1])

    # compute the cartesian coordinates for the midpoint of each side
    midpoints = [(corners[(i + 1) % 3] + corners[(i + 2) % 3]) / 2.0
                 for i in range(3)]

    def cartesian_to_barycentric(xy, tol=1.e-3):

        # convert Cartesian coordinates to Barycentric
        s = np.array([(corners[i] - midpoints[i]).dot(xy - midpoints[i]) / 0.75
                      for i in range(3)])

        # ensure we are not to close to 0 or 1 for numerical reasons
        s[s < tol] = tol
        s[s > 1 - tol] = 1 - tol

        # normalize the clipped result
        s /= np.sum(s)

        return s

    # set evaluation points
    refiner = tri.UniformTriRefiner(triangle)
    trimesh = refiner.refine_triangulation(subdiv=subdiv)

    # convert to Barycentric coordinates
    pi = np.array(
        [cartesian_to_barycentric(xy) for xy in zip(trimesh.x, trimesh.y)])

    # construct the figure
    rows = 4
    cols = 8
    fig, ax = plt.subplots(rows, cols, figsize=(8, 5))
    ax = np.reshape(ax, -1)
    i_plot = 0

    # set the color map
    cmap = 'jet'

    # plot the expected (symmetric under uniform permutations) distribution
    e_f = [dist.pdf(pi, order=-2) for pi in pi]
    ax[i_plot].tricontourf(trimesh, e_f, nlevels, vmin=0, cmap=cmap)
    ax[i_plot].set_title('$E[f]$', fontsize=FONT_SIZE_SP_TITLE)
    ax[i_plot].set_ylabel('PDF', fontsize=FONT_SIZE_AXIS_LABEL)
    i_plot += 1

    # plot the approximate expected (symmetric under uniform permutations) distribution
    e_f = [dist.pdf(pi, order=-1) for pi in pi]
    ax[i_plot].tricontourf(trimesh, e_f, nlevels, vmin=0, cmap=cmap)
    ax[i_plot].set_title('$\\hat{E}[f]$', fontsize=FONT_SIZE_SP_TITLE)
    i_plot += 1

    # loop over the pdf's associated with each stick-breaking order
    f = []
    for i in range(len(dist.f)):

        # evaluate the probabilities
        f.append([dist.pdf(pi, order=i) for pi in pi])

        # get the ordering
        order = ''.join([str(o + 1) for o in dist.perms[i]])

        # plot the data
        ax[i_plot].tricontourf(trimesh, f[-1], nlevels, vmin=0, cmap=cmap)
        ax[i_plot].set_title('$f_{' + order + '}$',
                             fontsize=FONT_SIZE_SP_TITLE)
        i_plot += 1

    # define possible symmetries
    axes = {0, 1, 2}
    symmetries = [[1, 2], [0, 2], [0, 1]]

    # loop over the symmetries
    asymmetries = []
    barycentric_axes = []
    for symmetry in symmetries:

        # loop over the orders
        for order in range(-2, len(f)):

            # collect asymmetries and its axis
            asymmetries.append(get_asymmetry(dist, order, pi, symmetry))
            barycentric_axes.extend(list(axes - set(symmetry)))

    # loop over the asymmetries
    for asymmetry, axis in zip(asymmetries, barycentric_axes):

        # plot anti-symmetric portion
        ax[i_plot].tricontourf(trimesh,
                               asymmetry,
                               nlevels,
                               vmin=0,
                               vmax=np.max(asymmetries),
                               cmap=cmap)
        if np.mod(i_plot, cols) == 0:
            ax[i_plot].set_ylabel('$x_{' + str(axis + 1) + '}$ Asym.',
                                  fontsize=FONT_SIZE_AXIS_LABEL)
        i_plot += 1

    # make it pretty
    for i in range(len(ax)):
        ax[i].axis('equal')
        ax[i].set_xlim(0, 1)
        ax[i].set_ylim(0, 0.75**0.5)
        ax[i].set_xticks([])
        ax[i].set_yticks([])
        ax[i].spines['top'].set_visible(False)
        ax[i].spines['right'].set_visible(False)
        ax[i].spines['bottom'].set_visible(False)
        ax[i].spines['left'].set_visible(False)

    # add the title if one is provided
    if title is not None:
        fig.suptitle(title, fontsize=FONT_SIZE_FIG_TITLE)

    # make it tight
    plt.subplots_adjust(left=0.04,
                        bottom=0,
                        right=1,
                        top=0.85,
                        wspace=0,
                        hspace=0)
Example #16
0
# 3D example! Woo!

n_dim = 3
B3 = 1.0  # 256.0 #

aa3 = np.array([1.0, 0.2, 0.5])  # np.random.uniform(size=n_dim) #
bb3 = np.array([2.0, 10.0, 4.0])  #np.random.uniform(size=n_dim) #
tt3 = np.zeros(n_dim)

lgs3 = LagrangeSolver(aa3, bb3, tt3, B3)

simplex_corners = np.array([[0, 0], [1, 0], [0.5, 0.75**0.5]])
tri_object = tri.Triangulation(simplex_corners[:, 0], simplex_corners[:, 1])

refiner = tri.UniformTriRefiner(tri_object)
simplex_mesh = refiner.refine_triangulation(subdiv=6)


def simplex2cart(a, b, c):
    x = .5 * (2 * b + c)
    y = np.sqrt(3) / 2 * c
    return x, y


def cart2simplex(x, y):
    c = y * 2 / np.sqrt(3)
    b = x - c / 2
    a = 1 - b - c
    return a, b, c
Example #17
0
            },
        },
        open('limits.json', 'w'),
        indent=2)

    writer.writerows(lines)

    # Center and scale
    x_points = np.array(x_data) - np.mean(x_data)
    y_points = np.array(y_data) - np.mean(y_data)
    z_points = np.array(z_data)

    # make delaunai triangulation
    triangulation = tri.Triangulation(x_points, y_points)

    refiner = tri.UniformTriRefiner(triangulation)
    tri_refi, z_test_refi = refiner.refine_field(z_points, subdiv=3)

    plt.gca().set_aspect('equal')
    plt.triplot(triangulation, lw=1, color='gray')

    levels = np.arange(int(min(z_data)), int(max(z_data)), 1)
    cmap = cm.get_cmap(name='bone', lut=None)
    # plt.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap)
    plt.tricontour(
        tri_refi,
        z_test_refi,
        levels=levels,
        colors=['0.25', '0.5', '0.5', '0.5', '0.5'],
        linewidths=[1.0, 0.5, 0.5, 0.5, 0.5],
    )
Example #18
0
def draw_func_contours(func,
                       labels=None,
                       nlevels=200,
                       subdiv=8,
                       fig=None,
                       ax=None,
                       grid=True,
                       **kwargs):
    '''
    Parameters:
    -----------
    labels: None, string or list of strings
        If labels == 'auto' it shows the class number on each corner
        If labels is a list of strings it shows each string in the
        corresponding corner
        If None does not show any label
    '''
    corners = np.array([[0, 0], [1, 0], [0.5, 0.75**0.5]])
    triangle = tri.Triangulation(corners[:, 0], corners[:, 1])

    refiner = tri.UniformTriRefiner(triangle)
    trimesh = refiner.refine_triangulation(subdiv=subdiv)

    pvals = np.array([func(xy2bc(xy)) for xy in zip(trimesh.x, trimesh.y)])

    if fig is None:
        fig = plt.figure()
    if ax is None:
        ax = fig.add_subplot(111)

    # FIXME I would like the following line to work, but the max value is not
    # shown. I had to do create manually the levels and increase the max value
    # by an epsilon. This could be a major problem if the epsilon is not small
    # for the original range of values
    # contour = ax.tricontourf(trimesh, pvals, nlevels, **kwargs)
    # contour = ax.tricontourf(trimesh, pvals, nlevels, extend='both')
    contour = ax.tricontourf(trimesh,
                             pvals,
                             levels=np.linspace(pvals.min(),
                                                pvals.max() + 1e-9, nlevels),
                             **kwargs)

    # Colorbar
    cb = fig.colorbar(contour, ax=ax, fraction=0.1, orientation='horizontal')
    tick_locator = ticker.MaxNLocator(nbins=5)
    cb.locator = tick_locator
    # cb.ax.xaxis.set_major_locator(ticker.AutoLocator())
    cb.update_ticks()

    if labels is not None:
        if labels == 'auto':
            labels = [r'$C_{}$'.format(i + 1) for i in range(len(corners))]
        center = corners.mean(axis=0)
        for i, corner in enumerate(corners):
            text_x, text_y = corner - (center - corner) * 0.1
            ax.text(text_x,
                    text_y,
                    labels[i],
                    verticalalignment='center',
                    horizontalalignment='center')

    triangle = tri.Triangulation(corners[:, 0], corners[:, 1])

    if grid:
        refiner = tri.UniformTriRefiner(triangle)
        trimesh = refiner.refine_triangulation(subdiv=4)
        ax.triplot(trimesh, c='gray', lw=0.2)

    ax.triplot(triangle, c='k', lw=0.8)

    # Axes options
    ax.set_xlim(xmin=0, xmax=1)
    ax.set_ylim(ymin=0, ymax=0.75**0.5)
    ax.set_xbound(lower=0, upper=1)
    ax.set_ybound(lower=0, upper=0.75**0.5)
    ax.axis('equal')
    ax.axis('off')
    plt.gca().set_adjustable("box")
def test_tri_smooth_gradient():
    # Image comparison based on example trigradient_demo.

    def dipole_potential(x, y):
        """ An electric dipole potential V """
        r_sq = x**2 + y**2
        theta = np.arctan2(y, x)
        z = np.cos(theta) / r_sq
        return (np.max(z) - z) / (np.max(z) - np.min(z))

    # Creating a Triangulation
    n_angles = 30
    n_radii = 10
    min_radius = 0.2
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi / n_angles
    x = (radii * np.cos(angles)).flatten()
    y = (radii * np.sin(angles)).flatten()
    V = dipole_potential(x, y)
    triang = mtri.Triangulation(x, y)
    xmid = x[triang.triangles].mean(axis=1)
    ymid = y[triang.triangles].mean(axis=1)
    mask = np.where(xmid * xmid + ymid * ymid < min_radius * min_radius, 1, 0)
    triang.set_mask(mask)

    # Refine data - interpolates the electrical potential V
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)

    # Computes the electrical field (Ex, Ey) as gradient of -V
    tci = mtri.CubicTriInterpolator(triang, -V)
    (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
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(triang, color='0.8')

    levels = np.arange(0., 1., 0.01)
    cmap = cm.get_cmap(name='hot', lut=None)
    plt.tricontour(tri_refi,
                   z_test_refi,
                   levels=levels,
                   cmap=cmap,
                   linewidths=[2.0, 1.0, 1.0, 1.0])
    # Plots direction of the electrical vector field
    plt.quiver(triang.x,
               triang.y,
               Ex / E_norm,
               Ey / E_norm,
               units='xy',
               scale=10.,
               zorder=3,
               color='blue',
               width=0.007,
               headwidth=3.,
               headlength=4.)
    plt.show()
Example #20
0
def plot_ternary(distribute_func, n_levels=200, subdiv=8, **kwargs):
    corners = np.array([[0, 0], [1, 0], [0.5, 0.75**0.5]])  # cos(30)
    triangle = tri.Triangulation(corners[:, 0], corners[:, 1])
    # Mid-points of triangle sides opposite of each corner

    RI = np.linalg.inv(np.vstack((corners.T, [1, 1, 1])))

    def xy2bc(xys, tol=1.e-3):
        '''
        Converts 2D Cartesian coordinates to barycentric.
        according to https://en.wikipedia.org/wiki/Barycentric_coordinate_system#Conversion_between_barycentric_and_Cartesian_coordinates'''
        xysT = np.transpose(xys)
        ones = [1] * len(xys)
        xysT1 = np.vstack((xysT, ones))
        lambda_ = RI.dot(xysT1).T
        return np.clip(lambda_, a_min=tol, a_max=1.0 - tol)

    def tick_labels(scale=100, size=20):
        return [
            str(int(i))
            for i in np.arange(0, scale / size * (size + 1), scale / size)
        ]

    def tick_txy(location, width=1.0, size=20):
        height = width * 0.75**0.5
        if location == 'left':
            xy = np.array((
                np.arange(0, width / 2 / size * (size + 1), width / 2 / size),
                np.arange(0, height / size * (size + 1), height / size),
            ))
            return xy[0, :][::-1], xy[1, :][::-1]
        if location == 'right':
            xy = np.array((
                np.arange(0.5, 0.5 + width / 2 / size * (size + 1),
                          width / 2 / size),
                np.arange(0, height / size * (size + 1), height / size),
            ))
            return xy[0, :][::-1], xy[1, :]
        if location == 'bottom':
            xy = np.array((
                np.arange(0, width / size * (size + 1), width / size),
                np.array((0.0, ) * (size + 1)),
            ))
            return xy[0, :], xy[1, :]

    refiner = tri.UniformTriRefiner(triangle)
    trimesh = refiner.refine_triangulation(subdiv=subdiv)
    bc = xy2bc(list(zip(trimesh.x, trimesh.y)))
    pvals = distribute_func(bc)
    fig = plt.figure()
    ax = fig.add_subplot(111, aspect='equal')
    ax.triplot(triangle, color='black')
    trimap = ax.tricontourf(trimesh, pvals, n_levels, **kwargs)
    # trimap = ax.tricontourf(x,y,t,n_levels,**kwargs)
    offset = 0.02
    linewidth = 1.
    for x, y, s in zip(*tick_txy('left'), tick_labels()):
        ax.text(x - offset / 2,
                y + 0.75**0.5 * offset,
                s,
                verticalalignment='center',
                horizontalalignment='right')
        ax.plot((x, x - offset / 2), (y, y + 0.75**0.5 * offset),
                '-',
                lw=linewidth,
                color='black')
    for x, y, s in zip(*tick_txy('right'), tick_labels()):
        ax.text(x + offset / 2,
                y,
                s,
                verticalalignment='center',
                horizontalalignment='left')
        ax.plot((x, x + offset / 2), (y, y), '-', lw=linewidth, color='black')
    for x, y, s in zip(*tick_txy('bottom'), tick_labels()):
        ax.text(x - offset / 2,
                y - 0.75**0.5 * offset,
                s,
                verticalalignment='top',
                horizontalalignment='center')
        ax.plot((x, x - offset / 2), (y, y - 0.75**0.5 * offset),
                '-',
                lw=linewidth,
                color='black')
    '''
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    divider = make_axes_locatable(plt.gca())
    cax = divider.append_axes("right", "5%", pad="-8%")
    fig.colorbar(trimap, cax=cax)
    '''
    fig.colorbar(trimap)
    ax.set_aspect('equal')
    fig.tight_layout(pad=0)
    ax.axis('equal')
    # ax.set_xlim(0, 1)
    # ax.set_ylim(-0.02, 0.75**0.5+0.02)
    ax.axis('off')
    return fig
Example #21
0
def contour_plot(local_to_global, nodes_to_coordinates, u_h):

    x = nodes_to_coordinates[:, 0]  #.transpose()
    y = nodes_to_coordinates[:, 1]  #.transpose()
    triangulation = tri.Triangulation(x, y, local_to_global)

    N_fe = local_to_global.shape[0]

    u_max = u_h.max()
    u_min = u_h.min()

    umin2 = u_min - 0.05 * abs(u_max - u_min)
    umax2 = u_max + 0.05 * abs(u_max - u_min)

    levels = np.arange(u_min - 0.05 * abs(u_max - u_min),
                       u_max + 0.05 * abs(u_max - u_min),
                       abs(u_max - u_min) / 25.)

    #levels = np.arange(-1.1, 1.1, 0.1)

    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.7, 0.8])
    ax.set_xlim((-1, 1))  #fix constants
    ax.set_ylim((-1, 1))

    for r in range(0, N_fe):
        i1 = local_to_global[r, 0]
        i2 = local_to_global[r, 1]
        i3 = local_to_global[r, 2]

        x1 = nodes_to_coordinates[i1, 0]
        x2 = nodes_to_coordinates[i2, 0]
        x3 = nodes_to_coordinates[i3, 0]
        y1 = nodes_to_coordinates[i1, 1]
        y2 = nodes_to_coordinates[i2, 1]
        y3 = nodes_to_coordinates[i3, 1]

        t = tri.Triangulation(x[[i1, i2, i3]], y[[i1, i2, i3]])
        r = tri.UniformTriRefiner(t)

        # zX = t.x.copy()
        # zX[0] = u_h[i1]
        # zX[1] = u_h[i2]
        # zX[2] = u_h[i3]

        #zX = np.array([u_h[i1],u_h[i2],u_h[i3]])

        #print(t.x)
        #print(zX)
        refi_t = r.refine_triangulation(subdiv=2)

        rx = refi_t.x.copy()
        ry = refi_t.y.copy()

        detJ = x2 * y3 - x2 * y1 - x1 * y3 - x3 * y2 + x3 * y1 + x1 * y2

        rx2 = rx.copy()
        ry2 = ry.copy()

        for i in range(0, rx.shape[0]):  #buggy?

            rx[i] = (y3 - y1) * (rx2[i] - x1) + (-x3 + x1) * (ry2[i] - y1)
            ry[i] = (-y2 + y1) * (rx2[i] - x1) + (x2 - x1) * (ry2[i] - y1)

        rx = 1. / detJ * rx
        ry = 1. / detJ * ry

        #local functions
        phi1 = 1 - rx - ry
        phi2 = rx
        phi3 = ry

        #print('rx = '+ str(rx))
        #print('ry = '+ str(ry))

        #add weights
        phi = u_h[i1] * phi1 + u_h[i2] * phi2 + u_h[i3] * phi3
        #print(phi)
        r2 = tri.UniformTriRefiner(refi_t)

        t2, z2 = r2.refine_field(phi, subdiv=3)

        #ax.tricontourf(t2, z2, cmap='cool', levels=levels)
        #t2, z2 = r.refine_field(zX, subdiv=2)
        ax.tricontour(t2, z2, cmap='cool', levels=levels)

        #plt.triplot(refi_t, color='g')

    ax.triplot(triangulation, color='0.5', lw=0.2)

    #ax2 = fig.add_axes([0.82, 0.1, 0.85, 0.8])
    ax2 = fig.add_axes([0.85, 0.1, 0.02, 0.8])
    norm = matplotlib.colors.Normalize(vmin=umin2, vmax=umax2)
    cb1 = matplotlib.colorbar.ColorbarBase(ax2,
                                           cmap='cool',
                                           norm=norm,
                                           orientation='vertical')

    plt.savefig('images/tri_sol.png', dpi=300)
    pass
Example #22
0
    def __init__(self, order=2):
        self.order = order
        x = np.asarray([-1, 1, -1])
        y = np.asarray([-1, -1, 1])
        tri = mtri.Triangulation(x, y)
        refiner = mtri.UniformTriRefiner(tri)
        fine_tri = refiner.refine_triangulation(subdiv=9)

        xi_1 = fine_tri.x
        xi_2 = fine_tri.y

        lamda = np.zeros((3, len(xi_1)))
        dlamda = [np.zeros((3, len(xi_1))), np.zeros((3, len(xi_1)))]

        lamda[0, :] = (xi_2 + 1.) / 2.
        dlamda[1][0, :] = 1. / 2.
        lamda[1, :] = -(xi_1 + xi_2) / 2.
        dlamda[0][1, :] = -1. / 2.
        dlamda[1][1, :] = -1. / 2.
        lamda[2, :] = (xi_1 + 1.) / 2.
        dlamda[0][2, :] = 1. / 2.

        # Number of Shape Functions
        self.nb_v = 3
        self.nb_e = 3 * (order - 1)
        self.nb_f = int(((order - 1) * (order - 2)) / 2)
        self.nb_SF = self.nb_v + self.nb_e + self.nb_f
        # Initialisation of Shape Functions and derivatives
        self.Phi = np.zeros((self.nb_SF, len(xi_1)))
        self.dPhi = [
            np.zeros((self.nb_SF, len(xi_1))),
            np.zeros((self.nb_SF, len(xi_1)))
        ]

        # Vertices Shape Functions
        self.Phi[0, :], self.Phi[1, :], self.Phi[2, :] = lamda[1, :], lamda[
            2, :], lamda[0, :]
        for _xi in range(2):
            self.dPhi[_xi][0, :], self.dPhi[_xi][1, :], self.dPhi[_xi][
                2, :] = dlamda[_xi][1, :], dlamda[_xi][2, :], dlamda[_xi][0, :]
        # Edge Shape Functions
        for _o in range(order - 1):
            _index_edge = [
                3 + _o, 3 + (order - 1) + _o, 3 + 2 * (order - 1) + _o
            ]
            for i_e in range(3):
                self.Phi[_index_edge[i_e], :] = lamda[
                    (i_e + 1) % 3, :] * lamda[(i_e + 2) % 3, :] * phi(
                        _o,
                        lamda[(i_e + 2) % 3, :] - lamda[(i_e + 1) % 3, :])[0]
                for _xi in range(2):
                    self.dPhi[_xi][_index_edge[i_e], :] += dlamda[_xi][
                        (i_e + 1) % 3, :] * lamda[(i_e + 2) % 3, :] * phi(
                            _o, lamda[(i_e + 2) % 3, :] -
                            lamda[(i_e + 1) % 3, :])[0]
                    self.dPhi[_xi][_index_edge[i_e], :] += dlamda[_xi][
                        (i_e + 2) % 3, :] * lamda[(i_e + 1) % 3, :] * phi(
                            _o, lamda[(i_e + 2) % 3, :] -
                            lamda[(i_e + 1) % 3, :])[0]
                    self.dPhi[_xi][_index_edge[i_e], :] += lamda[
                        (i_e + 1) % 3, :] * lamda[(i_e + 2) % 3, :] * phi(
                            _o, lamda[(i_e + 2) % 3, :] -
                            lamda[(i_e + 1) % 3, :])[1] * (
                                dlamda[_xi][(i_e + 2) % 3, :] -
                                dlamda[_xi][(i_e + 1) % 3, :])
        # Face Shape Functions
        _index = self.nb_v + self.nb_e
        for n_1 in range(1, order - 1):
            for n_2 in range(1, n_1 + 1):
                self.Phi[
                    _index, :] = lamda[0, :] * lamda[1, :] * lamda[2, :] * phi(
                        n_1 - 1, lamda[2, :] - lamda[1, :])[0] * phi(
                            n_2 - 1, lamda[1, :] - lamda[0, :])[0]
                for _xi in range(2):
                    self.dPhi[_xi][_index, :] += dlamda[_xi][
                        0, :] * lamda[1, :] * lamda[2, :] * phi(
                            n_1 - 1, lamda[2, :] - lamda[1, :])[0] * phi(
                                n_2 - 1, lamda[1, :] - lamda[0, :])[0]
                    self.dPhi[_xi][_index, :] += dlamda[_xi][
                        1, :] * lamda[0, :] * lamda[2, :] * phi(
                            n_1 - 1, lamda[2, :] - lamda[1, :])[0] * phi(
                                n_2 - 1, lamda[1, :] - lamda[0, :])[0]
                    self.dPhi[_xi][_index, :] += dlamda[_xi][
                        2, :] * lamda[1, :] * lamda[0, :] * phi(
                            n_1 - 1, lamda[2, :] - lamda[1, :])[0] * phi(
                                n_2 - 1, lamda[1, :] - lamda[0, :])[0]
                    self.dPhi[_xi][_index, :] += lamda[
                        0, :] * lamda[1, :] * lamda[2, :] * phi(
                            n_1 - 1, lamda[2, :] - lamda[1, :])[1] * (
                                dlamda[_xi][2, :] - dlamda[_xi][1, :]) * phi(
                                    n_2 - 1, lamda[1, :] - lamda[0, :])[0]
                    self.dPhi[_xi][_index, :] += lamda[
                        0, :] * lamda[1, :] * lamda[2, :] * phi(
                            n_2 - 1, lamda[1, :] - lamda[0, :])[1] * (
                                dlamda[_xi][1, :] - dlamda[_xi][0, :]) * phi(
                                    n_1 - 1, lamda[2, :] - lamda[1, :])[0]
                _index += 1

        i_SF = 14
        plt.figure()
        plt.tricontourf(fine_tri, self.Phi[i_SF, :], cmap=cm.jet, levels=10)
        plt.colorbar()
        plt.show()
Example #23
0
def plot2dHeatMap(BrutX,
                  BrutY,
                  BrutZ,
                  QuantityTitle,
                  filename,
                  ShowFinalPlot=True):  #{{{
    Header = "[plot2dHeatMap: ]"
    #print len(BrutX)
    #print len(BrutY)
    #print len(BrutZ)
    X = list(set(BrutX))
    Y = list(BrutY)
    #Z=DensityMax2Dsorted
    YY, XX = np.meshgrid(X, Y)
    # If the size is big enough, let's make a plot.
    #if(len(DensityMax2D) >= 2): #{{{
    if (len(BrutZ) >= 2):  #{{{
        ##try:
        triang = tri.Triangulation(BrutX, BrutY)
        triang.set_mask(
            np.hypot(BrutX[triang.triangles].mean(
                axis=1), BrutY[triang.triangles].mean(axis=1)) < 0.000000015)
        refiner = tri.UniformTriRefiner(triang)
        tri_refi, z_test_refi = refiner.refine_field(BrutZ, subdiv=3)
        #plt.figure()
        #plt.title(r'$N_{exc}(E_1,E_2)$, $\lambda_1=$'+str(wavelength1*1E9)+r'nm, $\lambda_2=$'+str(wavelength2*1E9)+'nm.')
        fig = plt.figure()
        #ax = fig.add_subplot(111) #, projection='3d')
        ##plt.gca().set_aspect('equal')
        plt.title(QuantityTitle)
        ##plt.xlabel(r'$E_1$ (V/nm)')
        ##plt.ylabel(r'$E_2$ (V/nm)')
        ##CS = plt.imshow(XX, YY, DensityMax2Dsorted) #, cmap=plt.cm.Blues)
        ##CS = plt.contourf(XX, YY, DensityMax2Dsorted, cmap=plt.cm.Blues)
        ##CS = ax.plot_wireframe(XX, YY, DensityMax2Dsorted) #, cmap=plt.cm.Blues) #FAILS: WHY do we have ground values ?!
        ##CS = ax.plot_surface(XX, YY, DensityMax2DsortedShape) #, cmap=plt.cm.Blues) #FAILS: WHY do we have ground values ?!
        #CS = ax.scatter(BrutX, BrutY, BrutZ) #, cmap=plt.cm.Blues) #WORKS but limited to boring dots
        #CS = ax.plot_trisurf(BrutX, BrutY, BrutZ, cmap=plt.cm.Blues, antialiased=True, edgecolor='none') #WORKS
        ##ax.view_init(90, 90)
        ##See https://matplotlib.org/gallery/images_contours_and_fields/tricontour_smooth_user.html#sphx-glr-gallery-images-contours-and-fields-tricontour-smooth-user-py

        plt.triplot(triang, lw=0.1, color='grey')
        #levels = np.linspace(np.min(BrutZ), np.max(BrutZ), 10)
        levels = np.linspace(0, 100, 10)
        #cmap = cm.get_cmap(name='terrain', lut=None)
        #cmap = cm.get_cmap(name='Blues', lut=None)
        cmap = cm.get_cmap(name='BuPu', lut=None)
        plt.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap)
        #plt.tricontour(tri_refi, z_test_refi, levels=levels,
        ##colors=['0.25', '0.5', '0.5', '0.5', '0.5'],
        ##linewidths=[1.0, 0.5, 0.5, 0.5, 0.5])
        plt.colorbar()
        plt.tight_layout()
        #except:
        #CS = -1
        #print Header+"** Warning: failed to produce one of the plots."

        #print np.shape(BrutX), np.shape(BrutY), np.shape(BrutZ)
        #print np.shape(Xi), np.shape(Yi)
        #print np.shape(XXi), np.shape(YYi)
        #print np.shape(BicolorNeFinal)

        #CS = ax.scatter(XXi, YYi, BicolorNeFinal) #, cmap=plt.cm.Blues) #WORKS

        #CS = ax.plot_trisurf(Xi, Yi, BicolorNeFinal, cmap=plt.cm.Spectral)

        #CS = ax.contour(XX, YY, Z, cmap=plt.cm.Blues) #WORKS
        #plt.colorbar(CS)

        plt.savefig(filename + '.eps')
        plt.savefig(filename + '.png')
        print(Header, "** Info: saved ", filename, "png|eps.")
        if (ShowFinalPlot):
            plt.show()
Example #24
0
class simplex_dynamics:
    '''draws dynamics of given function and 
    corresponding fixed points into triangle'''
    #corners of triangle and calculation of points
    r0 = np.array([0, 0])
    r1 = np.array([1, 0])
    r2 = np.array([1 / 2., np.sqrt(3) / 2.])
    corners = np.array([r0, r1, r2])
    triangle = tri.Triangulation(corners[:, 0], corners[:, 1])
    refiner = tri.UniformTriRefiner(triangle)
    trimesh = refiner.refine_triangulation(subdiv=5)
    trimesh_fine = refiner.refine_triangulation(subdiv=5)

    def __init__(self, fun):
        self.f = fun
        self.calculate_stationary_points()
        self.calc_direction_and_strength()

    #barycentric coordinates
    def xy2ba(self, x, y):
        corner_x = self.corners.T[0]
        corner_y = self.corners.T[1]
        x_1 = corner_x[0]
        x_2 = corner_x[1]
        x_3 = corner_x[2]
        y_1 = corner_y[0]
        y_2 = corner_y[1]
        y_3 = corner_y[2]
        l1 = ((y_2 - y_3) * (x - x_3) + (x_3 - x_2) *
              (y - y_3)) / ((y_2 - y_3) * (x_1 - x_3) + (x_3 - x_2) *
                            (y_1 - y_3))
        l2 = ((y_3 - y_1) * (x - x_3) + (x_1 - x_3) *
              (y - y_3)) / ((y_2 - y_3) * (x_1 - x_3) + (x_3 - x_2) *
                            (y_1 - y_3))
        l3 = 1 - l1 - l2
        return np.array([l1, l2, l3])

    def ba2xy(self, x):
        ### x: array of 3-dim ba coordinates
        ### corners: coordinates of corners of ba coordinate system
        x = np.array(x)
        # print(self.corners.shape)
        # print(self.corners.T)
        # print(x)
        return self.corners.T.dot(x.T).T

    def calculate_stationary_points(self):
        fp_raw = []
        border = 5  #don't check points close to simplex border
        delta = 1e-12
        for x, y in zip(self.trimesh.x[border:-border],
                        self.trimesh.y[border:-border]):
            start = self.xy2ba(x, y)
            fp_try = np.array([])

            sol = scipy.optimize.root(
                self.f, start, args=(0, ),
                method="hybr")  #,xtol=1.49012e-10,maxfev=1000
            if sol.success:
                fp_try = sol.x
                #check if FP is in simplex
                if not math.isclose(np.sum(fp_try), 1., abs_tol=2.e-3):
                    continue
                if not np.all((fp_try > -delta)
                              & (fp_try < 1 + delta)):  #only if fp in simplex
                    continue
            else:
                continue
            #only add new fixed points to list
            if not np.array(
                [np.allclose(fp_try, x, atol=1e-7) for x in fp_raw]).any():
                fp_raw.append(fp_try.tolist())
        #add fixed points in correct coordinates to fixpoints list
        fp_raw = np.array(fp_raw)
        if fp_raw.shape[0] > 0:
            self.fixpoints = self.corners.T.dot(np.array(fp_raw).T).T
        else:
            self.fixpoints = np.array([])

    def calc_direction_and_strength(self):
        direction = [
            self.f(self.xy2ba(x, y), 0)
            for x, y in zip(self.trimesh.x, self.trimesh.y)
        ]
        self.direction_norm = np.array([
            self.ba2xy(v) /
            np.linalg.norm(v) if np.linalg.norm(v) > 0 else np.array([0, 0])
            for v in direction
        ])
        self.direction_norm = self.direction_norm
        #print(direction_ba_norm)
        self.pvals = [np.linalg.norm(v) for v in direction]
        self.direction = np.array([self.ba2xy(v) for v in direction])

    def plot_simplex(self,
                     ax,
                     cmap='viridis',
                     typelabels=["A", "B", "C"],
                     **kwargs):

        ax.triplot(self.triangle, linewidth=0.8, color="black")
        ax.tricontourf(self.trimesh,
                       self.pvals,
                       alpha=0.8,
                       cmap=cmap,
                       **kwargs)

        #arrow plot options:
        # Q = ax.quiver(self.trimesh.x, self.trimesh.y, self.direction_norm.T[0],self.direction_norm.T[1],self.pvals,angles='xy',pivot='mid',  cmap=cmap)#pivot='tail',
        Q = ax.quiver(self.trimesh.x,
                      self.trimesh.y,
                      self.direction_norm.T[0],
                      self.direction_norm.T[1],
                      angles='xy',
                      pivot='mid')  #pivot='tail')#
        # Q = ax.quiver(self.trimesh.x, self.trimesh.y, self.direction.T[0],self.direction.T[1],angles='xy',pivot='mid')#pivot='tail')#

        ax.axis('equal')
        ax.axis('off')
        margin = 0.01
        ax.set_ylim(ymin=-margin, ymax=self.r2[1] + margin)
        ax.set_xlim(xmin=-margin, xmax=1. + margin)

        #timescatter=ax.scatter(points[::5,0],points[::5,1],c=t[::5],linewidth=0.0,cmap='viridis',alpha=.5)
        if self.fixpoints.shape[0] > 0:
            ax.scatter(self.fixpoints[:, 0],
                       self.fixpoints[:, 1],
                       facecolors='none',
                       edgecolors='black',
                       s=70,
                       linewidth=0.3)
        #fig.colorbar(timescatter,label="time")
        ax.annotate(typelabels[0], (0, 0),
                    xytext=(-0.0, -0.02),
                    horizontalalignment='center',
                    va='top')
        ax.annotate(typelabels[1], (1, 0),
                    xytext=(1.0, -0.02),
                    horizontalalignment='center',
                    va='top')
        ax.annotate(typelabels[2],
                    self.corners[2],
                    xytext=self.corners[2] + np.array([0.0, 0.02]),
                    horizontalalignment='center',
                    va='bottom')
Example #25
0
def ternary_plot(data_fn):

    reader = pd.read_csv(data_fn)

    SQRT3 = numpy.sqrt(3)
    SQRT3OVER2 = SQRT3 / 2.

    def unzip(l):
        return zip(*l)

    def permute_point(p, permutation=None):
        if not permutation:
            return p
        return [p[int(permutation[i])] for i in range(len(p))]

    def project_point(p, permutation=None):
        permuted = permute_point(p, permutation=permutation)
        a = permuted[0]
        b = permuted[1]
        x = a + b / 2.
        y = SQRT3OVER2 * b
        return numpy.array([x, y])

    def project_sequence(s, permutation=None):
        xs, ys = unzip([project_point(p, permutation=permutation) for p in s])
        return xs, ys

    data = []
    for i, (a, b, c) in reader.iterrows():
        a_ = a / (a + b + c)
        b_ = b / (a + b + c)
        c_ = c / (a + b + c)
        data.append((a_, b_, c_))

    xs, ys = project_sequence(data)
    vs = (1, 2, 3)

    fig = plt.figure(num=None,
                     figsize=(10, 6),
                     dpi=80,
                     facecolor='w',
                     edgecolor='k')
    corners = numpy.array([[0, 0], [1, 0], [0.5, numpy.sqrt(3) * 0.5 * 1]])
    triangle = tri.Triangulation(corners[:, 0], corners[:, 1])

    # creating the grid
    refiner = tri.UniformTriRefiner(triangle)
    trimesh = refiner.refine_triangulation(subdiv=4)

    #plotting the colorbar
    colormap = plt.cm.get_cmap('Reds')

    #plotting the mesh
    plt.triplot(trimesh, '', color='0.9', zorder=1)

    #plotting the points
    plt.scatter(xs, ys, c=vs, s=100, zorder=10, cmap=colormap)
    for i in range(len(xs)):
        plt.text(xs[i] + 0.001, ys[i] + 0.001, 'Samp-' + str(i))
    plt.tricontourf(xs, ys, triangle.triangles, vs)

    #plotting the axes
    plt.plot([corners[0][0], corners[1][0]], [corners[0][1], corners[1][1]],
             color='0.7',
             linestyle='-',
             linewidth=2)
    plt.plot([corners[0][0], corners[2][0]], [corners[0][1], corners[2][1]],
             color='0.7',
             linestyle='-',
             linewidth=2)
    plt.plot([corners[1][0], corners[2][0]], [corners[1][1], corners[2][1]],
             color='0.7',
             linestyle='-',
             linewidth=2)

    def plot_ticks(start, stop, tick, n):
        r = numpy.linspace(0, 1, num=10)
        xs = start[0] * (1 - r) + stop[0] * r
        xs = numpy.vstack((xs, xs + tick[0]))
        ys = start[1] * (1 - r) + stop[1] * r
        ys = numpy.vstack((ys, ys + tick[1]))
        for i in range(0, len(xs.tolist()[1])):
            x = xs.tolist()[1][i]
            y = ys.tolist()[1][i]
            plt.text(x, y, i, ha='center')
        plt.plot(xs, ys, 'k', lw=1, color='0.7')

    n = 10
    tick_size = 0.2
    margin = 0.1

    left = corners[0]
    right = corners[1]
    top = corners[2]

    # define vectors for ticks
    bottom_tick = tick_size * (right - top) / n
    right_tick = tick_size * (top - left) / n
    left_tick = tick_size * (left - right) / n

    # plot_ticks(left, right, bottom_tick, n)
    # plot_ticks(right, top, right_tick, n)
    # plot_ticks(left, top, left_tick, n)

    names = [reader[column].name for column in reader]

    plt.text(left[0] - 0.01,
             left[1],
             names[2],
             horizontalalignment='right',
             fontsize=15,
             color='b')
    plt.text(right[0],
             right[1],
             names[0],
             horizontalalignment='left',
             fontsize=15,
             color='b')
    plt.text(top[0], top[1], names[1], fontsize=15, color='b')

    plt.colorbar(label="Sample density")
    #
    # plt.savefig('chart.png')
    plt.show()
Example #26
0
with helper.Timer('blup'):

    plt.figure()
    levels = np.arange(1., 4, 0.1)

    #x =np.array

    for t in my_tri.triangles:

        t1 = mtri.Triangulation(x[t], y[t])
        z1 = f_z(x[t], y[t])

        #print(z1)

        r1 = mtri.UniformTriRefiner(t1)
        #

        t1r, z1r = r1.refine_field(z1, subdiv=3)

        plt.tricontourf(t1r, z1r, cmap='cool', levels=levels)
        plt.tricontour(t1r, z1r, levels=levels)

    plt.triplot(my_tri, color='r')

    plt.savefig('images/tri_test.png', dpi=300)

# refiner = mtri.UniformTriRefiner(my_tri)

# my_tri2, index = refiner.refine_triangulation(subdiv=1, return_tri_index=True)
Example #27
0
def pcolor_map(coordinates,
               data,
               projection='mollweide',
               limits=None,
               cmap=cm.viridis,
               show=True,
               refine=False,
               **kwargs):
    """
    Plot the map projection of data points sampled on a spherical surface.
    The data has to be real.

    Notes
    -----
    In case limits are given, all out of bounds data will be clipped to the
    respective limit.

    Parameters
    ----------
    latitude: ndarray, double
        Geodetic latitude angle of the map, must be in [-pi/2, pi/2]
    longitude: ndarray, double
        Geodetic longitude angle of the map, must be in [-pi, pi]
    data: ndarray, double
        Data for each angle, must have size corresponding to the number of
        points given in coordinates.
    show : boolean, optional
        Wheter to show the figure or not

    """
    tri = mtri.Triangulation(coordinates.longitude, coordinates.latitude)
    if refine is not None:
        if isinstance(refine, int):
            subdiv = refine
        else:
            subdiv = 2
        refiner = mtri.UniformTriRefiner(tri)
        tri, data = refiner.refine_field(
            data,
            triinterpolator=mtri.LinearTriInterpolator(tri, data),
            subdiv=subdiv)

    fig = plt.gcf()

    ax = plt.axes(projection=projection)

    ax.set_xlabel('Longitude [$^\\circ$]')
    ax.set_ylabel('Latitude [$^\\circ$]')

    extend = 'neither'
    if limits is None:
        limits = (data.min(), data.max())
    else:
        mask_min = data < limits[0]
        data[mask_min] = limits[0]
        mask_max = data > limits[1]
        data[mask_max] = limits[1]
        if np.any(mask_max) & np.any(mask_min):
            extend = 'both'
        elif np.any(mask_max) & ~np.any(mask_min):
            extend = 'max'
        elif ~np.any(mask_max) & np.any(mask_min):
            extend = 'min'

    cf = ax.tripcolor(tri,
                      data,
                      cmap=cmap,
                      vmin=limits[0],
                      vmax=limits[1],
                      **kwargs)

    plt.grid(True)
    cb = fig.colorbar(cf, ax=ax, extend=extend)
    cb.set_label('Amplitude')
    if show:
        plt.show()

    return cf
z = function_z(x, y)

# Now create the Triangulation.
# (Creating a Triangulation without specifying the triangles results in the
# Delaunay triangulation of the points.)
triang = tri.Triangulation(x, y)

# 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
# -----------------------------------------------------------------------------
refiner = tri.UniformTriRefiner(triang)
tri_refi, z_test_refi = refiner.refine_field(z, subdiv=3)

# -----------------------------------------------------------------------------
# Plot the triangulation and the high-res iso-contours
# -----------------------------------------------------------------------------
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.triplot(triang, lw=0.5, color='white')

levels = np.arange(0., 1., 0.025)
cmap = cm.get_cmap(name='terrain', lut=None)
ax.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap)
ax.tricontour(tri_refi, z_test_refi, levels=levels,
              colors=['0.25', '0.5', '0.5', '0.5', '0.5'],
              linewidths=[1.0, 0.5, 0.5, 0.5, 0.5])
Example #29
0
# Building parametrisation of the surface
s = np.zeros(np.shape(XS)[0])
t = np.zeros(np.shape(XS)[0])
begin = 0
end = 0
for g in range(np.shape(sample_data)[0]):
    cut = np.argwhere(XS == g).flatten()
    begin = end
    end += np.size(cut, 0)
    X_loc = XS[cut]
    Y_loc = YS[cut]
    Z_loc = ZS[cut]
    s[begin:end] = g / float(np.size(sample_data, 0))
    t[begin:end] = re_ordinate(Y_loc, Z_loc)
    #ax.plot(X_loc, Y_loc, Z_loc, color="grey")

triangles = mtri.Triangulation(s, t).triangles
refiner = mtri.UniformTriRefiner(mtri.Triangulation(s, t))

subdiv = 2
_, x_refi = refiner.refine_field(XS, subdiv=subdiv)
_, y_refi = refiner.refine_field(YS, subdiv=subdiv)
triang_param, z_refi = refiner.refine_field(ZS, subdiv=subdiv)

#triang_param = refiner.refine_triangulation()#mtri.Triangulation(XS, YS, triangles)
#print triang_param.triangles
triang = mtri.Triangulation(x_refi, y_refi, triang_param.triangles)
ax.plot_trisurf(triang, z_refi, cmap=cm.jet, lw=0.)

plt.show()