コード例 #1
0
ファイル: meshview.py プロジェクト: dongxu-cug/gimli
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
コード例 #2
0
ファイル: mapping.py プロジェクト: rdzotz/gimli
def cellDataToNodeData(mesh, data, style='mean'):
    """Convert cell data to node data.

    Convert cell data to node data via non-weighted averaging (mean) of common
    cell data.

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

    data : iterable [float]
        Data of len mesh.cellCount().
        TODO complex, R3Vector, ndarray

    style : str ['mean']
        Interpolation style.
        * 'mean' : non-weighted averaging
        TODO harmonic averaging
        TODO weighted averaging (mean, harmonic)
        TODO interpolation via cell centered mesh

    Examples
    --------
    >>> import pygimli as pg
    >>> grid = pg.createGrid(x=(1,2,3),y=(1,2,3))
    >>> celldata = np.array([1, 2, 3, 4])
    >>> nodedata = pg.meshtools.cellDataToNodeData(grid, celldata)
    >>> print(nodedata.array())
    [1.  1.5 2.  2.  2.5 3.  3.  3.5 4. ]
    """
    if len(data) != mesh.cellCount():
        raise BaseException(
            "Dimension mismatch, expecting cellCount(): " +
            str(mesh.cellCount()) + "got: " + str(len(data)),
            str(len(data[0])))

    if style == 'mean':

        if np.ndim(data) == 1:
            return pg.cellDataToPointData(mesh, data)

        if mesh.dim() == 1:
            return pg.cellDataToPointData(mesh, data)
        elif mesh.dim() == 2:
            return np.array([
                pg.cellDataToPointData(mesh, data[:, 0]),
                pg.cellDataToPointData(mesh, data[:, 1])
            ]).T
        elif mesh.dim() == 3:
            return np.array([
                pg.cellDataToPointData(mesh, data[0]),
                pg.cellDataToPointData(mesh, data[1]),
                pg.cellDataToPointData(mesh, data[2])
            ])
    else:
        raise BaseException("Style '" + style + "'not yet implemented."
                            "Currently styles available are: 'mean, '")
コード例 #3
0
ファイル: mapping.py プロジェクト: Spencerx/gimli
def cellDataToNodeData(mesh, data, style='mean'):
    """Convert cell data to node data.

    Convert cell data to node data via non-weighted averaging (mean) of common
    cell data.

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

    data : iterable [float]
        Data of len mesh.nodeCount().
        TODO complex, R3Vector, ndarray

    style : str ['mean']
        Interpolation style.
        * 'mean' : non-weighted averaging
        TODO harmonic averaging
        TODO weighted averaging (mean, harmonic)
        TODO interpolation via cell centered mesh

    Examples
    --------
    """
    if len(data) != mesh.cellCount():
        raise BaseException(
            "Dimension mismatch, expecting cellCount(): " +
            str(mesh.cellCount()) + "got: " + str(len(data)),
            str(len(data[0])))

    if style == 'mean':

        if isinstance(data, pg.RVector):
            print(pg.cellDataToPointData(mesh, data))
            return pg.cellDataToPointData(mesh, data)

        if mesh.dim() == 1:
            return pg.cellDataToPointData(mesh, data)
        elif mesh.dim() == 2:
            return np.array([
                pg.cellDataToPointData(mesh, data[:, 0]),
                pg.cellDataToPointData(mesh, data[:, 1])
            ]).T
        elif mesh.dim() == 3:
            return np.array([
                pg.cellDataToPointData(mesh, data[0]),
                pg.cellDataToPointData(mesh, data[1]),
                pg.cellDataToPointData(mesh, data[2])
            ])
    else:
        raise BaseException("Style '" + style + "'not yet implemented."
                            "Currently styles available are: 'mean, '")
コード例 #4
0
def linear_interpolation(inmesh, indata, outmesh):
    """ Linear interpolation using `pg.interpolate()` """
    outdata = pg.RVector()  # empty
    pg.interpolate(srcMesh=inmesh,
                   inVec=indata,
                   destPos=outmesh.cellCenters(),
                   outVec=outdata)

    # alternatively you can use the interpolation matrix
    outdata = inmesh.interpolationMatrix(outmesh.cellCenters()) * \
              pg.cellDataToPointData(inmesh, indata)
    return outdata
