Exemple #1
0
    def plotcelldata(self, z, xlims=None, ylims=None, colorbar=True, **kwargs):
        """
        Plot cell centered data
        """
        ax=plt.gca()
        fig = plt.gcf()
        # Find the colorbar limits if unspecified
        if self.clim is None:
            self.clim = [z.min(),z.max()]
        # Set the xy limits
        if xlims is None or ylims is None:
            xlims=self.xlims()
            ylims=self.ylims()
        
        collection = PolyCollection(self.xy(),closed=False,**kwargs)
        collection.set_array(z)
        collection.set_clim(vmin=self.clim[0],vmax=self.clim[1])
        collection.set_edgecolors(collection.to_rgba(z))    
        
        ax.add_collection(collection)

        ax.set_aspect('equal')
        ax.set_xlim(xlims)
        ax.set_ylim(ylims)

        axcb=None
        if colorbar:
            axcb = fig.colorbar(collection)

    
        return fig, ax, collection, axcb
Exemple #2
0
    def plotcelldata(self, z, xlims=None, ylims=None, colorbar=True, **kwargs):
        """
        Plot cell centered data
        """
        ax = plt.gca()
        fig = plt.gcf()
        # Find the colorbar limits if unspecified
        if self.clim is None:
            self.clim = [z.min(), z.max()]
        # Set the xy limits
        if xlims is None or ylims is None:
            xlims = self.xlims()
            ylims = self.ylims()

        collection = PolyCollection(self.xy(), closed=False, **kwargs)
        collection.set_array(z)
        collection.set_clim(vmin=self.clim[0], vmax=self.clim[1])
        collection.set_edgecolors(collection.to_rgba(z))

        ax.add_collection(collection)

        ax.set_aspect('equal')
        ax.set_xlim(xlims)
        ax.set_ylim(ylims)

        axcb = None
        if colorbar:
            axcb = fig.colorbar(collection)

        return fig, ax, collection, axcb
Exemple #3
0
class VarPlot(object):

    def __init__(self, var, cmap, axes):
        self.axes = axes
        self.var = var
        self.cmap = cmap
        self.mesh = self.var.mesh
        self.plot_mesh()

    def plot_mesh(self):
        vertexIDs = self.mesh._orderedCellVertexIDs
        vertexCoords = self.mesh.vertexCoords
        xCoords = numerix.take(vertexCoords[0], vertexIDs)
        yCoords = numerix.take(vertexCoords[1], vertexIDs)
        polys = []
        for x, y in zip(xCoords.swapaxes(0, 1), yCoords.swapaxes(0, 1)):
            polys.append(zip(x, y))
        self.collection = PolyCollection(polys)
        self.collection.set_linewidth(0.5)
        self.axes.add_collection(self.collection)
        self.update(self.var)

    def update(self, var):
        rgba = self.cmap(var.value)
        self.collection.set_facecolors(rgba)
        self.collection.set_edgecolors(rgba)
Exemple #4
0
    def grid_plot(self):
        """
        plotting the grid
        """
        maxfaces = self.cells.shape[1]

        pointdata = self.readTXT('%s/points.dat' % self.dire)
        xp1 = (pointdata[:, 0] - self.originx) / 1.
        yp1 = (pointdata[:, 1] - self.originy) / 1.
        #########################################################
        xp = np.zeros((self.Nc, maxfaces + 1))
        yp = np.zeros((self.Nc, maxfaces + 1))

        cells = self.cells.copy()
        #cells[cells.mask]=0
        xp[:, :maxfaces] = xp1[cells]
        xp[range(self.Nc), self.nfaces] = xp1[cells[:, 0]]
        yp[:, :maxfaces] = yp1[cells]
        yp[range(self.Nc), self.nfaces] = yp1[cells[:, 0]]
        ##########################################################
        xy = np.zeros((maxfaces + 1, 2))

        def _closepoly(ii):
            nf = self.nfaces[ii] + 1
            xy[:nf, 0] = xp[ii, :nf]
            xy[:nf, 1] = yp[ii, :nf]
            return xy[:nf, :].copy()

        cellxy = [_closepoly(ii) for ii in range(self.Nc)]

        #xlims = np.asarray([self.xv.min(), self.xv.max()])
        #ylims = np.asarray([self.yv.min(), self.yv.max()])

        xlims = np.asarray([616832, 709049]) - self.originx
        ylims = np.asarray([2854748, 3050710]) - self.originy

        fig = plt.figure(figsize=(12, 10))
        ax = fig.add_subplot(111)
        #cmap = plt.set_cmap('bwr')
        collection = PolyCollection(cellxy, facecolors='none')
        #collection.set_array(np.array(self.L[:]))
        collection.set_edgecolors('k')
        collection.set_linewidths(0.3)
        ax.add_collection(collection)
        lc = self.outline()  #line collection of outline
        ax.add_collection(lc)
        ax.set_xlim(xlims)
        ax.set_ylim(ylims)
        ax.set_aspect('equal')
        ax.tick_params(labelsize=22)
        ax.set_xlabel('Easting (m)', fontsize=22)
        ax.set_ylabel('Northing (m)', fontsize=22)
        fig.tight_layout()

        plt.show()
