Beispiel #1
0
def drawMesh(axes, mesh, **kwargs):
    """
    Draw a 2d mesh into a given axes.

    Set the limits of the axes tor the mesh extent.

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> import pygimli as pg
    >>> from pygimli.mplviewer import drawMesh
    >>> n = np.linspace(1,2,10)
    >>> mesh = pg.createGrid(x=n, y=n)
    >>> fig, ax = plt.subplots()
    >>> drawMesh(ax, mesh)
    >>> plt.show()
    """

    pg.mplviewer.drawMeshBoundaries(axes, mesh, fitView=False)

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

    updateAxes_(axes)
Beispiel #2
0
def drawStreamLines(axes, mesh, u, nx=25, ny=25, **kwargs):
    """
    Draw streamlines for the gradients of field values u on a mesh.

    The matplotlib routine streamplot needs equidistant spacings so
    we interpolate first on a grid defined by nx and ny nodes.
    Additionally arguments are piped to streamplot.

    This works only for rectangular regions.
    drawStreamLine is more comfortable and more flexible.
    """

    X, Y = np.meshgrid(np.linspace(mesh.xmin(), mesh.xmax(), nx),
                       np.linspace(mesh.ymin(), mesh.ymax(), ny))

    U = X.copy()
    V = X.copy()

    for i, row in enumerate(X):
        for j in range(len(row)):
            p = [X[i, j], Y[i, j]]
            gr = [0.0, 0.0]
            c = mesh.findCell(p)
            if c:
                gr = c.grad(p, u)

            U[i, j] = -gr[0]
            V[i, j] = -gr[1]

    gci = axes.streamplot(X, Y, U, V, **kwargs)

    updateAxes_(axes)
    return gci
Beispiel #3
0
def drawSensors(axes, sensors, diam=None, koords=None):
    """
    Draw sensor positions as black dots with a given diameter.

    Parameters
    ----------

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from pygimli.mplviewer import drawSensors
    >>> sensors = np.random.rand(5,2)
    >>> fig, ax = plt.subplots()
    >>> drawSensors(ax, sensors, diam=0.02, koords=[0,1])
    >>> ax.set_aspect('equal')
    """

    if koords is None:
        koords = [0, 2]

    eCircles = []

    if diam is None:
        eSpacing = sensors[0].distance(sensors[1])
        diam = eSpacing / 8.0

    for e in sensors:
        eCircles.append(mpl.patches.Circle((e[koords[0]], e[koords[1]]), diam))

    p = mpl.collections.PatchCollection(eCircles, color=(0.0, 0.0, 0.0))
    axes.add_collection(p)

    updateAxes_(axes)
Beispiel #4
0
def drawMPLTri(axes, mesh, data=None, cMin=None, cMax=None, logScale=True,
               cmap=None, interpolate=False, omitLines=False, **kwargs):
    """
        Only for triangle/quadrangle meshes currently
    """
    x, y, triangles, z, zIdx = createTriangles(mesh, data)

    gci = None

    levels = kwargs.pop('levels', [])
    nLevs = kwargs.pop('nLevs', 8)
    if len(levels) == 0:
        levels = autolevel(data, nLevs)

    if interpolate and len(data) == mesh.cellCount():
        z = pg.cellDataToPointData(mesh, data)

    if len(z) == len(triangles):
        shading = kwargs.pop('shading', 'flat')
        if shading == 'gouraud':
            z = pg.cellDataToPointData(mesh, data)

        gci = axes.tripcolor(x, y, triangles, z, levels, shading=shading,
                             **kwargs)

    elif len(z) == mesh.nodeCount():
        shading = kwargs.pop('shading', None)

        if shading is not None:
            gci = axes.tripcolor(x, y, triangles, z, levels, shading=shading,
                                 **kwargs)
        else:
            gci = axes.tricontourf(x, y, triangles, z, levels,
                                   **kwargs)
            if not omitLines:
                axes.tricontour(x, y, triangles, z, levels,
                                colors=kwargs.pop('colors', ['0.5']),
                                **kwargs)
    else:
        gci = None
        raise Exception("Data size does not fit mesh size: ",
                        len(z), mesh.cellCount(), mesh.nodeCount())

    if gci and cMin and cMax:
        gci.set_clim(cMin, cMax)

    if cmap is not None:
        if cmap == 'b2r':
            gci.set_cmap(cmapFromName('b2r'))
        else:
            gci.set_cmap(cmap)

    axes.set_aspect('equal')

    if kwargs.pop('fitView', True):
        axes.set_xlim(mesh.xmin(), mesh.xmax())
        axes.set_ylim(mesh.ymin(), mesh.ymax())

    updateAxes_(axes)
    return gci
