Ejemplo n.º 1
0
def showMesh(mesh,
             data=None,
             hold=False,
             block=False,
             colorBar=None,
             label=None,
             coverage=None,
             ax=None,
             savefig=None,
             showMesh=False,
             showBoundary=None,
             markers=False,
             **kwargs):
    """2D Mesh visualization.

    Create an axis object and plot a 2D mesh with given node or cell data.
    Returns the axis and the color bar. The type of data determine the
    appropriate draw method.

    Parameters
    ----------

    mesh : :gimliapi:`GIMLI::Mesh`
        2D or 3D GIMLi mesh

    data : iterable [None]
        Optionally data to visualize.

        . None (draw mesh only)
            forward to :py:mod:`pygimli.mplviewer.drawMesh`
            or if no cells are given:
            forward to :py:mod:`pygimli.mplviewer.drawPLC`

        . [[marker, value], ...]
            List of Cellvalues per cell marker
            forward to :py:mod:`pygimli.mplviewer.drawModel`

        . float per cell -- model, patch
            forward to :py:mod:`pygimli.mplviewer.drawModel`

        . float per node -- scalar field
            forward to :py:mod:`pygimli.mplviewer.drawField`

        . iterable of type [float, float] -- vector field
            forward to :py:mod:`pygimli.mplviewer.drawStreams`

        . pg.R3Vector -- vector field
            forward to :py:mod:`pygimli.mplviewer.drawStreams`

        . pg.stdVectorRVector3 -- sensor positions
            forward to :py:mod:`pygimli.mplviewer.drawSensors`


    hold : bool [false]
        Set interactive plot mode for matplotlib.
        If this is set to false [default] your script will open
        a window with the figure and draw your content.
        If set to true nothing happens until you either force another show with
        hold=False, you call plt.show() or pg.wait().
        If you want show with stopping your script set block = True.

    block : bool [false]
        Force show drawing your content and block the script until you
        close the current figure.

    colorBar : bool [None], Colorbar
        Create and show a colorbar. If colorBar is a valid colorbar then only
        its values will be updated.

    label : str
        Set colorbar label. If set colorbar is toggled to True. [None]

    coverage : iterable [None]
        Weight data by the given coverage array and fadeout the color.

    ax : matplotlib.Axes [None]
        Instead of create a new and empty ax, just draw into the a given.
        Useful to combine draws.

    savefig: string
        Filename for a direct save to disc.
        The matplotlib pdf-output is a little bit big so we try
        an epstopdf if the .eps suffix is found in savefig

    showMesh : bool [False]
        Shows the mesh itself aditional.

    showBoundary : bool [None]
        Shows all boundary with marker != 0. A value None means automatic
        True for cell data and False for node data.

    marker : bool [False]
        Show mesh and boundary marker.

    **kwargs :
        * xlabel : str [None]
            Add label to the x axis

        * ylabel : str [None]
            Add label to the y axis

        * all remaining
            Will be forwarded to the draw functions and matplotlib methods,
            respectively.

    Examples
    --------
    >>> import pygimli as pg
    >>> import pygimli.meshtools as mt
    >>> world = mt.createWorld(start=[-10, 0], end=[10, -10],
    ...                        layers=[-3, -7], worldMarker=False)
    >>> mesh = mt.createMesh(world, quality=32, area=0.2, smooth=[1, 10])
    >>> _ = pg.viewer.showMesh(mesh, markers=True)

    Returns
    -------
    ax : matplotlib.axes

    colobar : matplotlib.colorbar
    """
    pg.renameKwarg('cmap', 'cMap', kwargs)

    if ax is None:
        ax = plt.subplots()[1]

    # print('1*'*50)
    # print(locale.localeconv())

    # plt.subplots() resets locale setting to system default .. this went
    # horrible wrong for german 'decimal_point': ','
    pg.checkAndFixLocaleDecimal_point(verbose=False)

    # print('2*'*50)
    # print(locale.localeconv())

    if block:
        hold = True

    if hold:
        lastHoldStatus = pg.mplviewer.utils.holdAxes__
        pg.mplviewer.hold(val=1)

    gci = None
    validData = False

    if markers:
        kwargs["boundaryMarker"] = True
        if mesh.cellCount() > 0:
            uniquemarkers, uniqueidx = np.unique(np.array(mesh.cellMarkers()),
                                                 return_inverse=True)
            label = "Cell markers"
            kwargs["cMap"] = plt.cm.get_cmap("Set3", len(uniquemarkers))
            kwargs["logScale"] = False
            kwargs["cMin"] = -0.5
            kwargs["cMax"] = len(uniquemarkers) - 0.5
            data = np.arange(len(uniquemarkers))[uniqueidx]

    if data is None:
        showMesh = True
        if showBoundary is None:
            showBoundary = True
    elif isinstance(data, pg.stdVectorRVector3):
        drawSensors(ax, data, **kwargs)
    elif isinstance(data, pg.R3Vector):
        drawStreams(ax, mesh, data, **kwargs)
    else:
        #print('-----------------------------')
        #print(data, type(data))
        #print('-----------------------------')

        ### data=[[marker, val], ....]
        if isinstance(data, list) and \
            isinstance(data[0], list) and isinstance(data[0][0], int):
            data = pg.solver.parseMapToCellArray(data, mesh)

        if hasattr(data[0], '__len__') and not \
            isinstance(data, np.ma.core.MaskedArray):

            if len(data) == 2:  # [u,v] x N
                data = np.array(data).T

            if data.shape[1] == 2:
                drawStreams(ax, mesh, data, **kwargs)

            elif data.shape[1] == 3:  # probably N x [u,v,w]
                # if sum(data[:, 0]) != sum(data[:, 1]):
                # drawStreams(ax, mesh, data, **kwargs)
                drawStreams(ax, mesh, data[:, 0:2], **kwargs)
            else:
                pg.warn("No valid stream data:", data.shape, data.ndim)
                showMesh = True
        elif min(data) == max(data):  # or pg.haveInfNaN(data):
            pg.warn("No valid data: ", min(data), max(data),
                    pg.haveInfNaN(data))
            showMesh = True
        else:
            validData = True
            try:
                if len(data) == mesh.cellCount():
                    gci = drawModel(ax, mesh, data, **kwargs)
                    if showBoundary is None:
                        showBoundary = True

                elif len(data) == mesh.nodeCount():
                    gci = drawField(ax, mesh, data, **kwargs)

                cMap = kwargs.pop('cMap', None)
                if cMap is not None:
                    gci.set_cmap(cmapFromName(cMap))

            except BaseException as e:
                print("Exception occured: ", e)
                print("Data: ", min(data), max(data), pg.haveInfNaN(data))
                print("Mesh: ", mesh)
                drawMesh(ax, mesh, **kwargs)

    if mesh.cellCount() == 0:
        showMesh = False
        if mesh.boundaryCount() == 0:
            pg.mplviewer.drawPLC(ax,
                                 mesh,
                                 showNodes=True,
                                 fillRegion=False,
                                 showBoundary=False,
                                 **kwargs)
            showBoundary = False
            #ax.plot(pg.x(mesh), pg.y(mesh), '.', color='black')
        else:
            pg.mplviewer.drawPLC(ax, mesh, **kwargs)

    if showMesh:
        if gci is not None and hasattr(gci, 'set_antialiased'):
            gci.set_antialiased(True)
            gci.set_linewidth(0.3)
            gci.set_edgecolor("0.1")
        else:
            pg.mplviewer.drawSelectedMeshBoundaries(ax,
                                                    mesh.boundaries(),
                                                    color="0.1",
                                                    linewidth=0.3)
            #drawMesh(ax, mesh, **kwargs)

    if showBoundary is True or showBoundary is 1:
        b = mesh.boundaries(mesh.boundaryMarkers() != 0)
        pg.mplviewer.drawSelectedMeshBoundaries(ax,
                                                b,
                                                color=(0.0, 0.0, 0.0, 1.0),
                                                linewidth=1.4)

    fitView = kwargs.pop('fitView', True)
    if fitView:
        ax.set_xlim(mesh.xmin(), mesh.xmax())
        ax.set_ylim(mesh.ymin(), mesh.ymax())
        ax.set_aspect('equal')

    cbar = None

    if label is not None and colorBar is None:
        colorBar = True

    if colorBar and validData:
        # , **kwargs) # causes problems!
        labels = ['cMin', 'cMax', 'nLevs', 'cMap', 'logScale']
        subkwargs = {key: kwargs[key] for key in labels if key in kwargs}
        subkwargs['label'] = label

        if colorBar is True or colorBar is 1:
            cbar = createColorBar(gci,
                                  orientation=kwargs.pop(
                                      'orientation', 'horizontal'),
                                  size=kwargs.pop('size', 0.2),
                                  pad=kwargs.pop('pad', None))
            updateColorBar(cbar, **subkwargs)
        elif colorBar is not False:
            cbar = updateColorBar(colorBar, **subkwargs)

        if markers:
            ticks = np.arange(len(uniquemarkers))
            cbar.set_ticks(ticks)
            labels = []
            for marker in uniquemarkers:
                labels.append(str((marker)))
            cbar.set_ticklabels(labels)

    if coverage is not None:
        if len(data) == mesh.cellCount():
            addCoverageAlpha(gci, coverage)
        else:
            raise BaseException('toImplement')
            # addCoverageAlpha(gci, pg.cellDataToPointData(mesh, coverage))

    if not hold or block is not False and plt.get_backend() is not "Agg":
        if data is not None:
            if len(data) == mesh.cellCount():
                cb = CellBrowser(mesh, data, ax=ax)

        plt.show(block=block)
        try:
            plt.pause(0.01)
        except BaseException as _:

            pass

    if hold:
        pg.mplviewer.hold(val=lastHoldStatus)

    if savefig:
        print('saving: ' + savefig + ' ...')

        if '.' not in savefig:
            savefig += '.pdf'

        ax.figure.savefig(savefig, bbox_inches='tight')
        # rc params savefig.format=pdf

        if '.eps' in savefig:
            try:
                print("trying eps2pdf ... ")
                os.system('epstopdf ' + savefig)
            except BaseException:
                pass
        print('..done')

    return ax, cbar