class Matplotlib2DViewer(AbstractMatplotlib2DViewer):
    """
    Displays a contour plot of a 2D `CellVariable` object.    

    The `Matplotlib2DViewer` plots a 2D `CellVariable` using Matplotlib_.

    .. _Matplotlib: http://matplotlib.sourceforge.net/
    """

    __doc__ += AbstractMatplotlib2DViewer._test2Dirregular(
        viewer="Matplotlib2DViewer")

    def __init__(self,
                 vars,
                 title=None,
                 limits={},
                 cmap=None,
                 colorbar='vertical',
                 axes=None,
                 figaspect='auto',
                 **kwlimits):
        """Creates a `Matplotlib2DViewer`.
        

        :Parameters:
          vars
            a `CellVariable` object.
          title
            displayed at the top of the `Viewer` window
          limits : dict
            a (deprecated) alternative to limit keyword arguments
          cmap
            the colormap. Defaults to `matplotlib.cm.jet`
          xmin, xmax, ymin, ymax, datamin, datamax
            displayed range of data. Any limit set to 
            a (default) value of `None` will autoscale.
          colorbar
            plot a colorbar in specified orientation if not `None`
          axes
            if not `None`, `vars` will be plotted into this Matplotlib `Axes` object
          figaspect
            desired aspect ratio of figure. If arg is a number, use that aspect
            ratio. If arg is 'auto', the aspect ratio will be determined from
            the Variable's mesh.
        """
        kwlimits.update(limits)
        AbstractMatplotlib2DViewer.__init__(self,
                                            vars=vars,
                                            title=title,
                                            figaspect=figaspect,
                                            cmap=cmap,
                                            colorbar=colorbar,
                                            axes=axes,
                                            **kwlimits)

        self.mesh = self.vars[0].mesh

        vertexIDs = self.mesh._orderedCellVertexIDs

        vertexCoords = self.mesh.vertexCoords

        xCoords = numerix.take(vertexCoords[0], vertexIDs)
        yCoords = numerix.take(vertexCoords[1], vertexIDs)

        polys = []

        for x, y in zip(xCoords.swapaxes(0, 1), yCoords.swapaxes(0, 1)):
            if hasattr(x, 'mask'):
                x = x.compressed()
            if hasattr(y, 'mask'):
                y = y.compressed()
            polys.append(list(zip(x, y)))

        from matplotlib.collections import PolyCollection
        self.collection = PolyCollection(polys)
        self.collection.set_linewidth(0.5)
        try:
            self.axes.add_patch(self.collection)
        except:
            # PolyCollection not child of PatchCollection in matplotlib 0.98
            self.axes.add_collection(self.collection)

        xmin = self._getLimit('xmin', default=xCoords.min())
        xmax = self._getLimit('xmax', default=xCoords.max())
        ymin = self._getLimit('ymin', default=yCoords.min())
        ymax = self._getLimit('ymax', default=yCoords.max())

        self.axes.set_xlim(xmin=xmin, xmax=xmax)
        self.axes.set_ylim(ymin=ymin, ymax=ymax)

        self._plot()

    def _getSuitableVars(self, vars):
        from fipy.meshes.mesh2D import Mesh2D
        from fipy.variables.cellVariable import CellVariable
        vars = [var for var in AbstractMatplotlib2DViewer._getSuitableVars(self, vars) \
          if ((var.mesh.dim == 2 and isinstance(var, CellVariable))
              and var.rank == 0)]
        if len(vars) == 0:
            from fipy.viewers import MeshDimensionError
            raise MeshDimensionError(
                "Matplotlib2DViewer can only display a rank-0, 2D CellVariable"
            )
        # this viewer can only display one variable
        return [vars[0]]

    def _plot(self):
        ##         pylab.clf()

        ##         ## Added garbage collection since matplotlib objects seem to hang
        ##         ## around and accumulate.
        ##         import gc
        ##         gc.collect()

        Z = self.vars[0].value

        self.norm.vmin = self._getLimit(('datamin', 'zmin'))
        self.norm.vmax = self._getLimit(('datamax', 'zmax'))

        rgba = self.cmap(self.norm(Z))

        self.collection.set_facecolors(rgba)
        self.collection.set_edgecolors(rgba)

        if self.colorbar is not None:
            self.colorbar.plot()  #vmin=zmin, vmax=zmax)