Beispiel #5
0
def drawParameterConstraints(axes, mesh, cMat, cWeight=None):
    """
        What is this?
    """
    start, end = createParameterContraintsLines(mesh, cMat, cWeight)

    lines = []
    colors = []
    linewidths = []
    for i in range(len(start)):
        lines.append(list(zip([start[i].x(), end[i].x()],
                              [start[i].y(), end[i].y()])))

        linewidth = 0.5
        col = (0.0, 0.0, 1.0, 1.0)
        colors.append(col)
        linewidths.append(linewidth)

    linCol = mpl.collections.LineCollection(lines, antialiaseds=True)

    linCol.set_color(colors)
    linCol.set_linewidth(linewidths)
    axes.add_collection(linCol)

    updateAxes_(axes)
Beispiel #6
0
def createMeshPatches(axes, mesh, verbose=True, **kwargs):
    """
       Utility function to create 2d mesh patches in a axes
    """
    if not mesh:
        print("drawMeshBoundaries(axes, mesh): invalid mesh")
        return

    if mesh.nodeCount() < 2:
        print("drawMeshBoundaries(axes, mesh): to few nodes")
        return

    swatch = pg.Stopwatch(True)

    if kwargs.pop('fitView', True):
        axes.set_xlim(mesh.xmin(), mesh.xmax())
        axes.set_ylim(mesh.ymin(), mesh.ymax())

    polys = []

    for cell in mesh.cells():
        if (cell.shape().nodeCount() == 3):
            polys.append(list(zip(
                [cell.node(0).x(), cell.node(1).x(), cell.node(2).x()],
                [cell.node(0).y(), cell.node(1).y(), cell.node(2).y()])))
        elif (cell.shape().nodeCount() == 4):
            polys.append(list(zip([cell.node(0).x(), cell.node(1).x(),
                                   cell.node(2).x(), cell.node(3).x()],
                                  [cell.node(0).y(), cell.node(1).y(),
                                   cell.node(2).y(), cell.node(3).y()])))
        else:
            print(("unknown shape to patch: ", cell.shape(),
                   cell.shape().nodeCount()))

    patches = mpl.collections.PolyCollection(polys, antialiaseds=False,
                                             lod=True, picker=True)

#    patches.set_edgecolor(None)
    patches.set_edgecolor('face')
#    patches.set_linewidth(1.001)
    axes.add_collection(patches)

    updateAxes_(axes)

    if verbose:
        print(("plotting time = ", swatch.duration(True)))
    return patches
Beispiel #7
0
def draw1DColumn(ax, x, val, thk, width=30, ztopo=0, cmin=1, cmax=1000,
                 cmap=None, name=None, textoffset=0.0):
    """
    Draw a 1D column (e.g., from a 1D inversion) on a given axes.

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from pygimli.mplviewer import draw1DColumn
    >>> thk = [1,2,3,4]
    >>> val = thk
    >>> fig, ax = plt.subplots()
    >>> draw1DColumn(ax, 0.5, val, thk, width=0.1, cmin=1, cmax=4, name="VES")
    <matplotlib.collections.PatchCollection object at ...>
    >>> ax.set_ylim(-np.sum(thk), 0)
    (-10, 0)
    """
    z = -np.hstack((0., np.cumsum(thk), np.sum(thk) * 1.5)) + ztopo
    recs = []
    for i in range(len(val)):
        recs.append(Rectangle((x - width / 2., z[i]), width, z[i + 1] - z[i]))

    pp = PatchCollection(recs)
    col = ax.add_collection(pp)

    pp.set_edgecolor(None)
    pp.set_linewidths(0.0)
    
    if cmap is not None:
        pp.set_cmap(cmap)
    
    pp.set_norm(LogNorm(cmin, cmax))
    pp.set_array(np.array(val))
    pp.set_clim(cmin, cmax)
    if name:
        ax.text(x+textoffset, ztopo, name, ha='center', va='bottom')

    updateAxes_(ax)

    return col