Ejemplo n.º 2
0
# default (natural) BC that are of homogeneous Neumann type
# :math:`\frac{\partial u}{\partial n}=0`

ax = show(grid,
          data=u,
          filled=True,
          colorBar=True,
          orientation='vertical',
          label='Solution $u$',
          levels=np.linspace(min(u), max(u), 14),
          hold=1)[0]

###############################################################################
# Instead of the grid we now want to add streamlines to show the gradients of
# the solution (i.e., the flow direction).
drawStreams(ax, grid, u)

ax.text(0.0, 1.01, '$u=1$', horizontalalignment='center')  # top -- 3
ax.text(-1.0,
        0.0,
        '$\partial u/\partial n=-0.5$',
        va='center',
        ha='right',
        rotation='vertical')  # left -- 1
ax.text(0.0, -1.01, '$\partial u/\partial n=2.5$', ha='center',
        va='top')  # bot -- 4
ax.text(1.01,
        0.0,
        '$\partial u/\partial n=0$',
        va='center',
        ha='left',
               [3, lambda b_: 1. - np.tanh(10.)],
               [4, lambda b_: 1. + np.tanh(10 * (2 * b_.center()[0] + 1.))],
               ]

print ("start", swatch.duration())
uGrid = solveFiniteVolume(grid, a=1./Peclet, f=f, vel=vB,
                          uBoundary=dirichletBC,
                          duBoundary=neumannBC,
                          scheme=scheme)
            