コード例 #5
0
ファイル: solverFVM.py プロジェクト: frodo4fingers/gimli
def cellDataToCellGrad2(mesh, v):
    if len(v) != mesh.cellCount():
        raise

    vN = pg.cellDataToPointData(mesh, v)
    gC = np.zeros((mesh.cellCount(), 3))

    for c in mesh.cells():
        gr = c.grad(c.center(), vN)
        gC[c.id(), 0] = gr[0]
        gC[c.id(), 1] = gr[1]
        gC[c.id(), 2] = gr[2]
    return gC
コード例 #6
0
def cellDataToCellGrad2(mesh, v):
    if len(v) != mesh.cellCount():
        raise

    vN = pg.cellDataToPointData(mesh, v)
    gC = np.zeros((mesh.cellCount(), 3))

    for c in mesh.cells():
        gr = c.grad(c.center(), vN)
        gC[c.id(), 0] = gr[0]
        gC[c.id(), 1] = gr[1]
        gC[c.id(), 2] = gr[2]
    return gC
コード例 #7
0
ファイル: mapping.py プロジェクト: gimli-org/gimli
def cellDataToNodeData(mesh, data, style='mean'):
    """Convert cell data to node data.

    Convert cell data to node data via non-weighted averaging (mean) of common
    cell data.

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

    data : iterable [float]
        Data of len mesh.cellCount().
        TODO complex, R3Vector, ndarray

    style : str ['mean']
        Interpolation style.
        * 'mean' : non-weighted averaging
        TODO harmonic averaging
        TODO weighted averaging (mean, harmonic)
        TODO interpolation via cell centered mesh

    Examples
    --------
    >>> import pygimli as pg
    >>> grid = pg.createGrid(x=(1,2,3),y=(1,2,3))
    >>> celldata = np.array([1, 2, 3, 4])
    >>> nodedata = pg.meshtools.cellDataToNodeData(grid, celldata)
    >>> print(nodedata.array())
    [1.  1.5 2.  2.  2.5 3.  3.  3.5 4. ]
    """
    if len(data) != mesh.cellCount():
        raise BaseException("Dimension mismatch, expecting cellCount(): " +
                            str(mesh.cellCount()) +
                            "got: " + str(len(data)), str(len(data[0])))

    if style == 'mean':

        if np.ndim(data) == 1:
            return pg.cellDataToPointData(mesh, data)

        if mesh.dim() == 1:
            return pg.cellDataToPointData(mesh, data)
        elif mesh.dim() == 2:
            return np.array([pg.cellDataToPointData(mesh, data[:, 0]),
                             pg.cellDataToPointData(mesh, data[:, 1])]).T
        elif mesh.dim() == 3:
            return np.array([pg.cellDataToPointData(mesh, data[0]),
                            pg.cellDataToPointData(mesh, data[1]),
                            pg.cellDataToPointData(mesh, data[2])])
    else:
        raise BaseException("Style '" + style + "'not yet implemented."
                            "Currently styles available are: 'mean, '")
コード例 #8
0
ファイル: solver.py プロジェクト: dongxu-cug/gimli
def cellDataToPointData(mesh, vec):
    """
        DOCUMENT_ME
    """
    if len(vec) != mesh.cellCount():
        raise BaseException("Dimension mismatch, expecting cellCount(): " 
                            + str(mesh.cellCount()) 
                            + "got: " + str(len(vec)), str(len(vec[0])))
    
    if mesh.dim() == 1:
        return pg.cellDataToPointData(mesh, vec[0])
    elif mesh.dim() == 2:
        return np.array([pg.cellDataToPointData(mesh, vec[:,0]),
                         pg.cellDataToPointData(mesh, vec[:,1])])
    elif mesh.dim() == 3:
        return np.array([pg.cellDataToPointData(mesh, vec[0]),
                         pg.cellDataToPointData(mesh, vec[1]),
                         pg.cellDataToPointData(mesh, vec[2])])