Beispiel #8
0
def drawMesh(axes, mesh, **kwargs):
    """
    Draw a 2d mesh into a given axes.

    Set the limits of the axes tor the mesh extent.

    Parameters
    ----------

    mesh : :gimliapi:`GIMLI::Mesh`
        The plotted mesh to browse through.
    ax : mpl axis instance, optional
        Axis instance where the mesh is plotted (default is current axis).
    fitView: bool [True]
        Adjust axes limits to mesh bounding box.
        

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> import pygimli as pg
    >>> from pygimli.mplviewer import drawMesh
    >>> n = np.linspace(1,2,10)
    >>> mesh = pg.createGrid(x=n, y=n)
    >>> fig, ax = plt.subplots()
    >>> drawMesh(ax, mesh)
    >>> plt.show()
    """

    pg.mplviewer.drawMeshBoundaries(axes, mesh, **kwargs)

    if kwargs.pop('fitView', True):
        axes.set_xlim(mesh.xmin(), mesh.xmax())
        axes.set_ylim(mesh.ymin(), mesh.ymax())

    axes.set_aspect('equal')
    updateAxes_(axes)
Beispiel #9
0
def drawSelectedMeshBoundaries(axes, boundaries,
                               color=(0.0, 0.0, 0.0, 1.0), linewidth=1.0):
    """Draw mesh boundaries into a given axes'."""

    drawAA = True
    lines = []

    if hasattr(boundaries, '__len__'):
        if len(boundaries) == 0:
            return

    for bound in boundaries:
        lines.append(list(zip([bound.node(0).x(), bound.node(1).x()],
                              [bound.node(0).y(), bound.node(1).y()])))

    lineCollection = mpl.collections.LineCollection(lines, antialiaseds=drawAA)

    lineCollection.set_color(color)
    lineCollection.set_linewidth(linewidth)
    axes.add_collection(lineCollection)

    updateAxes_(axes)
    return lineCollection
Beispiel #10
0
def drawSelectedMeshBoundariesShadow(axes, boundaries, first='x', second='y',
                                     color=(0.5, 0.5, 0.5, 1.0)):
    """
        What is this?
    """
    polys = []

    for cell in boundaries:
        polys.append(list(zip([getattr(cell.node(0), first)(),
                               getattr(cell.node(1), first)(),
                               getattr(cell.node(2), first)()],
                              [getattr(cell.node(0), second)(),
                               getattr(cell.node(1), second)(),
                               getattr(cell.node(2), second)()])))

    collection = mpl.collections.PolyCollection(polys, antialiaseds=True)

    collection.set_color(color)
    collection.set_edgecolor(color)
    collection.set_linewidth(0.2)
    axes.add_collection(collection)

    updateAxes_(axes)
    return collection
Beispiel #11
0
def patchMatrix(A, xmap=None, ymap=None, ax=None, cMin=None, cMax=None,
                logScale=None, label=None, dx=1, **kwargs):
    """ plot previously generated (generateVecMatrix) matrix

    Parameters
    ----------
    A : numpy.array2d
        matrix to show
    xmap : dict {i:num}
        dict (must match A.shape[0])
    ymap : iterable
        vector for x axis (must match A.shape[0])
    ax : mpl.axis
        axis to plot, if not given a new figure is created
    cMin/cMax : float
        minimum/maximum color values
    logScale : bool
        logarithmic colour scale [min(A)>0]
    label : string
        colorbar label
    """
    mat = np.ma.masked_where(A == 0.0, A, False)
    if cMin is None:
        cMin = np.min(mat)
    if cMax is None:
        cMax = np.max(mat)
    if logScale is None:
        logScale = (cMin > 0.0)
    if logScale:
        norm = LogNorm(vmin=cMin, vmax=cMax)
    else:
        norm = Normalize(vmin=cMin, vmax=cMax)
    if 'ax' is None:
        fig, ax = plt.subplots()

    iy, ix = np.nonzero(A)  # != 0)
    recs = []
    vals = []
    for i in range(len(ix)):
        recs.append(Rectangle((ix[i]-dx/2, iy[i]-0.5), dx, 1))
        vals.append(A[iy[i], ix[i]])

    pp = PatchCollection(recs)
    col = ax.add_collection(pp)
    pp.set_edgecolor(None)
    pp.set_linewidths(0.0)
    if 'cmap' in kwargs:
        pp.set_cmap(kwargs.pop('cmap'))
    pp.set_norm(norm)
    pp.set_array(np.array(vals))
    pp.set_clim(cMin, cMax)
    xval = [k for k in xmap.keys()]
    ax.set_xlim(min(xval)-dx/2, max(xval)+dx/2)
    ax.set_ylim(len(ymap)+0.5, -0.5)

    updateAxes_(ax)
    cbar = None
    if kwargs.pop('colorBar', True):
        cbar = pg.mplviewer.createColorbar(col, cMin=cMin, cMax=cMax, nLevs=5,
                                           label=label)
    return ax, cbar