class Matplotlib2DViewer(_MatplotlibViewer):
    """
    Displays a contour plot of a 2D `CellVariable` object.    

    The `Matplotlib2DViewer` plots a 2D `CellVariable` using Matplotlib_.

    .. _Matplotlib: http://matplotlib.sourceforge.net/
    """ 
    
    __doc__ += _MatplotlibViewer._test2Dirregular(viewer="Matplotlib2DViewer")

    def __init__(self, vars, title=None, limits={}, cmap=None, colorbar=True, axes=None, **kwlimits):
        """Creates a `Matplotlib2DViewer`.
        

        :Parameters:
          vars
            a `CellVariable` object.
          title
            displayed at the top of the `Viewer` window
          limits : dict
            a (deprecated) alternative to limit keyword arguments
          cmap
            the colormap. Defaults to `matplotlib.cm.jet`
          xmin, xmax, ymin, ymax, datamin, datamax
            displayed range of data. Any limit set to 
            a (default) value of `None` will autoscale.
          colorbar
            plot a colorbar in specified orientation if not `None`
          axes
            if not `None`, `vars` will be plotted into this Matplotlib `Axes` object
        """
        kwlimits.update(limits)
        _MatplotlibViewer.__init__(self, vars=vars, title=title, figaspect=1. / 1.3, 
                                   cmap=cmap, colorbar=colorbar, axes=axes, 
                                   **kwlimits)

        self.mesh = self.vars[0].getMesh()
        
        vertexIDs = self.mesh._getOrderedCellVertexIDs()

        vertexCoords = self.mesh.getVertexCoords()

        xCoords = numerix.take(vertexCoords[0], vertexIDs)
        yCoords = numerix.take(vertexCoords[1], vertexIDs)
        
        polys = []

        for x, y in zip(xCoords.swapaxes(0,1), yCoords.swapaxes(0,1)):
            if hasattr(x, 'mask'):
                x = x.compressed()
            if hasattr(y, 'mask'):
                y = y.compressed()
            polys.append(zip(x,y))

        import matplotlib

        from matplotlib.collections import PolyCollection
        self.collection = PolyCollection(polys)
        self.collection.set_linewidth(0.5)
        try:
            self.axes.add_patch(self.collection)
        except:
            # PolyCollection not child of PatchCollection in matplotlib 0.98
            self.axes.add_collection(self.collection)

        xmin = self._getLimit('xmin', default=xCoords.min())
        xmax = self._getLimit('xmax', default=xCoords.max())
        ymin = self._getLimit('ymin', default=yCoords.min())
        ymax = self._getLimit('ymax', default=yCoords.max())

        self.axes.set_xlim(xmin=xmin, xmax=xmax)
        self.axes.set_ylim(ymin=ymin, ymax=ymax)

        self._plot()
        
    def _getSuitableVars(self, vars):
        from fipy.meshes.numMesh.mesh2D import Mesh2D
        from fipy.variables.cellVariable import CellVariable
        vars = [var for var in _MatplotlibViewer._getSuitableVars(self, vars) \
          if ((isinstance(var.getMesh(), Mesh2D) and isinstance(var, CellVariable))
              and var.getRank() == 0)]
        if len(vars) == 0:
            from fipy.viewers import MeshDimensionError
            raise MeshDimensionError, "Matplotlib2DViewer can only display a rank-0, 2D CellVariable"
        # this viewer can only display one variable
        return [vars[0]]
        
    def _plot(self):