ax1,cb = show(grid)


drawStreams(ax1, grid, vC, coarseMesh=pg.createGrid(x=np.linspace(-1.0, 1.0, 41),
                                                    y=np.linspace(0.0, 1.0, 21)),
            )
print(swatch.duration())

#grid2, u2 = createFVPostProzessMesh(grid, u, dirichletBC)
show(grid, data=uGrid, 
     logScale=False, interpolate=1, tri=1,
     colorBar=True, axes=ax1)

#unstructured
boundary = []
boundary.append([-1.0, 0.0])
boundary.append([ 0.0, 0.0])
boundary.append([ 1.0, 0.0])
boundary.append([ 1.0, 1.0])
boundary.append([-1.0, 1.0])
               [4, lambda b_: 1. + np.tanh(10 * (2 * b_.center()[0] + 1.))],
               ]

print ("start", swatch.duration())
uGrid = solveFiniteVolume(grid, a=1./Peclet, f=f, vel=vB,
                          uBoundary=dirichletBC,
                          duBoundary=neumannBC,
                          scheme=scheme)
            

pg.showLater(1)
ax1,cb = show(grid)


drawStreams(ax1, grid, vC, coarseMesh=pg.createGrid(x=np.linspace(-1.0, 1.0, 41),
                                                    y=np.linspace(0.0, 1.0, 21)),
            )
print(swatch.duration())

#grid2, u2 = createFVPostProzessMesh(grid, u, dirichletBC)
show(grid, data=uGrid, 
     logScale=False, interpolate=1, tri=1,
     colorBar=True, axes=ax1)

#unstructured
boundary = []
boundary.append([-1.0, 0.0])
boundary.append([ 0.0, 0.0])
boundary.append([ 1.0, 0.0])
boundary.append([ 1.0, 1.0])
boundary.append([-1.0, 1.0])
Ejemplo n.º 5
0
k = 1e-3
sigma = 1
u = solve(grid, a=sigma, b=sigma * k*k, f=pointSource,
          duB=neumannBC,
          userData={'sourcePos': sourcePosA, 'k': k},
          verbose=True)

u -= solve(grid, a=sigma, b=sigma * k*k, f=pointSource,
           duB=neumannBC,
           userData={'sourcePos': sourcePosB, 'k': k},
           verbose=True)

# uAna = pg.RVector(map(lambda p__: uAnalytical(p__, sourcePosA, k),
#                       grid.positions()))
# uAna -= pg.RVector(map(lambda p__: uAnalytical(p__, sourcePosB, k),
#                        grid.positions()))

# err = (1.0 -u/uAna) * 100.0

# print("error min max", min(err), max(err))

ax = show(grid, data=u, filled=True, colorBar=True, cmap="RdBu_r",
          orientation='horizontal', label='Solution u', hold=True)[0]
show(grid, ax=ax, hold=True)
gridCoarse = pg.createGrid(x=np.linspace(-10.0, 10.0, 20),
                           y=np.linspace(-15.0, .0, 20))