Beispiel #12
0
def patchValMap(vals, xvec=None, yvec=None, ax=None, cMin=None, cMax=None,
                logScale=None, label=None, dx=1, dy=None, **kwargs):
    """ plot previously generated (generateVecMatrix) y map (category)

    Parameters
    ----------
    A : iterable
        to show
    xvec : dict {i:num}
        dict (must match A.shape[0])
    ymap : iterable
        vector for x axis (must match A.shape[0])
    ax : mpl.axis
        axis to plot, if not given a new figure is created
    cMin/cMax : float
        minimum/maximum color values
    logScale : bool
        logarithmic colour scale [min(A)>0]
    label : string
        colorbar label
    """
    if cMin is None:
        cMin = np.min(vals)
    if cMax is None:
        cMax = np.max(vals)
    if logScale is None:
        logScale = (cMin > 0.0)
    if logScale:
        norm = LogNorm(vmin=cMin, vmax=cMax)
    else:
        norm = Normalize(vmin=cMin, vmax=cMax)
    if 'ax' is None:
        fig, ax = plt.subplots()

    recs = []
    if dy is None:  # map y values to unique
        ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))}
        for i in range(len(vals)):
            recs.append(Rectangle((xvec[i]-dx/2, ymap[yvec[i]]-0.5), dx, 1))
    else:
        for i in range(len(vals)):
            recs.append(Rectangle((xvec[i]-dx/2, yvec[i]-dy/2), dx, dy))

    pp = PatchCollection(recs)
    col = ax.add_collection(pp)
    pp.set_edgecolor(None)
    pp.set_linewidths(0.0)
    if 'cmap' in kwargs:
        pp.set_cmap(kwargs.pop('cmap'))
    pp.set_norm(norm)
    pp.set_array(np.array(vals))
    pp.set_clim(cMin, cMax)
    ax.set_xlim(min(xvec)-dx/2, max(xvec)+dx/2)
    ax.set_ylim(len(ymap)-0.5, -0.5)

    updateAxes_(ax)
    cbar = None
    if kwargs.pop('colorBar', True):
        cbar = pg.mplviewer.createColorbar(col, cMin=cMin, cMax=cMax, nLevs=5,
                                           label=label)
    return ax, cbar, ymap
Beispiel #13
0
def drawPLC(axes, mesh, fillRegion=True, boundaryMarker=False, **kwargs):
    """
    Draw 2D PLC into the given axes.

    Parameters
    ----------

    fillRegion: bool [True]
        Fill the regions with default colormap.

    boundaryMarker: bool [False]
        show boundary marker

    **kwargs

    Examples
    --------
    """

    eCircles = []
    cols = []

    if fillRegion and mesh.boundaryCount() > 0:
        tmpMesh = pg.meshtools.createMesh(mesh, quality=20)
        if tmpMesh.cellCount() == 0:
            pass
        else:
            drawModel(axes=axes, mesh=tmpMesh, data=tmpMesh.cellMarkers(),
                    nLevs=len(pg.unique(pg.sort(tmpMesh.cellMarkers()))),
                    levels=pg.utils.unique(tmpMesh.cellMarkers()),
                    tri=True, alpha=0.5, linewidth=0.0, edgecolors='k',
                    snap=False)

    for n in mesh.nodes():
        col = (0.0, 0.0, 0.0)
        if n.marker() == pg.MARKER_NODE_SENSOR:
            col = (1.0, 0.0, 0.0)