##         pylab.clf()
        
##         ## Added garbage collection since matplotlib objects seem to hang
##         ## around and accumulate.
##         import gc
##         gc.collect()

        Z = self.vars[0].getValue() 
        
        zmin, zmax = self._autoscale(vars=self.vars,
                                     datamin=self._getLimit(('datamin', 'zmin')),
                                     datamax=self._getLimit(('datamax', 'zmax')))

        diff = zmax - zmin
        
        import matplotlib

        if diff == 0:
            rgba = self.cmap(0.5)
        else:
            rgba = self.cmap((Z - zmin) / diff)
        
        self.collection.set_facecolors(rgba)
        self.collection.set_edgecolors(rgba)

        if self.colorbar is not None:
            self.colorbar.plot(vmin=zmin, vmax=zmax)
Exemple #7
0
class Mesh():
    """
    Mesh described by vertices and faces
    """
    def __init__(self,
                 ax,
                 transform,
                 vertices,
                 faces,
                 cmap=None,
                 facecolors="white",
                 edgecolors="black",
                 linewidths=0.5,
                 mode="front"):
        """
        """

        self.collection = PolyCollection([], clip_on=False, snap=False)
        self.vertices = vertices
        self.faces = faces
        self.cmap = cmap
        self.facecolors = mpl.colors.to_rgba_array(facecolors)
        self.edgecolors = mpl.colors.to_rgba_array(edgecolors)
        self.linewidths = linewidths
        self.mode = mode
        self.update(transform)
        ax.add_collection(self.collection, autolim=False)

    def update(self, transform):
        """
        Update mesh according to transform (4x4 array)
        """

        T = glm.transform(self.vertices, transform)[self.faces]
        Z = -T[:, :, 2].mean(axis=1)

        if self.cmap is not None:
            # Facecolors using depth buffer
            norm = mpl.colors.Normalize(vmin=Z.min(), vmax=Z.max())
            facecolors = self.cmap(norm(Z))

        else:
            facecolors = self.facecolors
        edgecolors = self.edgecolors
        linewidths = self.linewidths

        # Back face culling
        if self.mode == "front":
            front, back = glm.frontback(T)
            T, Z = T[front], Z[front]
            if len(facecolors) == len(self.faces):
                facecolors = facecolors[front]
            if len(edgecolors) == len(self.faces):
                edgecolors = edgecolors[front]

        # Front face culling
        elif self.mode == "back":
            front, back = glm.frontback(T)
            T, Z = T[back], Z[back]
            if len(facecolors) == len(faces):
                facecolors = facecolors[back]
            if len(edgecolor) == len(faces):
                edgecolors = edgecolors[back]

        # Separate 2d triangles from zbuffer
        triangles = T[:, :, :2]
        antialiased = linewidths > 0

        # Sort triangles according to z buffer
        I = np.argsort(Z)
        triangles = triangles[I, :]
        if len(facecolors) == len(I):
            facecolors = facecolors[I, :]
        if len(edgecolors) == len(I):
            edgecolors = edgecolors[I, :]

        self.collection.set_verts(triangles)
        self.collection.set_linewidths(linewidths)
        self.collection.set_facecolors(facecolors)
        self.collection.set_edgecolors(edgecolors)
        self.collection.set_antialiased(antialiased)