# Instead of the grid we want to add streamlines to the plot to show the
# gradients of the solution.
drawStreams(ax, grid, u, coarseMesh=gridCoarse, color='Black')
pg.wait()
Ejemplo n.º 6
0
def showMesh(mesh, data=None, hold=False, block=False,
             colorBar=False, coverage=None,
             axes=None, savefig=None, **kwargs):
    """
    2D Mesh visualization.

    Create an axes and plot node or cell values for the given 2d mesh.
    Returns the axes and the color bar.

    Parameters
    ----------

    mesh : :gimliapi:`GIMLI::Mesh`
        2D or 3D GIMLi mesh

    data : iterable [None]
        Optionally data to visualize.

        . None (draw mesh only)
            forward to :py:mod:`pygimli.mplviewer.meshview.drawMesh`

        . float per cell -- model, patch
            forward to :py:mod:`pygimli.mplviewer.meshview.drawModel`

        . float per node -- scalar field
            forward to :py:mod:`pygimli.mplviewer.meshview.drawField`

        . iterable of type [float, float] -- vector field
            forward to :py:mod:`pygimli.mplviewer.meshview.drawStreams`

        . pg.stdVectorRVector3 -- sensor positions
            forward to :py:mod:`pygimli.mplviewer.meshview.drawSensors`

    hold : bool [false]
        Set interactive plot mode for matplotlib.
        If this is set to false [default] your script will open
        a window with the figure and draw your content.
        If set to true nothing happens until you either force another show with
        hold=False, you call plt.show() or pg.wait().
        If you want show with stopping your script set block = True.

    block : bool [false]
        Force show drawing your content and block the script until you
        close the current figure.

    colorBar : bool [false]
        Create and show a colorbar.

    coverage : iterable [None]
        Weight data by the given coverage array and fadeout the color.

    axes : matplotlib.Axes [None]
        Instead of create a new and empty axes, just draw into the a given.
        Useful to combine draws.

    savefig: string
        Filename for a direct save to disc.
        The matplotlib pdf-output is a little bit big so we try
        an epstopdf if the .eps suffix is found in savefig

    **kwargs :
        Will be forwarded to the draw functions and matplotlib methods,
        respectively.

    Returns
    -------
    axes : matplotlib.axes

    colobar : matplotlib.colobar
    """

    ax = axes
    if block:
        hold = 1

    if hold:
        lastHoldStatus = pg.mplviewer.holdAxes_
        pg.mplviewer.holdAxes_ = 1

    if ax is None:
        fig, ax = plt.subplots()

    gci = None
    cbar = None
    validData = False

    if data is None:
        drawMesh(ax, mesh)
    elif isinstance(data, pg.stdVectorRVector3):
        drawSensors(ax, data)
    else:
        if hasattr(data[0], '__len__') and not isinstance(data,
                                                          np.ma.core.MaskedArray):

            if len(data) == 2:  # [u,v]
                data = np.array(data).T

            if sum(data[:, 0]) != sum(data[:, 1]):
                drawStreams(ax, mesh, data, **kwargs)
            else:
                print("No valid stream data:", data)
                drawMesh(ax, mesh)

        elif (min(data) == max(data)):  # or pg.haveInfNaN(data):

            print("No valid data: ", min(data), max(data), pg.haveInfNaN(data))
            drawMesh(ax, mesh)
        else:
            validData = True
            try:
                if len(data) == mesh.cellCount():
                    gci = drawModel(ax, mesh, data, **kwargs)
                elif len(data) == mesh.nodeCount():
                    gci = drawField(ax, mesh, data, **kwargs)
            except Exception as e:
                print("Exception occured: " + e)
                print("Data: ", min(data), max(data), pg.haveInfNaN(data))
                print("Mesh: ", mesh)
                drawMesh(ax, mesh)

    ax.set_aspect('equal')

    label = kwargs.pop('label', None)

    if colorBar and validData:
        # , *args, **kwargs) # causes problems!
        cbar = createColorbar(gci, label=label, **kwargs)

    plt.tight_layout()

    if coverage is not None:
        if len(data) == mesh.cellCount():
            addCoverageAlpha(gci, coverage)
        else:
            raise('toImplement')
            addCoverageAlpha(gci, pg.cellDataToPointData(mesh, coverage))

    if showLater in kwargs:
        hold = showLater
        print("showLater will be removed in the future. use hold instead")

    if not hold or block is not False:
        plt.show(block=block)
        try:
            plt.pause(0.01)
        except:
            pass

    if hold:
        pg.mplviewer.holdAxes_ = lastHoldStatus

    if savefig:
        print('saving: ' + savefig + ' ...')
        ax.figure.savefig(savefig, bbox_inches='tight')

        if '.eps' in savefig:
            try:
                print("trying eps2pdf ... ")
                os.system('epstopdf ' + savefig)
            except:
                pass
        print('..done')

    return ax, cbar
Ejemplo n.º 7
0
u -= solve(grid, a=sigma, b=-sigma * k*k, f=pointSource(grid, sourcePosB),
           bc={'Robin': robBC},
           userData={'sourcePos': sourcePosB, 'k': k},
           verbose=True)

# uAna = pg.RVector(map(lambda p__: uAnalytical(p__, sourcePosA, k),
#                       grid.positions()))
# uAna -= pg.RVector(map(lambda p__: uAnalytical(p__, sourcePosB, k),
#                        grid.positions()))

# err = (1.0 -u/uAna) * 100.0

# print("error min max", min(err), max(err))