#        eCircles.append(mpl.patches.Circle((n.pos()[0], n.pos()[1])))
        ms = kwargs.pop('markersize', 5)
        axes.plot(n.pos()[0], n.pos()[1], 'bo', markersize=ms,
                  color='black')
#        eCircles.append(mpl.patches.Circle((n.pos()[0], n.pos()[1]), 0.1))
        cols.append(col)

    if boundaryMarker:
        for b in mesh.boundaries():
            axes.text(b.center()[0], b.center()[1], str(b.marker()),
                      color='red', verticalalignment='center',
                      horizontalalignment='center')  # 'white'

    p = mpl.collections.PatchCollection(eCircles, color=cols)
    axes.add_collection(p)

    for reg in mesh.regionMarker():
        axes.text(reg[0], reg[1],
                  str(reg.marker()) + ": " + str(reg.area()),
                  color='black',
                  verticalalignment='center',
                  horizontalalignment='left'
                  )  # 'white'

    for hole in mesh.holeMarker():
        axes.text(hole[0], hole[1], 'H', color='black')

    updateAxes_(axes)
Beispiel #14
0
def drawModel(axes, mesh, data=None,
              cMin=None, cMax=None, logScale=True, cmap=None,
              alpha=1, xlabel=None, ylabel=None, verbose=False,
              **kwargs):
    """
    Draw a 2d mesh and color the cell by the data.

    Implement this with tripcolor  ..........!!!!!!!!

    Parameters
    ----------

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> import pygimli as pg
    >>> from pygimli.mplviewer import drawModel
    >>> n = np.linspace(0, -2, 11)
    >>> mesh = pg.createGrid(x=n, y=n)
    >>> mx = pg.x(mesh.cellCenter())
    >>> my = pg.y(mesh.cellCenter())
    >>> data = np.cos(1.5 * mx) * np.sin(1.5 * my)
    >>> fig, ax = plt.subplots()
    >>> drawModel(ax, mesh, data)
    <matplotlib.collections.PolyCollection object at ...>
    """
    if mesh.nodeCount() == 0:
        raise "drawModel: The mesh is empty."

    useTri = kwargs.pop('tri', False)

    if useTri:
        gci = drawMPLTri(axes, mesh, data, cmap=cmap,
                         **kwargs)

    else:

        gci = pg.mplviewer.createMeshPatches(axes, mesh, alpha=alpha,
                                             verbose=verbose, **kwargs)

        if cmap is not None:
            if cmap == 'b2r':
                gci.set_cmap(cmapFromName('b2r'))
            else:
                gci.set_cmap(cmap)

        axes.set_aspect('equal')

        gci.set_antialiased(True)
        gci.set_linewidth(None)

        if data is None:
            data = pg.RVector(mesh.cellCount())

        if len(data) != mesh.cellCount():
            
            print(data, mesh)
            print("INFO: drawModel have wrong data length .. "
                    " indexing data from cellMarker()")
            viewdata = data(mesh.cellMarker())
        else:
            viewdata = data

        if min(data) <= 0:
            logScale = False

        pg.mplviewer.setMappableData(gci, viewdata, cMin=cMin, cMax=cMax,
                                     logScale=logScale)

    if xlabel is not None:
        axes.set_xlabel(xlabel)
    if ylabel is not None:
        axes.set_ylabel(ylabel)

    updateAxes_(axes)
    return gci