Exemple #8
0
class Matplotlib2DViewer(_MatplotlibViewer):
    """
    Displays a contour plot of a 2D `CellVariable` object.    

    The `Matplotlib2DViewer` plots a 2D `CellVariable` using Matplotlib_.

    .. _Matplotlib: http://matplotlib.sourceforge.net/
    """ 
    
    __doc__ += _MatplotlibViewer._test2Dirregular(viewer="Matplotlib2DViewer")

    def __init__(self, vars, title=None, limits={}, cmap=None, **kwlimits):
        """Creates a `Matplotlib2DViewer`.
        

        :Parameters:
          vars
            a `CellVariable` object.
          title
            displayed at the top of the `Viewer` window
          limits : dict
            a (deprecated) alternative to limit keyword arguments
          cmap
            the colormap. Defaults to `pylab.cm.jet`
          xmin, xmax, ymin, ymax, datamin, datamax
            displayed range of data. Any limit set to 
            a (default) value of `None` will autoscale.

        """
        kwlimits.update(limits)
        _MatplotlibViewer.__init__(self, vars=vars, title=title, figaspect=1. / 1.3, **kwlimits)

        self.colorbar = None
        
        self.mesh = self.vars[0].getMesh()
        
        vertexIDs = self.mesh._getOrderedCellVertexIDs()

        vertexCoords = self.mesh.getVertexCoords()

        xCoords = numerix.take(vertexCoords[0], vertexIDs)
        yCoords = numerix.take(vertexCoords[1], vertexIDs)
        
        polys = []

        for x, y in zip(xCoords.swapaxes(0,1), yCoords.swapaxes(0,1)):
            if hasattr(x, 'mask'):
                x = x.compressed()
            if hasattr(y, 'mask'):
                y = y.compressed()
            polys.append(zip(x,y))

        import pylab
        import matplotlib

        fig = pylab.figure(self.id)

        ax = fig.get_axes()[0]

        from matplotlib.collections import PolyCollection
        self.collection = PolyCollection(polys)
        self.collection.set_linewidth(0.5)
        try:
            ax.add_patch(self.collection)
        except:
            # PolyCollection not child of PatchCollection in matplotlib 0.98
            ax.add_collection(self.collection)

        if self._getLimit('xmin') is None:
            xmin = xCoords.min()
        else:
            xmin = self._getLimit('xmin')

        if self._getLimit('xmax') is None:
            xmax = xCoords.max()
        else:
            xmax = self._getLimit('xmax')

        if self._getLimit('ymin') is None:
            ymin = yCoords.min()
        else:
            ymin = self._getLimit('ymin')

        if self._getLimit('ymax') is None:
            ymax = yCoords.max()
        else:
            ymax = self._getLimit('ymax')

        pylab.axis((xmin, xmax, ymin, ymax))

        cbax, kw = matplotlib.colorbar.make_axes(ax, orientation='vertical')
        
        # Set the colormap and norm to correspond to the data for which
        # the colorbar will be used.
        if cmap is None:
            self.cmap = matplotlib.cm.jet
        else:
            self.cmap = cmap
            
        norm = matplotlib.colors.normalize(vmin=-1, vmax=1)
        
        # ColorbarBase derives from ScalarMappable and puts a colorbar
        # in a specified axes, so it has everything needed for a
        # standalone colorbar.  There are many more kwargs, but the
        # following gives a basic continuous colorbar with ticks
        # and labels.
        self.cb = matplotlib.colorbar.ColorbarBase(cbax, cmap=self.cmap,
                                                   norm=norm,
                                                   orientation='vertical')
        self.cb.set_label(self.vars[0].name)
        
        self._plot()
        
    def _getSuitableVars(self, vars):
        from fipy.meshes.numMesh.mesh2D import Mesh2D
        from fipy.variables.cellVariable import CellVariable
        vars = [var for var in _MatplotlibViewer._getSuitableVars(self, vars) \
          if ((isinstance(var.getMesh(), Mesh2D) and isinstance(var, CellVariable))
              and var.getRank() == 0)]
        if len(vars) == 0:
            from fipy.viewers import MeshDimensionError
            raise MeshDimensionError, "Matplotlib2DViewer can only display a rank-0, 2D CellVariable"
        # this viewer can only display one variable
        return [vars[0]]
        
    def _plot(self):
##         pylab.clf()
        