ax = show(grid, data=u, fillContour=True, colorBar=True, cMap="RdBu_r",
          orientation='horizontal', label='Solution u', nLevs=11,
          logScale=False, hold=True, showMesh=True)[0]

# Additional to the image of the potential we want to see the current flow too.
# The current flows along the gradient of our solution and can be plotted as
# stream lines. On default the drawStreams method draws one segment of a
# stream line per cell of the mesh. This can be a little confusing for dense
# meshes so we can give a second (coarse) mesh as a new cell basis to draw the
# streams. If the drawStreams get scalar data the gradients will be calculated.

gridCoarse = pg.createGrid(x=np.linspace(-10.0, 10.0, 20),
                           y=np.linspace(-15.0,   .0, 20))
drawStreams(ax, grid, u, coarseMesh=gridCoarse, color='Black')

pg.wait()
Ejemplo n.º 8
0
# or natural BC that are of homogeneous Neumann type
# :math:`\frac{\partial u}{\partial n}=0`

ax = show(
    grid,
    data=u,
    filled=True,
    colorBar=True,
    orientation="vertical",
    label="Solution $u$",
    levels=np.linspace(min(u), max(u), 14),
    hold=1,
)[0]

###############################################################################
# Instead of the grid we now want to add streamlines to the plot to show the
# gradients of the solution (i.e., the flow direction).
drawStreams(ax, grid, u)

ax.text(0.0, 1.01, "$u=1$", horizontalalignment="center")  # top -- 3
ax.text(-1.0, 0.0, "$\partial u/\partial n=-0.5$", va="center", ha="right", rotation="vertical")  # left -- 1
ax.text(0.0, -1.01, "$\partial u/\partial n=2.5$", ha="center", va="top")  # bot -- 4
ax.text(1.01, 0.0, "$\partial u/\partial n=0$", va="center", ha="left", rotation="vertical")  # right -- 2

ax.set_title("$\\nabla\cdot(1\\nabla u)=0$")

ax.set_xlim([-1.1, 1.1])
ax.set_ylim([-1.1, 1.1])