コード例 #9
0
    
    setAboveWT = 1
    setValue = 0.3
    if setAboveWT == 1:
        for c in mesh.cells():
            if c.center()[1] > 0:
                dataVec[c.id()] = setValue
    
    checkZeros = 1
    if checkZeros == 1:
        if 'MINIT' in data:
            dataVec[dataVec == 0] = 0.0001
        if 'COND' in data:
            dataVec[dataVec < min(data['COND'])] = np.mean(data['COND'])
    
    nData = pg.cellDataToPointData(bPolyMesh, dataVec)

    fig, ax = plt.subplots()
    plt.rc('font', family='Arial', size = 12)
    
    if 'MINIT' in data.columns:
        print('Plotting Mass Concentration data...')
        _ , cbar = pg.show(mesh, dataVec, label="Mass Concentration [mg/l]", cMap=ccmap, cMin=360, cMax=36000, extend="both", logScale=True, colorbar = True, ax = ax)
        pg.mplviewer.drawField(ax, mesh, nData, levels = [500,1000,10000, 20000, 35000], cMin = min(nData), cMax = np.floor(max(nData)), fillContour=False, logScale = True, colors=['black'], linewidths=0.2, alpha=1)
        plt.sca(plt.gcf().get_axes()[0])
        cbar.ax.xaxis.set_ticklabels(np.ceil(cbar.get_ticks()).astype(int))
    
    elif 'COND' in data.columns:
        print('Plotting Hydraulic Conductivity data...')
        _, cb = pg.show(mesh, dataVec, label="Hydrualic Conductivity (m/d)",
                         cMap=cmap,  colorBar=True, cMin=None, cMax=None,
コード例 #10
0
ファイル: unsorted.py プロジェクト: torvalds2010/gimli
def streamlineDir(mesh,
                  field,
                  startCoord,
                  dLengthSteps,
                  dataMesh=None,
                  maxSteps=1000,
                  down=True,
                  verbose=False,
                  coords=(0, 1)):
    """
        down = -1, up = 1, both = 0
    """
    xd = []
    yd = []
    vd = []
    counter = 0

    pot = None
    vx = None
    vy = None
    isVectorData = False

    if isinstance(field, pg.R3Vector):
        field = field.array()

    if hasattr(field[0], '__len__'):
        if min(field[:, 0]) == max(field[:, 0]) and \
           min(field[:, 1]) == max(field[:, 1]):
            raise BaseException("No data range streamline: min/max == ",
                                min(field[:, 0]))
        vx = pg.RVector(field[:, 0])
        vy = pg.RVector(field[:, 1])

        isVectorData = True
    else:
        if min(field) == max(field):
            raise BaseException("No data range for streamline: min/max == ",
                                min(field))

        if dataMesh is not None:
            if len(field) == dataMesh.nodeCount():
                pot = pg.RVector(field)
            elif len(field) == dataMesh.cellCount():
                pot = pg.cellDataToPointData(dataMesh, field)
            else:
                raise BaseException(
                    "Data length (%i) for streamline is "
                    "neighter nodeCount (%i) nor cellCount (%i)" %
                    (len(field), dataMesh.nodeCount(), dataMesh.nodeCount()))
        else:
            if len(field) == mesh.nodeCount():
                pot = pg.RVector(field)
            elif len(field) == mesh.cellCount():
                pot = pg.cellDataToPointData(mesh, field)
            else:
                raise BaseException(
                    "Data length (%i) for streamline is "
                    "neighter nodeCount (%i) nor cellCount (%i)" %
                    (len(field), mesh.nodeCount(), mesh.nodeCount()))

    direction = 1
    if down:
        direction = -1

    # search downward
    pos = pg.RVector3(startCoord)
    c = mesh.findCell(startCoord)
    dLength = c.center().dist(c.node(0).pos()) / dLengthSteps

    # stream line starting point
    if c is not None:
        xd.append(pos[coords[0]])
        yd.append(pos[coords[1]])
        vd.append(-1)

    lastC = c
    lastU = -direction * 1e99

    d = None
    while c is not None and len(xd) < maxSteps:

        # valid .. temporary check if there is already a stream within the cell
        if not c.valid():
            break

        if isVectorData:
            u = 0.
            if len(vx) == mesh.cellCount():
                d = pg.RVector3(vx[c.id()], vy[c.id()])
            elif len(vx) == mesh.nodeCount():
                d = pg.RVector3(c.pot(pos, vx), c.pot(pos, vy))
            elif dataMesh:
                cd = dataMesh.findCell(pos)
                if cd is None:
                    raise BaseException("Cannot find " + str(pos) +
                                        " dataMesh")
                if len(vx) == dataMesh.cellCount():
                    d = pg.RVector3(vx[cd.id()], vy[cd.id()])
                elif len(vx) == dataMesh.nodeCount() and \
                    len(vy) == dataMesh.nodeCount():
                    d = pg.RVector3(cd.pot(pos, vx), cd.pot(pos, vy))
                else:
                    print(dataMesh)
                    print(len(vx), len(vy))
                    raise BaseException("data size wrong")
            else:
                raise Exception
        else:
            if dataMesh:
                cd = dataMesh.findCell(pos)
                if not cd:
                    break

                d = cd.grad(pos, pot)
                u = cd.pot(pos, pot)
            else:
                d = c.grad(pos, pot)
                u = c.pot(pos, pot)
        # print "cell:", c.id(), u
        # always go u down
        dAbs = d.length()
        if dAbs == 0.0:
            print(
                d,
                "check this in streamlineDir(",
            )
            break

        if down:
            if u > lastU:
                break
        else:
            if u < lastU:
                break

        # * min(1.0, ((startCoord - pos).length()))
        pos += direction * d / dAbs * dLength
        c = mesh.findCell(pos, False)

        # Change cell here .. set old cell to be processed
        if c is not None:

            xd.append(pos[coords[0]])
            yd.append(pos[coords[1]])
            # set the stating value here
            if vd[0] == -1:
                vd[0] = dAbs
            vd.append(dAbs)

            # If the new cell is different from the current we move into the
            # new cell and make the last to be invalid ..
            # the last active contains a stream element
            if c.id() != lastC.id():
                lastC.setValid(False)
                lastC = c
                dLength = c.center().dist(c.node(0).pos()) / dLengthSteps
        else:
            # There is no new cell .. the last active contains a stream element
            lastC.setValid(False)

        lastU = u
        if verbose:
            print(pos, u)

    # Stream line has stopped and the current cell (if there is one) ..
    # .. contains a stream element
    if c is not None:

        c.setValid(False)

    if down:
        xd.reverse(), yd.reverse(), vd.reverse()

    return xd, yd, vd
コード例 #11
0
ファイル: showmesh.py プロジェクト: zhangwise/gimli
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
コード例 #12
0
    vel, pre, pCNorm, divVNorm = solveStokes_NEEDNAME(mesh, velBoundary, preBoundary,
                                            viscosity=a,
                                            pre0=pre,
                                            vel0=vel,
                                            maxIter=maxIter,
                                            tol=1e-2,
                                            verbose=1)
    print(" Time: ", swatch.duration(True))
    
   

print("OverallTime:", swatchG.duration(True))
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
plt.ion()
ax, cbar = show(mesh, data=pg.cellDataToPointData(mesh, np.sqrt(vel[:,0]*vel[:,0] +vel[:,1]*vel[:,1])),
     logScale=False, colorBar=True, axes=ax1, cbar='b2r')
cbar.ax.set_xlabel('Geschwindigkeit in m$/$s')
     
meshC, velBoundary, preBoundary, a, maxIter = modelCavity2(0.001, False)

show(mesh, data=vel, coarseMesh=meshC, axes=ax1)
#show(mesh, data=vel, axes=ax1)

show(meshC, axes=ax1)
#show(mesh, axes=ax1)
        
plt.figure()
plt.semilogy(pCNorm, label='norm')
plt.semilogy(divVNorm, label='norm')
plt.legend()
コード例 #13
0
ファイル: divergenceTest.py プロジェクト: jchavezolalla/gimli
    div = pg.RVector(mesh.cellCount())

    for c in mesh.cells():
        div[c.id()] = divergenceCell(c, F)

    return div


grid = pg.createGrid(x=np.arange(3. + 1), y=np.arange(2. + 1))
pot = np.arange(3. * 2)
print(grid, pot)

plt.ion()
show(grid, pot)

pN = pg.cellDataToPointData(grid, pot)

ax, cbar = show(grid, pN)
ax, cbar = show(grid, axes=ax)

vF = np.zeros((grid.boundaryCount(), 2))
cellGrad = cellDataToCellGrad(grid, pot)
print(cellGrad)
cellGrad = cellDataToCellGrad2(grid, pot)
print(cellGrad)

boundGrad = cellDataToBoundaryGrad(grid, pot)
boundGrad2 = cellDataToBoundaryGrad(grid, pot, 1)

for c in grid.cells():
    gr = cellGrad[c.id()]
コード例 #14
0
ファイル: solverFVM.py プロジェクト: frodo4fingers/gimli
    vel, pres, pCNorm, divVNorm = solveStokes_NEEDNAME(
            grid, velBoundary, preBoundary, viscosity=a, maxIter=maxIter,
            verbose=1)

    print("time", len(pCNorm), swatch.duration(True))
    referencesolution = 1.2889506342694153
    referencesolutionDivV = 0.029187181920161752
    print("divNorm: ", divVNorm[-1])
    print("to reference: ", divVNorm[-1]-referencesolutionDivV)

    fig = plt.figure()
    ax1 = fig.add_subplot(1, 3, 1)
    ax2 = fig.add_subplot(1, 3, 2)
    ax3 = fig.add_subplot(1, 3, 3)

    show(grid, data=pg.cellDataToPointData(grid, pres),
         logScale=False, showLater=True, colorBar=True, axes=ax1, cbar='b2r')
    show(grid, data=pg.logTransDropTol(pg.cellDataToPointData(grid, vel[:, 0]),
                                       1e-2),
         logScale=False, showLater=True, colorBar=True, axes=ax2)
    show(grid, data=pg.logTransDropTol(pg.cellDataToPointData(grid, vel[:, 1]),
                                       1e-2),
         logScale=False, showLater=True, colorBar=True, axes=ax3)

    show(grid, data=vel, axes=ax1)
    show(grid, showLater=True, axes=ax1)

    plt.figure()
    plt.semilogy(pCNorm, label='norm')
    plt.legend()
コード例 #15
0
ファイル: unsorted.py プロジェクト: gimli-org/gimli
def streamlineDir(mesh, field, startCoord, dLengthSteps, dataMesh=None,
                  maxSteps=1000, down=True, verbose=False, coords=(0, 1)):
    """
        down = -1, up = 1, both = 0
    """
    xd = []
    yd = []
    vd = []
    counter = 0

    pot = None
    vx = None
    vy = None
    isVectorData = False

    if isinstance(field, pg.R3Vector):
        field = field.array()

    if hasattr(field[0], '__len__'):
        if min(field[:, 0]) == max(field[:, 0]) and \
           min(field[:, 1]) == max(field[:, 1]):
            raise BaseException("No data range streamline: min/max == ",
                                min(field[:, 0]))
        vx = pg.RVector(field[:, 0])
        vy = pg.RVector(field[:, 1])

        isVectorData = True
    else:
        if min(field) == max(field):
            raise BaseException("No data range for streamline: min/max == ",
                                min(field))

        if dataMesh is not None:
            if len(field) == dataMesh.nodeCount():
                pot = pg.RVector(field)
            elif len(field) == dataMesh.cellCount():
                pot = pg.cellDataToPointData(dataMesh, field)
            else:
                raise BaseException(
                    "Data length (%i) for streamline is "
                    "neighter nodeCount (%i) nor cellCount (%i)" %
                    (len(field), dataMesh.nodeCount(), dataMesh.nodeCount()))
        else:
            if len(field) == mesh.nodeCount():
                pot = pg.RVector(field)
            elif len(field) == mesh.cellCount():
                pot = pg.cellDataToPointData(mesh, field)
            else:
                raise BaseException(
                    "Data length (%i) for streamline is "
                    "neighter nodeCount (%i) nor cellCount (%i)" %
                    (len(field), mesh.nodeCount(), mesh.nodeCount()))

    direction = 1
    if down:
        direction = -1

    # search downward
    pos = pg.RVector3(startCoord)
    c = mesh.findCell(startCoord)
    dLength = c.center().dist(c.node(0).pos()) / dLengthSteps

    # stream line starting point
    if c is not None:
        xd.append(pos[coords[0]])
        yd.append(pos[coords[1]])
        vd.append(-1)

    lastC = c
    lastU = -direction * 1e99

    d = None
    while c is not None and len(xd) < maxSteps:

        # valid .. temporary check if there is already a stream within the cell
        if not c.valid():
            break

        if isVectorData:
            u = 0.
            if len(vx) == mesh.cellCount():
                d = pg.RVector3(vx[c.id()], vy[c.id()])
            elif len(vx) == mesh.nodeCount():
                d = pg.RVector3(c.pot(pos, vx), c.pot(pos, vy))
            elif dataMesh:
                cd = dataMesh.findCell(pos)
                if cd is None:
                    raise BaseException("Cannot find " + str(pos) +
                                        " dataMesh")
                if len(vx) == dataMesh.cellCount():
                    d = pg.RVector3(vx[cd.id()], vy[cd.id()])
                elif len(vx) == dataMesh.nodeCount() and \
                    len(vy) == dataMesh.nodeCount():
                    d = pg.RVector3(cd.pot(pos, vx), cd.pot(pos, vy))
                else:
                    print(dataMesh)
                    print(len(vx), len(vy))
                    raise BaseException("data size wrong")
            else:
                raise Exception
        else:
            if dataMesh:
                cd = dataMesh.findCell(pos)
                if not cd:
                    break

                d = cd.grad(pos, pot)
                u = cd.pot(pos, pot)
            else:
                d = c.grad(pos, pot)
                u = c.pot(pos, pot)
        # print "cell:", c.id(), u
        # always go u down
        dAbs = d.length()
        if dAbs == 0.0:
            print(d,
                  "check this in streamlineDir(",)
            break

        if down:
            if u > lastU:
                break
        else:
            if u < lastU:
                break

        # * min(1.0, ((startCoord - pos).length()))
        pos += direction * d / dAbs * dLength
        c = mesh.findCell(pos, False)

        # Change cell here .. set old cell to be processed
        if c is not None:

            xd.append(pos[coords[0]])
            yd.append(pos[coords[1]])
            # set the stating value here
            if vd[0] == -1:
                vd[0] = dAbs
            vd.append(dAbs)

            # If the new cell is different from the current we move into the
            # new cell and make the last to be invalid ..
            # the last active contains a stream element
            if c.id() != lastC.id():
                lastC.setValid(False)
                lastC = c
                dLength = c.center().dist(c.node(0).pos()) / dLengthSteps
        else:
            # There is no new cell .. the last active contains a stream element
            lastC.setValid(False)

        lastU = u
        if verbose:
            print(pos, u)

    # Stream line has stopped and the current cell (if there is one) ..
    # .. contains a stream element
    if c is not None:

        c.setValid(False)

    if down:
        xd.reverse(), yd.reverse(), vd.reverse()

    return xd, yd, vd
コード例 #16
0
def divergence(mesh, F):
    div = pg.RVector(mesh.cellCount())

    for c in mesh.cells():
        div[c.id()] = divergenceCell(c, F)

    return div

grid = pg.createGrid(x=np.arange(3. + 1), y=np.arange(2. + 1))
pot = np.arange(3. * 2)
print(grid, pot)

plt.ion()
show(grid, pot)

pN = pg.cellDataToPointData(grid, pot)

ax, cbar = show(grid, pN)
ax, cbar = show(grid, axes=ax)

vF = np.zeros((grid.boundaryCount(), 2))
cellGrad = cellDataToCellGrad(grid, pot)
print(cellGrad)
cellGrad = cellDataToCellGrad2(grid, pot)
print(cellGrad)

boundGrad = cellDataToBoundaryGrad(grid, pot)
boundGrad2 = cellDataToBoundaryGrad(grid, pot, 1)

for c in grid.cells():
    gr = cellGrad[c.id()]
コード例 #17
0
                                                       preBoundary=preBoundary,
                                                       pre0=pre,
                                                       vel0=vel,
                                                       maxIter=maxIter,
                                                       tol=1e-2,
                                                       verbose=1)
    print(" Time: ", swatch.duration(True))
    
   