##         ## Added garbage collection since matplotlib objects seem to hang
##         ## around and accumulate.
##         import gc
##         gc.collect()

        Z = self.vars[0].getValue() 
        
        zmin, zmax = self._autoscale(vars=self.vars,
                                     datamin=self._getLimit(('datamin', 'zmin')),
                                     datamax=self._getLimit(('datamax', 'zmax')))

        diff = zmax - zmin
        
        import matplotlib

        if diff == 0:
            rgba = self.cmap(0.5)
        else:
            rgba = self.cmap((Z - zmin) / diff)
        
        self.collection.set_facecolors(rgba)
        self.collection.set_edgecolors(rgba)

        self.cb.norm = matplotlib.colors.normalize(vmin=zmin, vmax=zmax)
        self.cb.cmap = self.cmap
        self.cb.draw_all()
Exemple #9
0
class Bar:
    """ Bar (histogram) """
    def __init__(self,
                 ax,
                 transform,
                 Z,
                 facecolors="white",
                 edgecolors="black",
                 linewidth=0,
                 clip=False):
        """ """

        self.Z = Z
        if isinstance(facecolors, np.ndarray):
            shape = facecolors.shape
            facecolors = facecolors.reshape(-1, shape[-1])
            facecolors = mpl.colors.to_rgba_array(facecolors)
            self.facecolors = facecolors.reshape(shape[0], shape[1], 4)
        else:
            shape = Z.shape
            self.facecolors = np.zeros((shape[0], shape[1], 4))
            self.facecolors[...] = mpl.colors.to_rgba(facecolors)

        if isinstance(edgecolors, np.ndarray):
            shape = edgecolors.shape
            edgecolors = edgecolors.reshape(-1, shape[-1])
            edgecolors = mpl.colors.to_rgba_array(edgecolors)
            self.edgecolors = edgecolors.reshape(shape[0], shape[1], 4)
        else:
            shape = Z.shape
            self.edgecolors = np.zeros((shape[0], shape[1], 4))
            self.edgecolors[...] = mpl.colors.to_rgba(edgecolors)

        self.linewidth = linewidth
        self.xlim = -0.5, +0.50
        self.ylim = -0.5, +0.50
        self.zlim = -0.5, +0.50
        self.clip = clip

        # Because all the bars have the same orientation, we can use a hack to
        # shade each face at once instead of computing individual face lighting.
        self.shade = np.array([[1.00, 1.00, 0.75, 1.00, 0.50, 1.00]])

        self.collection = PolyCollection([], clip_on=self.clip, snap=False)
        self.update(transform)
        ax.add_collection(self.collection, autolim=False)

    def update(self, transform):
        """ """

        Z = self.Z
        xmin, xmax = self.xlim
        ymin, ymax = self.ylim
        zmin, zmax = self.zlim
        dx, dy = 0.5 * 1 / Z.shape[0], 0.5 * 1 / Z.shape[1]

        # Each bar is described by 8 vertices and 6 faces
        V = np.zeros((Z.shape[0], Z.shape[1], 8, 3))
        F = np.zeros((Z.shape[0], Z.shape[1], 6, 4), dtype=int)

        # Face and edge colors for the six faces
        FC = np.zeros((Z.shape[0], Z.shape[1], 6, 4))
        FC[:, :] = self.facecolors.reshape(Z.shape[0], Z.shape[1], 1, 4)
        FC *= self.shade.T
        FC[:, :, :, 3] = 1

        EC = np.zeros((Z.shape[0], Z.shape[1], 6, 4))
        EC[:, :] = self.edgecolors.reshape(Z.shape[0], Z.shape[1], 1, 4)

        # Build vertices
        X, Y = np.meshgrid(np.linspace(xmin, xmax, Z.shape[0]),
                           np.linspace(ymin, ymax, Z.shape[1]))
        V[..., 0] = X.reshape(Z.shape[0], Z.shape[1], 1)
        V[..., 1] = Y.reshape(Z.shape[0], Z.shape[1], 1)

        V[:, :, 0] += [+dx, +dy, zmin]
        V[:, :, 1] += [+dx, -dy, zmin]
        V[:, :, 2] += [-dx, -dy, zmin]
        V[:, :, 3] += [-dx, +dy, zmin]

        V[:, :, 4] += [+dx, +dy, zmin]
        V[:, :, 5] += [+dx, -dy, zmin]
        V[:, :, 6] += [-dx, -dy, zmin]
        V[:, :, 7] += [-dx, +dy, zmin]
        V[:, :, 4:, 2] += Z.reshape(Z.shape[0], Z.shape[1], 1)

        # Build faces
        I = 8 * np.arange(Z.shape[0] * Z.shape[1])
        F[:, :] = I.reshape(Z.shape[0], Z.shape[1], 1, 1)
        F[:, :] += [
            [0, 1, 2, 3],  # -Z
            [0, 1, 5, 4],  # +X
            [2, 3, 7, 6],  # -X
            [1, 2, 6, 5],  # -Y
            [0, 3, 7, 4],  # +Y
            [4, 5, 6, 7]
        ]  # +Z

        # Actual transformation
        V = V.reshape(-1, 3)
        V = glm.transform(V[F], transform)  #[...,:2]

        # Depth computation
        # We combine the global "depth" of the bar (depth of the bottom face)
        # and the local depth of each face. This trick avoids problems when
        # sorting all the different faces.
        Z1 = (V[:, :, 0, :, 2].mean(axis=2)).reshape(Z.shape[0], Z.shape[1], 1)
        Z2 = (V[..., 2].mean(axis=3) + 10 * Z1).ravel()

        # Sorting
        I = np.argsort(-Z2)
        V = (V[..., :2].reshape(Z.shape[0] * Z.shape[1] * 6, 4, 2))

        self.collection.set_verts(V[I])
        self.collection.set_facecolors(FC.reshape(-1, 4)[I])
        self.collection.set_edgecolors(EC.reshape(-1, 4)[I])
        self.collection.set_linewidths(self.linewidth)
        if self.linewidth == 0.0:
            self.collection.set_antialiased(False)
        else:
            self.collection.set_antialiased(True)