pg.wait()
Ejemplo n.º 9
0
def showMesh(mesh,
             data=None,
             hold=False,
             block=False,
             colorBar=None,
             label=None,
             coverage=None,
             ax=None,
             savefig=None,
             **kwargs):
    """2D Mesh visualization.

    Create an axis object and plot a 2D mesh with given node or cell data.
    Returns the axis and the color bar. The type of data determine the
    appropriate draw method.

    Parameters
    ----------

    mesh : :gimliapi:`GIMLI::Mesh`
        2D or 3D GIMLi mesh

    data : iterable [None]
        Optionally data to visualize.

        . None (draw mesh only)
            forward to :py:mod:`pygimli.mplviewer.drawMesh`
            or if no cells are given:
            forward to :py:mod:`pygimli.mplviewer.drawPLC`

        . float per cell -- model, patch
            forward to :py:mod:`pygimli.mplviewer.drawModel`

        . float per node -- scalar field
            forward to :py:mod:`pygimli.mplviewer.drawField`

        . iterable of type [float, float] -- vector field
            forward to :py:mod:`pygimli.mplviewer.drawStreams`

        . pg.stdVectorRVector3 -- sensor positions
            forward to :py:mod:`pygimli.mplviewer.drawSensors`

    hold : bool [false]
        Set interactive plot mode for matplotlib.
        If this is set to false [default] your script will open
        a window with the figure and draw your content.
        If set to true nothing happens until you either force another show with
        hold=False, you call plt.show() or pg.wait().
        If you want show with stopping your script set block = True.

    block : bool [false]
        Force show drawing your content and block the script until you
        close the current figure.

    colorBar : bool [None], Colorbar
        Create and show a colorbar. If colorBar is a valid colorbar then only
        his values will be updated.

    label : str
        Set colorbar label. If set colorbar is toggled to True. [None]

    coverage : iterable [None]
        Weight data by the given coverage array and fadeout the color.

    ax : matplotlib.Axes [None]
        Instead of create a new and empty ax, just draw into the a given.
        Useful to combine draws.

    savefig: string
        Filename for a direct save to disc.
        The matplotlib pdf-output is a little bit big so we try
        an epstopdf if the .eps suffix is found in savefig

    **kwargs :
        * xlabel : str [None]
            Add label to the x axis

        * ylabel : str [None]
            Add label to the y axis

        * all remaining
            Will be forwarded to the draw functions and matplotlib methods,
            respectively.

    Returns
    -------
    ax : matplotlib.ax

    colobar : matplotlib.colobar
    """
    ax = ax
    if block:
        hold = 1

    if hold:
        lastHoldStatus = pg.mplviewer.utils.holdAxes__
        pg.mplviewer.hold(val=1)

    # print('1*'*50)
    # print(locale.localeconv())

    if ax is None:
        ax = plt.subplots()[1]

    # plt.subplots() resets locale setting to system default .. this went
    # horrible wrong for german 'decimal_point': ','
    pg.checkAndFixLocaleDecimal_point(verbose=False)

    # print('2*'*50)
    # print(locale.localeconv())

    gci = None
    validData = False

    if data is None:
        drawMesh(ax, mesh, **kwargs)
    elif isinstance(data, pg.stdVectorRVector3):
        drawSensors(ax, data, **kwargs)
    else:
        # print(data, type(data))
        if (hasattr(data[0], '__len__')
                and not isinstance(data, np.ma.core.MaskedArray)):

            if len(data) == 2:  # [u,v]
                data = np.array(data).T

            if sum(data[:, 0]) != sum(data[:, 1]):
                drawStreams(ax, mesh, data, **kwargs)
            else:
                print("No valid stream data:", data)
                drawMesh(ax, mesh, **kwargs)
        elif min(data) == max(data):  # or pg.haveInfNaN(data):
            print("No valid data: ", min(data), max(data), pg.haveInfNaN(data))
            drawMesh(ax, mesh, **kwargs)
        else:
            validData = True
            try:
                if len(data) == mesh.cellCount():
                    gci = drawModel(ax, mesh, data, **kwargs)
                elif len(data) == mesh.nodeCount():
                    gci = drawField(ax, mesh, data, **kwargs)

                cmap = kwargs.pop('cmap', None)
                cMap = kwargs.pop('cMap', None)
                if cMap is not None:
                    cmap = cMap

                if cmap is not None:
                    gci.set_cmap(cmapFromName(cmap))

            except BaseException as e:
                print("Exception occured: " + e)
                print("Data: ", min(data), max(data), pg.haveInfNaN(data))
                print("Mesh: ", mesh)
                drawMesh(ax, mesh, **kwargs)

    ax.set_aspect('equal')

    cbar = None

    if label is not None and colorBar is None:
        colorBar = True

    if colorBar and validData:
        # , **kwargs) # causes problems!
        labels = ['cMin', 'cMax', 'nLevs', 'orientation', 'pad']
        subkwargs = {key: kwargs[key] for key in labels if key in kwargs}

        if colorBar is True or colorBar is 1:
            cbar = createColorBar(gci, label=label, **subkwargs)
        elif colorBar is not False:
            cbar = updateColorBar(colorBar, gci, label=label, **subkwargs)

    if coverage is not None:
        if len(data) == mesh.cellCount():
            addCoverageAlpha(gci, coverage)
        else:
            raise BaseException('toImplement')
            # addCoverageAlpha(gci, pg.cellDataToPointData(mesh, coverage))

    if not hold or block is not False:
        if data is not None:
            if len(data) == mesh.cellCount():
                cb = CellBrowser(mesh, data, ax=ax)
                cb.connect()

        plt.show(block=block)
        try:
            plt.pause(0.01)
        except BaseException as _:

            pass

    if hold:
        pg.mplviewer.hold(val=lastHoldStatus)

    if savefig:
        print('saving: ' + savefig + ' ...')

        if '.' not in savefig:
            savefig += '.pdf'

        ax.figure.savefig(savefig, bbox_inches='tight')
        # rc params savefig.format=pdf

        if '.eps' in savefig:
            try:
                print("trying eps2pdf ... ")
                os.system('epstopdf ' + savefig)
            except BaseException as _:
                pass
        print('..done')

    return ax, cbar