print("OverallTime:", swatchG.duration(True))

fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax, cbar = pg.show(mesh, 
                   data=pg.cellDataToPointData(mesh, pre),
                   logScale=False, colorBar=True, axes=ax1)
cbar.ax.set_xlabel('Pressure in ??')
meshC, velBoundary, preBoundary, a, maxIter = modelBuilder(0.01)
pg.show(mesh, data=vel, coarseMesh=meshC, axes=ax1)
pg.show(mesh, axes=ax1)

ax2 = fig.add_subplot(1, 2, 2)
ax, cbar = pg.show(mesh, 
                   data=pg.cellDataToPointData(mesh,
                                    np.sqrt(vel[:,0]*vel[:,0] +vel[:,1]*vel[:,1])),
                   logScale=False, colorBar=True, axes=ax2)
cbar.ax.set_xlabel('Geschwindigkeit in m$/$s')
pg.show(mesh, data=vel, coarseMesh=meshC, axes=ax2)
pg.show(mesh, axes=ax2)
コード例 #18
0
                                              velBoundary, preBoundary,
                                              maxIter=maxIter,
                                              verbose=1)

    print("time", len(pCNorm), swatch.duration(True))
    referencesolution = 1.2889506342694153
    referencesolutionDivV = 0.029187181920161752
    print("divNorm: ", divVNorm[-1])
    print("to reference: ", divVNorm[-1] - referencesolutionDivV)

    fig = plt.figure()
    ax1 = fig.add_subplot(1, 3, 1)
    ax2 = fig.add_subplot(1, 3, 2)
    ax3 = fig.add_subplot(1, 3, 3)

    show(grid, data=pg.cellDataToPointData(grid, pres),
         logScale=False, showLater=True, colorBar=True, axes=ax1, cbar='b2r')
    show(grid,
         data=pg.logTransDropTol(
             pg.cellDataToPointData(
                 grid, vel[
                     :, 0]), 1e-2),
         logScale=False, showLater=True, colorBar=True, axes=ax2)
    show(grid,
         data=pg.logTransDropTol(
             pg.cellDataToPointData(
                 grid, vel[
                     :, 1]), 1e-2),
         logScale=False, showLater=True, colorBar=True, axes=ax3)

    show(grid, data=vel, axes=ax1)
コード例 #19
0
                                                       viscosity=a,
                                                       velBoundary=velBoundary,
                                                       preBoundary=preBoundary,
                                                       pre0=pre,
                                                       vel0=vel,
                                                       maxIter=maxIter,
                                                       tol=1e-2,
                                                       verbose=1)
    print(" Time: ", swatch.duration(True))

print("OverallTime:", swatchG.duration(True))

fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax, cbar = pg.show(mesh,
                   data=pg.cellDataToPointData(mesh, pre),
                   logScale=False,
                   colorBar=True,
                   axes=ax1)
cbar.ax.set_xlabel('Pressure in ??')
meshC, velBoundary, preBoundary, a, maxIter = modelBuilder(0.01)
pg.show(mesh, data=vel, coarseMesh=meshC, axes=ax1)
pg.show(mesh, axes=ax1)

ax2 = fig.add_subplot(1, 2, 2)
ax, cbar = pg.show(mesh,
                   data=pg.cellDataToPointData(
                       mesh,
                       np.sqrt(vel[:, 0] * vel[:, 0] + vel[:, 1] * vel[:, 1])),
                   logScale=False,
                   colorBar=True,