Exemple #10
0
class Matplotlib2DViewer(AbstractMatplotlib2DViewer):
    """
    Displays a contour plot of a 2D `CellVariable` object.

    The `Matplotlib2DViewer` plots a 2D `CellVariable` using Matplotlib_.

    .. _Matplotlib: http://matplotlib.sourceforge.net/
    """

    __doc__ += AbstractMatplotlib2DViewer._test2Dirregular(viewer="Matplotlib2DViewer")

    def __init__(self, vars, title=None, limits={}, cmap=None, colorbar='vertical', axes=None, figaspect='auto', **kwlimits):
        """Creates a `Matplotlib2DViewer`.


        :Parameters:
          vars
            a `CellVariable` object.
          title
            displayed at the top of the `Viewer` window
          limits : dict
            a (deprecated) alternative to limit keyword arguments
          cmap
            the colormap. Defaults to `matplotlib.cm.jet`
          xmin, xmax, ymin, ymax, datamin, datamax
            displayed range of data. Any limit set to
            a (default) value of `None` will autoscale.
          colorbar
            plot a colorbar in specified orientation if not `None`
          axes
            if not `None`, `vars` will be plotted into this Matplotlib `Axes` object
          figaspect
            desired aspect ratio of figure. If arg is a number, use that aspect
            ratio. If arg is 'auto', the aspect ratio will be determined from
            the Variable's mesh.
        """
        kwlimits.update(limits)
        AbstractMatplotlib2DViewer.__init__(self, vars=vars, title=title, figaspect=figaspect,
                                            cmap=cmap, colorbar=colorbar, axes=axes,
                                            **kwlimits)

        self.mesh = self.vars[0].mesh

        vertexIDs = self.mesh._orderedCellVertexIDs

        vertexCoords = self.mesh.vertexCoords

        xCoords = numerix.take(vertexCoords[0], vertexIDs)
        yCoords = numerix.take(vertexCoords[1], vertexIDs)

        polys = []

        for x, y in zip(xCoords.swapaxes(0, 1), yCoords.swapaxes(0, 1)):
            if hasattr(x, 'mask'):
                x = x.compressed()
            if hasattr(y, 'mask'):
                y = y.compressed()
            polys.append(list(zip(x, y)))

        from matplotlib.collections import PolyCollection
        self.collection = PolyCollection(polys)
        self.collection.set_linewidth(0.5)
        try:
            self.axes.add_patch(self.collection)
        except:
            # PolyCollection not child of PatchCollection in matplotlib 0.98
            self.axes.add_collection(self.collection)

        xmin = self._getLimit('xmin', default=xCoords.min())
        xmax = self._getLimit('xmax', default=xCoords.max())
        ymin = self._getLimit('ymin', default=yCoords.min())
        ymax = self._getLimit('ymax', default=yCoords.max())

        self.axes.set_xlim(xmin=xmin, xmax=xmax)
        self.axes.set_ylim(ymin=ymin, ymax=ymax)

        self._plot()

    def _getSuitableVars(self, vars):
        from fipy.meshes.mesh2D import Mesh2D
        from fipy.variables.cellVariable import CellVariable
        vars = [var for var in AbstractMatplotlib2DViewer._getSuitableVars(self, vars) \
          if ((var.mesh.dim == 2 and isinstance(var, CellVariable))
              and var.rank == 0)]
        if len(vars) == 0:
            from fipy.viewers import MeshDimensionError
            raise MeshDimensionError("Matplotlib2DViewer can only display a rank-0, 2D CellVariable")
        # this viewer can only display one variable
        return [vars[0]]

    def _plot(self):