Beispiel #15
0
def drawStreams(axes, mesh, data, startStream=3, **kwargs):
    """
    Draw streamlines based on an unstructured mesh.

    Every cell contains only one streamline and every new stream line
    starts in the center of a cell. Stream density can by chosen by
    parameter a leading to a new mesh with equidistant maximum cell size a.

    Parameters
    ----------

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> import pygimli as pg
    >>> from pygimli.mplviewer import drawStreams
    >>> n = np.linspace(1,2,10)
    >>> mesh = pg.createGrid(x=n, y=n)
    >>> nx = pg.x(mesh.positions())
    >>> ny = pg.y(mesh.positions())
    >>> data = np.cos(1.5 * nx) * np.sin(1.5 * ny)
    >>> fig, ax = plt.subplots()
    >>> drawStreams(ax, mesh, data)
    >>> ax.set_aspect('equal')
    """

    viewMesh = None
    dataMesh = None

    if 'coarseMesh' in kwargs:
        viewMesh = kwargs['coarseMesh']
        dataMesh = mesh
        dataMesh.createNeighbourInfos()
        del(kwargs['coarseMesh'])
    else:
        viewMesh = mesh

    viewMesh.createNeighbourInfos()

    for c in viewMesh.cells():
        c.setValid(True)

    if startStream == 1:
        # start a stream from each boundary cell
        for y in np.linspace(viewMesh.ymin(), viewMesh.ymax(), 100):
            c = viewMesh.findCell(
                [(viewMesh.xmax() - viewMesh.xmax()) / 2.0, y])
            if c is not None:
                if c.valid():
                    drawStreamLine_(axes, viewMesh, c, data, dataMesh,
                                    **kwargs)

    elif startStream == 2:
        # start a stream from each boundary cell
        for x in np.linspace(viewMesh.xmin(), viewMesh.xmax(), 100):
            c = viewMesh.findCell(
                [x, (viewMesh.ymax() - viewMesh.ymax()) / 2.0])
            if c is not None:
                if c.valid():
                    drawStreamLine_(axes, viewMesh, c, data, dataMesh,
                                    **kwargs)

    elif startStream == 3:
        # start a stream from each boundary cell
        for b in viewMesh.findBoundaryByMarker(1, 99):
            c = b.leftCell()
            if c is None:
                c = b.rightCell()

            if c.valid():
                drawStreamLine_(axes, viewMesh, c, data, dataMesh,
                                **kwargs)

    # start a stream from each unused cell
    for c in viewMesh.cells():
        if c.valid():
            drawStreamLine_(axes, viewMesh, c, data, dataMesh,
                            **kwargs)

    for c in viewMesh.cells():
        c.setValid(True)

    updateAxes_(axes)
Beispiel #16
0
def drawMeshBoundaries(axes, mesh, hideMesh=False, **kwargs):
    """
    Draw mesh on axes with boundary conditions colorized.

    Parameters
    ----------

    hideMesh: bool [False]
        Show only the boundary of the mesh and omit inner edges that
        separate the cells.

    **kwargs:
        fitView : bool [True]

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> import pygimli as pg
    >>> from pygimli.mplviewer import drawMeshBoundaries
    >>> n = np.linspace(0,-2,11)
    >>> mesh = pg.createGrid(x=n, y=n)
    >>> for bound in mesh.boundaries():
    ...     if not bound.rightCell():
    ...         bound.setMarker(pg.MARKER_BOUND_MIXED)
    ...     if bound.center().y() == 0:
    ...         bound.setMarker(pg.MARKER_BOUND_HOMOGEN_NEUMANN)
    >>> fig, ax = plt.subplots()
    >>> drawMeshBoundaries(ax, mesh)
    """
    if not mesh:
        raise Exception("drawMeshBoundaries(axes, mesh): invalid mesh")

    if not mesh.dimension() == 2:
        raise Exception("No 2d mesh: dim = ", mesh.dimension())

    if mesh.nodeCount() < 2:
        raise Exception("drawMeshBoundaries(axes, mesh): to few nodes",
                        mesh.nodeCount())

    if kwargs.pop('fitView', True):
        axes.set_xlim(mesh.xmin() - 0.05, mesh.xmax() + 0.05)
        axes.set_ylim(mesh.ymin() - 0.05, mesh.ymax() + 0.05)

#    drawAA = True
#    swatch = pg.Stopwatch(True)
    mesh.createNeighbourInfos()

    if not hideMesh:
        drawSelectedMeshBoundaries(axes, mesh.findBoundaryByMarker(0),
                                   color=(0.0, 0.0, 0.0, 1.0), linewidth=0.3)

    drawSelectedMeshBoundaries(axes, mesh.findBoundaryByMarker(
                               pg.MARKER_BOUND_HOMOGEN_NEUMANN),
                               color=(0.0, 1.0, 0.0, 1.0), linewidth=1.0)
    drawSelectedMeshBoundaries(axes, mesh.findBoundaryByMarker(
                               pg.MARKER_BOUND_MIXED),
                               color=(1.0, 0.0, 0.0, 1.0), linewidth=1.0)
    b0 = [b for b in mesh.boundaries() if b.marker() > 0]
    drawSelectedMeshBoundaries(axes, b0, color=(0.0, 0.0, 0.0, 1.0),
                               linewidth=1.5)
    b4 = [b for b in mesh.boundaries() if b.marker() < -4]
    drawSelectedMeshBoundaries(axes, b4, color=(0.0, 0.0, 0.0, 1.0),
                               linewidth=1.5)

    if mesh.cellCount() == 0:
        drawPLC(axes, mesh, **kwargs)

    updateAxes_(axes)