Ejemplo n.º 10
0
def showMesh(mesh, data=None, hold=False, block=False, colorBar=None,
             label=None, coverage=None, ax=None, savefig=None,
             showMesh=False, showBoundary=None,
             markers=False, **kwargs):
    """2D Mesh visualization.

    Create an axis object and plot a 2D mesh with given node or cell data.
    Returns the axis and the color bar. The type of data determines the
    appropriate draw method.

    Parameters
    ----------

    mesh : :gimliapi:`GIMLI::Mesh`
        2D or 3D GIMLi mesh

    data : iterable [None]
        Optionally data to visualize.

        . None (draw mesh only)
            forward to :py:mod:`pygimli.mplviewer.drawMesh`
            or if no cells are given:
            forward to :py:mod:`pygimli.mplviewer.drawPLC`

        . [[marker, value], ...]
            List of Cellvalues per cell marker
            forward to :py:mod:`pygimli.mplviewer.drawModel`

        . float per cell -- model, patch
            forward to :py:mod:`pygimli.mplviewer.drawModel`

        . float per node -- scalar field
            forward to :py:mod:`pygimli.mplviewer.drawField`

        . iterable of type [float, float] -- vector field
            forward to :py:mod:`pygimli.mplviewer.drawStreams`

        . pg.R3Vector -- vector field
            forward to :py:mod:`pygimli.mplviewer.drawStreams`

        . pg.stdVectorRVector3 -- sensor positions
            forward to :py:mod:`pygimli.mplviewer.drawSensors`


    hold : bool [false]
        Set interactive plot mode for matplotlib.
        If this is set to false [default] your script will open
        a window with the figure and draw your content.
        If set to true nothing happens until you either force another show with
        hold=False, you call plt.show() or pg.wait().
        If you want show with stopping your script set block = True.

    block : bool [false]
        Force show drawing your content and block the script until you
        close the current figure.

    colorBar : bool [None], Colorbar
        Create and show a colorbar. If colorBar is a valid colorbar then only
        its values will be updated.

    label : str
        Set colorbar label. If set colorbar is toggled to True. [None]

    coverage : iterable [None]
        Weight data by the given coverage array and fadeout the color.

    ax : matplotlib.Axes [None]
        Instead of creating a new and empty ax, just draw into the given one.
        Useful to combine multiple plots into one figure.

    savefig: string
        Filename for a direct save to disc.
        The matplotlib pdf-output is a little bit big so we try
        an epstopdf if the .eps suffix is found in savefig

    showMesh : bool [False]
        Shows the mesh itself aditional.

    showBoundary : bool [None]
        Shows all boundary with marker != 0. A value None means automatic
        True for cell data and False for node data.

    marker : bool [False]
        Show mesh and boundary marker.

    **kwargs :
        * xlabel : str [None]
            Add label to the x axis

        * ylabel : str [None]
            Add label to the y axis

        * all remaining
            Will be forwarded to the draw functions and matplotlib methods,
            respectively.

    Examples
    --------
    >>> import pygimli as pg
    >>> import pygimli.meshtools as mt
    >>> world = mt.createWorld(start=[-10, 0], end=[10, -10],
    ...                        layers=[-3, -7], worldMarker=False)
    >>> mesh = mt.createMesh(world, quality=32, area=0.2, smooth=[1, 10])
    >>> _ = pg.viewer.showMesh(mesh, markers=True)

    Returns
    -------
    ax : matplotlib.axes

    colobar : matplotlib.colorbar
    """
    pg.renameKwarg('cmap', 'cMap', kwargs)

    if ax is None:
        ax = plt.subplots()[1]

    # print('1*'*50)
    # print(locale.localeconv())

    # plt.subplots() resets locale setting to system default .. this went
    # horrible wrong for german 'decimal_point': ','
    pg.checkAndFixLocaleDecimal_point(verbose=False)

    # print('2*'*50)
    # print(locale.localeconv())

    if block:
        hold = True

    lastHoldStatus = pg.mplviewer.utils.holdAxes__
    if not lastHoldStatus or hold:
        pg.mplviewer.hold(val=1)
        hold = True

    gci = None
    validData = False

    if markers:
        kwargs["boundaryMarker"] = True
        if mesh.cellCount() > 0:
            uniquemarkers, uniqueidx = np.unique(
                np.array(mesh.cellMarkers()), return_inverse=True)
            label = "Cell markers"
            kwargs["cMap"] = plt.cm.get_cmap("Set3", len(uniquemarkers))
            kwargs["logScale"] = False
            kwargs["cMin"] = -0.5
            kwargs["cMax"] = len(uniquemarkers) - 0.5
            data = np.arange(len(uniquemarkers))[uniqueidx]

    if data is None:
        showMesh = True
        if showBoundary is None:
            showBoundary = True
    elif isinstance(data, pg.stdVectorRVector3):
        drawSensors(ax, data, **kwargs)
    elif isinstance(data, pg.R3Vector):
        drawStreams(ax, mesh, data, **kwargs)
    else:
        ### data=[[marker, val], ....]
        if isinstance(data, list) and \
            isinstance(data[0], list) and isinstance(data[0][0], int):
            data = pg.solver.parseMapToCellArray(data, mesh)

        if hasattr(data[0], '__len__') and not \
            isinstance(data, np.ma.core.MaskedArray):

            if len(data) == 2:  # [u,v] x N
                data = np.array(data).T

            if data.shape[1] == 2:
                drawStreams(ax, mesh, data, **kwargs)

            elif data.shape[1] == 3:  # probably N x [u,v,w]
                # if sum(data[:, 0]) != sum(data[:, 1]):
                # drawStreams(ax, mesh, data, **kwargs)
                drawStreams(ax, mesh, data[:, 0:2], **kwargs)
            else:
                pg.warn("No valid stream data:", data.shape, data.ndim)
                showMesh = True
        elif min(data) == max(data):  # or pg.haveInfNaN(data):
            pg.warn("No valid data: ", min(data), max(data), pg.haveInfNaN(data))
            showMesh = True
        else:
            validData = True
            try:
                cMap = kwargs.pop('cMap', None)
                
                if len(data) == mesh.cellCount():
                    gci = drawModel(ax, mesh, data, **kwargs)
                    if showBoundary is None:
                        showBoundary = True

                elif len(data) == mesh.nodeCount():
                    gci = drawField(ax, mesh, data, **kwargs)

                if cMap is not None:
                    gci.set_cmap(cmapFromName(cMap))
                    #gci.cmap.set_under('k')

            except BaseException as e:
                print("Exception occured: ", e)
                print("Data: ", min(data), max(data), pg.haveInfNaN(data))
                print("Mesh: ", mesh)
                drawMesh(ax, mesh, **kwargs)

    if mesh.cellCount() == 0:
        showMesh = False
        if mesh.boundaryCount() == 0:
            pg.mplviewer.drawPLC(ax, mesh, showNodes=True,
                                 fillRegion=False, showBoundary=False,
                                 **kwargs)
            showBoundary = False
            #ax.plot(pg.x(mesh), pg.y(mesh), '.', color='black')
        else:
            pg.mplviewer.drawPLC(ax, mesh, **kwargs)


    if showMesh:
        if gci is not None and hasattr(gci, 'set_antialiased'):
            gci.set_antialiased(True)
            gci.set_linewidth(0.3)
            gci.set_edgecolor("0.1")
        else:
            pg.mplviewer.drawSelectedMeshBoundaries(ax, mesh.boundaries(),
                                                    color="0.1", linewidth=0.3)
            #drawMesh(ax, mesh, **kwargs)

    if showBoundary is True or showBoundary is 1:
        b = mesh.boundaries(mesh.boundaryMarkers() != 0)
        pg.mplviewer.drawSelectedMeshBoundaries(ax, b,
                                                color=(0.0, 0.0, 0.0, 1.0),
                                                linewidth=1.4)

    fitView = kwargs.pop('fitView', True)
    if fitView:
        ax.set_xlim(mesh.xmin(), mesh.xmax())
        ax.set_ylim(mesh.ymin(), mesh.ymax())
        ax.set_aspect('equal')

    cbar = None

    if label is not None and colorBar is None:
        colorBar = True

    if colorBar and validData:
        # , **kwargs) # causes problems!
        labels = ['cMin', 'cMax', 'nLevs', 'cMap', 'logScale']
        subkwargs = {key: kwargs[key] for key in labels if key in kwargs}
        subkwargs['label'] = label

        if colorBar is True or colorBar is 1:
            cbar = createColorBar(gci,
                                  orientation=kwargs.pop('orientation',
                                                         'horizontal'),
                                  size=kwargs.pop('size', 0.2),
                                  pad=kwargs.pop('pad', None)
                                  )
            updateColorBar(cbar, **subkwargs)
        elif colorBar is not False:
            cbar = updateColorBar(colorBar, **subkwargs)

        if markers:
            ticks = np.arange(len(uniquemarkers))
            cbar.set_ticks(ticks)
            labels = []
            for marker in uniquemarkers:
                labels.append(str((marker)))
            cbar.set_ticklabels(labels)

    if coverage is not None:
        if len(data) == mesh.cellCount():
            addCoverageAlpha(gci, coverage)
        else:
            raise BaseException('toImplement')
            # addCoverageAlpha(gci, pg.cellDataToPointData(mesh, coverage))

    if not hold or block is not False and plt.get_backend() is not "Agg":
        if data is not None:
            if len(data) == mesh.cellCount():
                cb = CellBrowser(mesh, data, ax=ax)

        plt.show(block=block)
        try:
            plt.pause(0.01)
        except BaseException as _:

            pass

    if hold:
        pg.mplviewer.hold(val=lastHoldStatus)

    if savefig:
        print('saving: ' + savefig + ' ...')

        if '.' not in savefig:
            savefig += '.pdf'

        ax.figure.savefig(savefig, bbox_inches='tight')
        # rc params savefig.format=pdf

        if '.eps' in savefig:
            try:
                print("trying eps2pdf ... ")
                os.system('epstopdf ' + savefig)
            except BaseException:
                pass
        print('..done')

    return ax, cbar