##         plt.clf()

##         ## Added garbage collection since matplotlib objects seem to hang
##         ## around and accumulate.
##         import gc
##         gc.collect()

        Z = self.vars[0].value

        self.norm.vmin = self._getLimit(('datamin', 'zmin'))
        self.norm.vmax = self._getLimit(('datamax', 'zmax'))

        rgba = self.cmap(self.norm(Z))

        self.collection.set_facecolors(rgba)
        self.collection.set_edgecolors(rgba)

        if self.colorbar is not None:
            self.colorbar.plot() #vmin=zmin, vmax=zmax)
                    plt.savefig(case + '_' + str(n) + '.png',
                                bbox_inches='tight')
                    plt.close('all')
                elif 'U-chan' in case and n % 10 == 0:
                    fig = plt.figure()
                    ax = fig.add_subplot(111)
                    collection = PolyCollection(
                        xy,
                        cmap=plt.get_cmap('jet'))  # 'Blues' 'jet' 'ocean' mcm
                    ui = self.get_center_vel(uj)
                    uimag = np.sqrt(
                        np.multiply(ui[:, 0], ui[:, 0]) +
                        np.multiply(ui[:, 1], ui[:, 1]))
                    collection.set_array(uimag)
                    collection.set_linewidths(0.2)
                    collection.set_edgecolors('none')
                    collection.set_clim(vmin=0.15, vmax=0.45)
                    ax.add_collection(collection)
                    ax.set_xlim([-2.2, 2.5])
                    ax.set_ylim([-0.1, 2.6])
                    ax.set_aspect('equal')
                    plt.savefig(case + '_' + str(n) + '.png',
                                bbox_inches='tight')
                    plt.close('all')

        return hi, uj, ei

    def get_edge_x_vel(self, uj):
        """
        Return x direction velocity and location at cell edge midpoints
        """
        sc.set_label('model')
        cb = plt.colorbar(sc)
        cb.set_label('Edge length (m)')
        plt.legend()
        plt.show()

        if '1D' not in swampy.grid_type:
            # Contour plot of water levels
            fig = plt.figure()
            ax = fig.add_subplot(111)
            xy = swampy.get_grid_poly_collection()
            collection = PolyCollection(
                xy, cmap=plt.get_cmap('jet'))  # 'Blues' 'jet' 'ocean' mcm
            collection.set_array(ei)
            collection.set_linewidths(0.2)
            collection.set_edgecolors('k')
            ax.add_collection(collection)
            ax.set_xlim([0, domain_length])
            if 'tri' in swampy.grid_type:
                ax.set_ylim([0, 5])
            else:
                ax.set_ylim([0, 100])
                # ax.set_xlim([400, 900])
            ax.set_aspect('equal')

            # Contour plot of water levels and velocity vectors
            fig = plt.figure()
            ax = fig.add_subplot(111)
            collection = PolyCollection(
                xy, cmap=plt.get_cmap('jet'))  # 'Blues' 'jet' 'ocean' mcm
            collection.set_array(ei)