Beispiel #17
0
def drawMeshBoundaries(axes, mesh, hideMesh=False, **kwargs):
    """
    Draw mesh on axes with boundary conditions colorized.

    Parameters
    ----------

    **kwargs:
        fitView : bool [True]

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> import pygimli as pg
    >>> from pygimli.mplviewer import drawMeshBoundaries
    >>> n = np.linspace(0,-2,11)
    >>> mesh = pg.createGrid(x=n, y=n)
    >>> for bound in mesh.boundaries():
    ...     if not bound.rightCell():
    ...         bound.setMarker(pg.MARKER_BOUND_MIXED)
    ...     if bound.center().y() == 0:
    ...         bound.setMarker(pg.MARKER_BOUND_HOMOGEN_NEUMANN)
    >>> fig, ax = plt.subplots()
    >>> drawMeshBoundaries(ax, mesh)
    """
    if not mesh:
        raise Exception("drawMeshBoundaries(axes, mesh): invalid mesh")

    if not mesh.dimension() == 2:
        raise Exception("No 2d mesh: dim = ", mesh.dimension())

    if mesh.nodeCount() < 2:
        raise Exception("drawMeshBoundaries(axes, mesh): to few nodes",
                        mesh.nodeCount())

    if kwargs.pop('fitView', True):
        axes.set_xlim(mesh.xmin() - 0.05, mesh.xmax() + 0.05)
        axes.set_ylim(mesh.ymin() - 0.05, mesh.ymax() + 0.05)

#    drawAA = True
#    swatch = pg.Stopwatch(True)
    mesh.createNeighbourInfos()

    if not hideMesh:
        drawSelectedMeshBoundaries(axes, mesh.findBoundaryByMarker(0),
                                   color=(0.0, 0.0, 0.0, 1.0), linewidth=0.3)

    drawSelectedMeshBoundaries(axes, mesh.findBoundaryByMarker(
                               pg.MARKER_BOUND_HOMOGEN_NEUMANN),
                               color=(0.0, 1.0, 0.0, 1.0), linewidth=1.0)
    drawSelectedMeshBoundaries(axes, mesh.findBoundaryByMarker(
                               pg.MARKER_BOUND_MIXED),
                               color=(1.0, 0.0, 0.0, 1.0), linewidth=1.0)
    b0 = [b for b in mesh.boundaries() if b.marker() > 0]
    drawSelectedMeshBoundaries(axes, b0, color=(0.0, 0.0, 0.0, 1.0),
                               linewidth=1.5)
    b4 = [b for b in mesh.boundaries() if b.marker() < -4]
    drawSelectedMeshBoundaries(axes, b4, color=(0.0, 0.0, 0.0, 1.0),
                               linewidth=1.5)

    if mesh.cellCount() == 0:
        eCircles = []
        cols = []
        for n in mesh.nodes():
            col = (0.0, 0.0, 0.0)
            if n.marker() == pg.MARKER_NODE_SENSOR:
                col = (1.0, 0.0, 0.0)
            #eCircles.append(mpl.patches.Circle((n.pos()[0], n.pos()[1])))
            axes.plot(n.pos()[0], n.pos()[1], 'bo', markersize=5, color='black')
            #eCircles.append(mpl.patches.Circle((n.pos()[0], n.pos()[1]), 0.1))
            cols.append(col)
        p = mpl.collections.PatchCollection(eCircles, color=cols)
        axes.add_collection(p)

        for reg in mesh.regionMarker():
            axes.text(reg[0], reg[1],
                      str(reg.marker()) + ": " + str(reg.area()),
                      color='black')  # 'white'

        for hole in mesh.holeMarker():
            axes.text(hole[0], hole[1], 'H', color='black')
            
    updateAxes_(axes)