Ejemplo n.º 11
0
grid=pg.createGrid(x,y)
fig = plt.figure()
ax1 = fig.add_subplot(1, 3, 1)
ax2 = fig.add_subplot(1, 3, 2)
ax3 = fig.add_subplot(1, 3, 3)

pl = pg.logTransDropTol(np.array((p.T).flat), 1e-2)
ul = pg.logTransDropTol(np.array((u.T).flat), 1e-2)
vl = pg.logTransDropTol(np.array((v.T).flat), 1e-2)

show(grid, pl, logScale=False, showLater=True, colorBar=True, axes=ax1, cmap='b2r')
show(grid, ul, logScale=False, showLater=True, colorBar=True, axes=ax2)
show(grid, vl, logScale=False, showLater=True, colorBar=True, axes=ax3)

vel = np.vstack([np.array((u.T).flat), np.array((v.T).flat)]).T    
drawStreams(ax1, grid, vel)
    
#im1 = ax1.contourf(X,Y,p,alpha=0.5)    ###plnttong the pressure field as a contour
#divider1 = make_axes_locatable(ax1)
#cax1 = divider1.append_axes("right", size="20%", pad=0.05)
#cbar1 = plt.colorbar(im1, cax=cax1)

#im2 = ax2.contourf(X,Y,u,alpha=0.5)    ###plnttong the pressure field as a contour
#divider2 = make_axes_locatable(ax2)
#cax2 = divider2.append_axes("right", size="20%", pad=0.05)
#cbar2 = plt.colorbar(im2, cax=cax2)

#im3 = ax3.contourf(X,Y,v,alpha=0.5)    ###plnttong the pressure field as a contour
#divider3 = make_axes_locatable(ax3)
#cax3 = divider3.append_axes("right", size="20%", pad=0.05)
#cbar3 = plt.colorbar(im3, cax=cax3)