Exemple #1
0
        def _testP1_(mesh, show=False, followP2=True):
            """ Laplace u = 0
                with u = x and u(x=min)=0 and u(x=max)=1
                Test for u == exact x for P1 base functions
            """
            #print('b', mesh, mesh.cell(0))
            u = pg.solve(mesh, a=1, b=0, f=0,
                         bc={'Dirichlet': {1: 0, 2: 1}})

            if show:
                if mesh.dim()==1:
                    pg.plt.figure()
                    x = pg.x(mesh)
                    ix = np.argsort(x)
                    pg.plt.plot(x[ix], u[ix])
                elif mesh.dim() > 1:
                    pg.show(mesh, u, label='u')

            xMin = mesh.xMin()
            xSpan = (mesh.xMax() - xMin)
            np.testing.assert_allclose(u, (pg.x(mesh)-xMin) / xSpan)

            if followP2:
                _testP2_(mesh, show)
            return u
Exemple #2
0
        def _testP2_(mesh, show=False):
            """ Laplace u - 2 = 0
                with u(x) = x² + x/(xMax-xMin) + xMin/(xMax-xMin)
                and u(xMin)=0 and u(xMax)=1
                Test for u_h === u(x) for P2 base functions
            """
            meshP2 = mesh.createP2()
            u = pg.solve(
                meshP2,
                f=-2,
                bc={'Dirichlet': {
                    '1,2': 2
                }},
            )

            xMin = mesh.xMin()
            xSpan = (mesh.xMax() - xMin)

            if show:
                if mesh.dim() == 1:
                    pg.plt.figure()
                    x = pg.x(mesh)
                    ix = np.argsort(x)
                    pg.plt.plot(x[ix], x[ix]**2 - (xSpan / 2)**2 + 2)
                elif mesh.dim() > 1:
                    pg.show(meshP2, u, label='u = x**2')

            np.testing.assert_allclose(u, pg.x(meshP2)**2 - (xSpan / 2)**2 + 2)
Exemple #3
0
    def test_Helmholtz(self):
        """
            d² u / d x² + k u + f = 0
            k = 2
            a) P1(exact)
                u = x
                f = -2x
            b) P2(exact)
                u = x*x
                f = -(2 + 2x*x)
        """
        h = np.pi/2 / 21
        x = np.arange(0.0, np.pi/2, h)
        mesh = pg.createGrid(x)

        ### test a)
        k = 2.0
        u = lambda _x: _x
        f = lambda _x: -(k * u(_x))

        x = pg.x(mesh)
        dirichletBC = [[1, u(min(x))], [2, u(max(x))]]
        uFEM = pg.solve(mesh, a=1, b=k, f=f(x), bc={'Dirichlet': dirichletBC})
        np.testing.assert_allclose(uFEM, u(x))

        ### test b)
        u = lambda _x: _x * _x
        f = lambda _x: -(2. + k *u(_x))

        mesh = mesh.createP2()
        x = pg.x(mesh)
        dirichletBC = [[1, u(min(x))], [2, u(max(x))]]
        uFEM = pg.solve(mesh, a=1, b=k, f=f(x), bc={'Dirichlet': dirichletBC})
        np.testing.assert_allclose(uFEM, u(x), atol=1e-6)
Exemple #4
0
    def test_Helmholtz(self):
        """
            d² u / d x² + k u + f = 0
            k = 2
            a) P1(exact)
                u = x
                f = -2x
            b) P2(exact)
                u = x*x
                f = -(2 + 2x*x)
        """
        h = np.pi / 2 / 21
        x = np.arange(0.0, np.pi / 2, h)
        mesh = pg.createGrid(x)

        ### test a)
        k = 2.0
        u = lambda _x: _x
        f = lambda _x: -(k * u(_x))

        x = pg.x(mesh)
        dirichletBC = [[1, u(min(x))], [2, u(max(x))]]
        uFEM = pg.solve(mesh, a=1, b=k, f=f(x), bc={'Dirichlet': dirichletBC})
        np.testing.assert_allclose(uFEM, u(x))

        ### test b)
        u = lambda _x: _x * _x
        f = lambda _x: -(2. + k * u(_x))

        mesh = mesh.createP2()
        x = pg.x(mesh)
        dirichletBC = [[1, u(min(x))], [2, u(max(x))]]
        uFEM = pg.solve(mesh, a=1, b=k, f=f(x), bc={'Dirichlet': dirichletBC})
        np.testing.assert_allclose(uFEM, u(x), atol=1e-6)
Exemple #5
0
def testShowVariants():
    # Create geometry definition for the modelling domain
    world = mt.createWorld(start=[-10, 0], end=[10, -16],
                        layers=[-8], worldMarker=False)

    # Create a heterogeneous block
    block = mt.createRectangle(start=[-6, -3.5], end=[6, -6.0],
                            marker=4,  boundaryMarker=10, area=0.1)

    circ = mt.createCircle(pos=[0, -11], radius=2, boundaryMarker=11, isHole=True)

    # Merge geometrical entities
    geom = world + block + circ
    mesh = mt.createMesh(geom)

    fig, axs = plt.subplots(3,5)

    pg.show(geom, ax=axs[0][0])
    axs[0][0].set_title('plc, (default)')
    pg.show(geom, fillRegion=False, ax=axs[0][1])
    axs[0][1].set_title('plc, fillRegion=False')
    pg.show(geom, showBoundary=False, ax=axs[0][2])
    axs[0][2].set_title('plc, showBoundary=False')
    pg.show(geom, markers=True, ax=axs[0][3])
    axs[0][3].set_title('plc, markers=True')
    pg.show(mesh, ax=axs[0][4], showBoundary=False)
    axs[0][4].set_title('mesh, showBoundary=False')

    pg.show(mesh, ax=axs[1][0])
    axs[1][0].set_title('mesh, (default)')
    pg.show(mesh, mesh.cellMarkers(), label='Cell markers', ax=axs[1][1])
    axs[1][1].set_title('mesh, cells, (default)')
    pg.show(mesh, markers=True, ax=axs[1][2])
    axs[1][2].set_title('mesh, cells, markers=True')
    pg.show(mesh, mesh.cellMarkers(), label='Cell markers', showMesh=True, ax=axs[1][3])
    axs[1][3].set_title('mesh, cells, showMesh=True')
    pg.show(mesh, mesh.cellMarkers(), label='Cell markers', showBoundary=False, ax=axs[1][4])
    axs[1][4].set_title('mesh, cells, showBoundary=False')

    pg.show(mesh, pg.x(mesh), label='Nodes (x)', ax=axs[2][0])
    axs[2][0].set_title('mesh, nodes, (default)')
    pg.show(mesh, pg.x(mesh), label='Nodes (x)', showMesh=True, ax=axs[2][1])
    axs[2][1].set_title('mesh, nodes, showMesh=True')
    pg.show(mesh, pg.x(mesh), label='Nodes (x)', showBoundary=True, ax=axs[2][2])
    axs[2][2].set_title('mesh, nodes, showBoundary=True')
    pg.show(mesh, pg.y(mesh.cellCenters()), label='Cell center (y)',
            tri=True, shading='flat', ax=axs[2][3])
    axs[2][3].set_title('mesh, cells, tri=True, shading=flat')
    pg.show(mesh, pg.y(mesh.cellCenters()), label='Cell center (y)',
            tri=True, shading='gouraud', ax=axs[2][4])
    axs[2][4].set_title('mesh, cells, tri=True, shading=gouraud')
    ##pg.show(mesh, mesh.cellMarker(), label(markers), axs[1][1])
    axs[2][4].figure.tight_layout()
Exemple #6
0
    def ani(i):
        axGra.clear()
        axGra.plot(pg.x(gravPoints), dz[i])
        axGra.plot(pg.x(gravPoints), pg.y(gravPoints), 'v', color='black')
        axGra.set_ylabel('Grav in mGal')
        axGra.set_xlim((-20, 20))
        axGra.set_ylim((0, 0.001))
        axGra.grid()

        pg.mplviewer.setMappableData(gciDDe, abs(dDens[i]),
                                     cMin=0, cMax=20,
                                     logScale=False)
Exemple #7
0
def drawVA(ax, data, vals=None, usePos=True, pseudosection=False, **kwargs):
    """Draw apparent velocities as matrix into an axis.

    Parameters
    ----------
    ax : mpl.Axes

    data : pg.DataContainer()
        Datacontainer with 's' and 'g' Sensorindieces and 't' traveltimes.

    usePos: bool [True]
        Use sensor positions for axes tick labels

    pseudosection : bool [False]
        Show in pseudosection style.

    vals : iterable
        Traveltimes, if None data need to contain 't' values.
    """
    if isinstance(vals, str):
        vals = data(vals)

    if vals is None:
        vals = data('t')

    px = pg.x(data)
    gx = np.asarray([px[g] for g in data.id("g")])
    sx = np.asarray([px[s] for s in data.id("s")])

    offset = shotReceiverDistances(data, full=True)

    if min(vals) < 1e-10:
        print(vals)
        pg.error('zero traveltimes found.')
    va = offset / vals

    if pseudosection:
        midpoint = (gx + sx) / 2
        gci = pg.viewer.mpl.dataview.drawVecMatrix(ax, midpoint, offset, va,
                                                   queeze=True,
                                                   label=pg.unit('as'))
    else:
        gci = pg.viewer.mpl.dataview.drawVecMatrix(ax, gx, sx, va,
                                                   squeeze=True,
                                                   label=pg.unit('as'))

    # A = np.ones((data.sensorCount(), data.sensorCount())) * np.nan
    # for i in range(data.size()):
    #     A[int(data('s')[i]), int(data('g')[i])] = va[i]
    # gci = ax.imshow(A, interpolation='nearest')
    # ax.grid(True)

    if usePos:
        xt = np.arange(0, data.sensorCount(), 50)
        ax.set_xticks(xt)
        ax.set_xticklabels([str(int(px[xti])) for xti in xt])
        ax.set_yticks(xt)
        ax.set_yticklabels([str(int(px[xti])) for xti in xt])

    return gci
Exemple #8
0
def create_mesh_and_data(n):
    nc = np.linspace(-2.0, 0.0, n)
    mesh = pg.createMesh2D(nc, nc)
    mcx = pg.x(mesh.cellCenter())
    mcy = pg.y(mesh.cellCenter())
    data = np.cos(1.5 * mcx) * np.sin(1.5 * mcy)
    return mesh, data
def cellDataToBoundaryGrad(mesh, v, vGrad):
    """TODO Documentme."""
    if len(v) != mesh.cellCount() or len(vGrad) != mesh.cellCount():
        raise BaseException("len(v) dismatch mesh.cellCount()")

    gB = mesh.cellDataToBoundaryGradient(v, vGrad)
    return np.vstack([pg.x(gB), pg.y(gB), pg.z(gB)]).T
Exemple #10
0
def drawFirstPicks(ax, data, tt=None, plotva=False, **kwargs):
    """Plot first arrivals as lines."""
    px = pg.x(data)
    gx = np.array([px[int(g)] for g in data("g")])
    sx = np.array([px[int(s)] for s in data("s")])
    if tt is None:
        tt = np.array(data("t"))
    if plotva:
        tt = np.absolute(gx - sx) / tt

    uns = np.unique(sx)

    cols = plt.cm.tab10(np.arange(10))
    kwargs.setdefault('marker', 'x')
    kwargs.setdefault('markersize', 8)
    kwargs.setdefault('linestyle', '-')
    for i, si in enumerate(uns):
        ti = tt[sx == si]
        gi = gx[sx == si]
        ii = gi.argsort()
        ax.plot(gi[ii], ti[ii], color=cols[i % 10], **kwargs)
        ax.plot(si, 0., 's', color=cols[i % 10])

    ax.grid(True)
    if plotva:
        ax.set_ylabel("Apparent velocity (m/s)")
    else:
        ax.set_ylabel("Traveltime (s)")

    ax.set_xlabel("x (m)")
    ax.invert_yaxis()
Exemple #11
0
def cellDataToCellGrad(mesh, v, CtB):
    """TODO Documentme."""
    if len(v) != mesh.cellCount():
        print(len(v), mesh.cellCount())
        raise BaseException("len of v missmatch mesh.cellCount()")
    div = mesh.boundaryDataToCellGradient(CtB * v)
    return np.vstack([pg.x(div), pg.y(div), pg.z(div)]).T
Exemple #12
0
def integrate(f, ent, order):
    """ integrate function """

    J = 0
    x = []
    w = []
    if type(ent) is list:

        a = ent[0]
        b = ent[1]
        xs = pg.IntegrationRules.instance().gauAbscissa(order)
        w = pg.IntegrationRules.instance().gauWeights(order)

        x = (b - a) / 2.0 * pg.x(xs) + (a + b) / 2.0
        J = (b - a) / 2.

    else:
        J = ent.shape().jacobianDeterminant()
        xs = pg.IntegrationRules.instance().abscissa(ent.shape(), order)
        w = pg.IntegrationRules.instance().weights(ent.shape(), order)

        x = [ent.shape().xyz(xsi) for xsi in xs]

    for xx in x:
        print xx
    print w
    print funct(f)(x)
    return J * sum(funct(f)(x) * w)
def cellDataToBoundaryGrad(mesh, v, vGrad):
    """
    """
    if len(v) != mesh.cellCount() or len(vGrad) != mesh.cellCount():
        raise
    gB = mesh.cellDataToBoundaryGradient(v, vGrad)
    return np.vstack([pg.x(gB), pg.y(gB), pg.z(gB)]).T

    gB = np.zeros((mesh.boundaryCount(), 3))

    for b in mesh.boundaries():
        leftCell = b.leftCell()
        rightCell = b.rightCell()
        gr = pg.RVector3(0.0, 0.0, 0.0)
        t = (b.node(1).pos() - b.node(0).pos()).norm()

        if leftCell and rightCell:
            df1 = b.center().distance(leftCell.center())
            df2 = b.center().distance(rightCell.center())

            gr = b.norm() * \
                (v[rightCell.id()] - v[leftCell.id()]) / (df1 + df2)

            grL = t * t.dot(vGrad[leftCell.id()])
            grR = t * t.dot(vGrad[rightCell.id()])

            gr += (grL + grR) * 0.5

        elif leftCell:
            gr = t * t.dot(vGrad[leftCell.id()])

        gB[b.id(), 0] = gr[0]
        gB[b.id(), 1] = gr[1]
        gB[b.id(), 2] = gr[2]
    return gB
Exemple #14
0
def shotReceiverDistances(data, full=False):
    """Return vector of all distances (in m) between shot and receiver.
    for each 's' and 'g' in data.

    Parameters
    ----------
    data : pg.DataContainerERT

    full : bool [False]
        Get distances between shot and receiver position when full is True or
        only form x coordinate if full is False

    Returns
    -------
    dists :  array
        Array of distances

    """
    if full:
        pos = data.sensors()
        s, g = data.id("s"), data.id("g")
        off = [pos[s[i]].distance(pos[g[i]]) for i in range(data.size())]
        return np.absolute(off)
    else:
        px = pg.x(data)
        gx = np.array([px[g] for g in data.id("g")])
        sx = np.array([px[s] for s in data.id("s")])
        return np.absolute(gx - sx)
Exemple #15
0
def cellDataToBoundaryGrad(mesh, v, vGrad):
    """
    """
    if len(v) != mesh.cellCount() or len(vGrad) != mesh.cellCount():
        raise
    gB = mesh.cellDataToBoundaryGradient(v, vGrad)
    return np.vstack([pg.x(gB), pg.y(gB), pg.z(gB)]).T

    gB = np.zeros((mesh.boundaryCount(), 3))

    for b in mesh.boundaries():
        leftCell = b.leftCell()
        rightCell = b.rightCell()
        gr = pg.RVector3(0.0, 0.0, 0.0)
        t = (b.node(1).pos() - b.node(0).pos()).norm()

        if leftCell and rightCell:
            df1 = b.center().distance(leftCell.center())
            df2 = b.center().distance(rightCell.center())

            gr = b.norm() * (v[rightCell.id()] - v[leftCell.id()]) / (df1 +
                                                                      df2)

            grL = t * t.dot(vGrad[leftCell.id()])
            grR = t * t.dot(vGrad[rightCell.id()])

            gr += (grL + grR) * 0.5

        elif leftCell:
            gr = t * t.dot(vGrad[leftCell.id()])

        gB[b.id(), 0] = gr[0]
        gB[b.id(), 1] = gr[1]
        gB[b.id(), 2] = gr[2]
    return gB
Exemple #16
0
def plotFirstPicks(ax, data, tt=None, plotva=False, marker='x-'):
    """plot first arrivals as lines"""
    px = pg.x(data.sensorPositions())
    gx = np.array([px[int(g)] for g in data("g")])
    sx = np.array([px[int(s)] for s in data("s")])
    if tt is None:
        tt = np.array(data("t"))
    if plotva:
        tt = np.absolute(gx - sx) / tt

    uns = np.unique(sx)

    cols = plt.cm.tab10(np.arange(10))

    for i, si in enumerate(uns):
        ti = tt[sx == si]
        gi = gx[sx == si]
        ii = gi.argsort()
        ax.plot(gi[ii], ti[ii], marker, color=cols[i % 10])
        ax.plot(si, 0., 's', color=cols[i % 10], markersize=8)

    ax.grid(True)
    if plotva:
        ax.set_ylabel("Apparent velocity (m/s)")
    else:
        ax.set_ylabel("Traveltime (s)")
    ax.set_xlabel("x (m)")
    ax.invert_yaxis()
Exemple #17
0
def cellDataToCellGrad(mesh, v, CtB):
    if len(v) != mesh.cellCount():
        print(len(v), mesh.cellCount())
        raise
    div = mesh.boundaryDataToCellGradient(CtB * v)
    return np.vstack([pg.x(div), pg.y(div), pg.z(div)]).T

    vF = cellDataToBoundaryData(mesh, v)
    gC = np.zeros((mesh.cellCount(), 3))

    for b in mesh.boundaries():
        leftCell = b.leftCell()
        rightCell = b.rightCell()
        vec = b.norm() * vF[b.id()] * b.size()

        if leftCell:
            gC[leftCell.id(), 0] += vec[0]
            gC[leftCell.id(), 1] += vec[1]
            gC[leftCell.id(), 2] += vec[2]
        if rightCell:
            gC[rightCell.id(), 0] -= vec[0]
            gC[rightCell.id(), 1] -= vec[1]
            gC[rightCell.id(), 2] -= vec[2]

    gC[:, 0] /= mesh.cellSizes()
    gC[:, 1] /= mesh.cellSizes()
    gC[:, 2] /= mesh.cellSizes()

    return gC
Exemple #18
0
def transform2DMeshTo3D(mesh, x, y, z=None):
    """
    Transform a 2D mesh into 3D coordinates using a point list (e.g. from GPS)

    Parameters
    ----------
    mesh: GIMLi::Mesh
    x,y: array of x/y positions along 2d profile
    z: optional height to add (topographical correction if computed flat earth)

    See Also
    --------

    References
    ----------
    """

    # get mesh node positions
    mt, mz = pg.x( mesh.positions() ), pg.y( mesh.positions() ) # mesh tape and z
    # compute length of reference points along tape
    pt = np.hstack( (0., np.cumsum( np.sqrt( np.diff( x )**2 + np.diff( y )**2 ) ) ) )
    #  interpolate node positions from tape to x/y using tape positions
    mx = np.interp( mt, pt, x )
    my = np.interp( mt, pt, y )
    # compute z offset by interpolating z
    if z is None:
        oz = np.zeros( len(mt) )
    else:
        oz = np.interp( mt, pt, z )

    # set the positions in the mesh
    for i, node in enumerate( mesh.nodes() ):
        node.setPos( pg.RVector3( mx[i], my[i], mz[i]+oz[i] ) )
Exemple #19
0
    def showVA(self, data=None, t=None, name='va', pseudosection=False,
               squeeze=True, full=True, ax=None, cmap=None, **kwargs):
        """Show apparent velocity as image plot.

        TODO showXXX commands need to return ax and cbar .. if there is one

        """
        if data is None:
            data = self.dataContainer

        if ax is None:
            fig, ax = plt.subplots()
            self.figs[name] = fig

        self.axs[name] = ax
        if t is None:
            t = data('t')

        px = pg.x(data.sensorPositions())
        gx = np.array([px[int(g)] for g in data("g")])
        sx = np.array([px[int(s)] for s in data("s")])
        offset = self.getOffset(data=data, full=full)
        va = offset / t

        if pseudosection:
            midpoint = (gx + sx) / 2
            showVecMatrix(midpoint, offset, va, squeeze=True, ax=ax,
                          label='Apparent slowness [s/m]', cmap=cmap, **kwargs)
        else:
            showVecMatrix(gx, sx, va, squeeze=squeeze, ax=ax,
                          label='Apparent velocity [m/s]', cmap=cmap, **kwargs)
        fig.show()
        return ax  # va
def create_mesh_and_data(n):
    nc = np.linspace(-2.0, 0.0, n)
    mesh = pg.createMesh2D(nc, nc)
    mcx = pg.x(mesh.cellCenter())
    mcy = pg.y(mesh.cellCenter())
    data = np.cos(1.5 * mcx) * np.sin(1.5 * mcy)
    return mesh, data
Exemple #21
0
    def showVA(self, ax=None, t=None, name='va', pseudosection=False,
               squeeze=True, full=True):
        """show apparent velocity as image plot

        TODO showXXX commands need to return axes and cbar .. if there is one

        """

        if ax is None:
            fig, ax = plt.subplots()
            self.figs[name] = fig

        self.axs[name] = ax
        if t is None:
            t = self.dataContainer('t')

        px = pg.x(self.dataContainer.sensorPositions())
        gx = np.array([px[int(g)] for g in self.dataContainer("g")])
        sx = np.array([px[int(s)] for s in self.dataContainer("s")])
        offset = self.getOffset(full=full)
        va = offset / t

        if pseudosection:
            midpoint = (gx + sx) / 2
            plotVecMatrix(midpoint, offset, va, squeeze=True, ax=ax,
                          label='Apparent slowness [s/m]')
        else:
            plotVecMatrix(gx, sx, va, squeeze=squeeze, ax=ax,
                          label='Apparent velocity [m/s]')
#        va = showVA(ax, self.dataContainer)
#        plt.show(block=False)
        return va
Exemple #22
0
def integrate(f, ent, order):
    """ integrate function """

    J = 0
    x = []
    w = []
    if type(ent) is list:

        a = ent[0]
        b = ent[1]
        xs = pg.IntegrationRules.instance().gauAbscissa(order)
        w = pg.IntegrationRules.instance().gauWeights(order)

        x = (b - a) / 2.0 * pg.x(xs) + (a + b) / 2.0
        J = (b - a) / 2.0

    else:
        J = ent.shape().jacobianDeterminant()
        xs = pg.IntegrationRules.instance().abscissa(ent.shape(), order)
        w = pg.IntegrationRules.instance().weights(ent.shape(), order)

        x = [ent.shape().xyz(xsi) for xsi in xs]

    for xx in x:
        print xx
    print w
    print funct(f)(x)
    return J * sum(funct(f)(x) * w)
def cellDataToCellGrad(mesh, v, CtB):
    if len(v) != mesh.cellCount():
        print(len(v), mesh.cellCount())
        raise
    div = mesh.boundaryDataToCellGradient(CtB * v)
    return np.vstack([pg.x(div), pg.y(div), pg.z(div)]).T

    vF = cellDataToBoundaryData(mesh, v)
    gC = np.zeros((mesh.cellCount(), 3))

    for b in mesh.boundaries():

        leftCell = b.leftCell()
        rightCell = b.rightCell()
        vec = b.norm() * vF[b.id()] * b.size()

        if leftCell:
            gC[leftCell.id(), 0] += vec[0]
            gC[leftCell.id(), 1] += vec[1]
            gC[leftCell.id(), 2] += vec[2]
        if rightCell:
            gC[rightCell.id(), 0] -= vec[0]
            gC[rightCell.id(), 1] -= vec[1]
            gC[rightCell.id(), 2] -= vec[2]

    gC[:, 0] /= mesh.cellSizes()
    gC[:, 1] /= mesh.cellSizes()
    gC[:, 2] /= mesh.cellSizes()

    return gC
Exemple #24
0
def cellDataToBoundaryGrad(mesh, v, vGrad):
    """TODO Documentme."""
    if len(v) != mesh.cellCount() or len(vGrad) != mesh.cellCount():
        raise BaseException("len(v) dismatch mesh.cellCount()")

    gB = mesh.cellDataToBoundaryGradient(v, vGrad)
    return np.vstack([pg.x(gB), pg.y(gB), pg.z(gB)]).T
Exemple #25
0
def showMesh3DFallback(mesh, data, **kwargs):
    """
    Plot the 3D object sketchy.
    """
    ax = kwargs.pop('ax', None)

    from mpl_toolkits.mplot3d import Axes3D

    if ax is None or not isinstance(ax, Axes3D):
        fig = plt.figure()
        ax = fig.gca(projection='3d', proj_type='persp')
        #ax = fig.gca(projection='3d', proj_type='ortho')

    if mesh.boundaryCount() > 0:
        x, y, tri, z, dataIndex = pg.viewer.mpl.createTriangles(mesh)
        ax.plot_trisurf(x, y, tri, z)
    else:
        if mesh.nodeCount() < 1e4:
            x = pg.x(mesh.positions())
            y = pg.y(mesh.positions())
            z = pg.z(mesh.positions())
            ax.scatter(x, y, z, 'ko')
    ax.set_title('Fallback, install pyvista for proper 3D visualization')

    return ax, None
Exemple #26
0
def cellDataToCellGrad(mesh, v, CtB):
    """TODO Documentme."""
    if len(v) != mesh.cellCount():
        print(len(v), mesh.cellCount())
        raise BaseException("len of v missmatch mesh.cellCount()")
    div = mesh.boundaryDataToCellGradient(CtB * v)
    return np.vstack([pg.x(div), pg.y(div), pg.z(div)]).T
Exemple #27
0
def createCoarsePoly( coarseData ):
    boundary = 1250.0
    mesh = g.Mesh()

    x = g.x( coarseData )
    y = g.y( coarseData )
    z = g.z( coarseData )

    xMin = min( x ); xMax = max( x )    
    yMin = min( y ); yMax = max( y )
    zMin = min( z ); zMax = max( z )        

    print(xMin, xMax, yMin, yMax)
    border = max( (xMax - xMin) * boundary / 100.0, (yMax - yMin) * boundary / 100.0);

    n1 = mesh.createNode( xMin - border, yMin - border, zMin, 1 )
    n2 = mesh.createNode( xMax + border, yMin - border, zMin, 2 )
    n3 = mesh.createNode( xMax + border, yMax + border, zMin, 3 )
    n4 = mesh.createNode( xMin - border, yMax + border, zMin, 4 )
  
    mesh.createEdge( n1, n2, 12 );
    mesh.createEdge( n2, n3, 23 );
    mesh.createEdge( n3, n4, 34 );
    mesh.createEdge( n4, n1, 41 );

    for p in coarseData:
        mesh.createNode( p )

    return mesh
Exemple #28
0
def plotFirstPicks(ax, data, tt=None, plotva=False, marker='x-'):
    """plot first arrivals as lines"""
    px = pg.x(data.sensorPositions())
    gx = np.array([px[int(g)] for g in data("g")])
    sx = np.array([px[int(s)] for s in data("s")])
    if tt is None:
        tt = np.array(data("t"))
    if plotva:
        tt = np.absolute(gx - sx) / tt

    uns = np.unique(sx)

    cols = plt.cm.tab10(np.arange(10))

    for i, si in enumerate(uns):
        ti = tt[sx == si]
        gi = gx[sx == si]
        ii = gi.argsort()
        ax.plot(gi[ii], ti[ii], marker, color=cols[i % 10])
        ax.plot(si, 0., 's', color=cols[i % 10], markersize=8)

    ax.grid(True)
    if plotva:
        ax.set_ylabel("Apparent velocity (m/s)")
    else:
        ax.set_ylabel("Traveltime (s)")
    ax.set_xlabel("x (m)")
    ax.invert_yaxis()
Exemple #29
0
    def test_Helmholtz(self):
        """
            d² u / d x² + k u + f = 0
            k = 2
            a) P1(exact)
                u = x
                f = -k x
            b) P2(exact)
                u = x*x
                f = -(2 + 2x*x)
        """
        h = np.pi / 2 / 21
        x = np.arange(0.0, np.pi / 2, h)
        mesh = pg.createGrid(x)

        ### test a)
        k = 2.0
        u = lambda _x: _x
        f = lambda _x, _k: -_k * u(_x)

        x = pg.x(mesh)
        dirichletBC = {1: u(min(x)), 2: u(max(x))}
        uFEM = pg.solve(mesh,
                        a=1,
                        b=k,
                        f=f(x, k),
                        bc={'Dirichlet': dirichletBC})

        # pg.plt.plot(x, uFEM, '.')
        # pg.plt.plot(pg.sort(x), u(pg.sort(x)))
        # pg.wait()

        np.testing.assert_allclose(uFEM, u(x))

        ### test b)
        u = lambda _x: _x * _x
        f = lambda _x, _k: -(2. + k * u(_x))

        mesh = mesh.createP2()
        x = pg.x(mesh)
        dirichletBC = {1: u(min(x)), 2: u(max(x))}
        uFEM = pg.solve(mesh,
                        a=1,
                        b=k,
                        f=f(x, k),
                        bc={'Dirichlet': dirichletBC})
        np.testing.assert_allclose(uFEM, u(x), atol=1e-6)
Exemple #30
0
def createGradientModel2D(data, mesh, vTop, vBot):
    """Create 2D velocity gradient model.

    Creates a smooth, linear, starting model that takes the slope
    of the topography into account. This is done by fitting a straight line
    and using the distance to that as the depth value.
    Known as "The Marcus method"

    TODO
    ----
        * Cite "The Marcus method"

    Parameters
    ----------
    data: pygimli DataContainer
        The topography list is in here.
    mesh: pygimli.Mesh
        The parametric mesh used for the inversion
    vTop: float
        The velocity at the surface of the mesh
    vBot: float
        The velocity at the bottom of the mesh

    Returns
    -------
    model: pygimli Vector, length M
        A numpy array with slowness values that can be used to start
        the inversion.
    """
    yVals = pg.y(data)
    if abs(min(yVals)) < 1e-8 and abs(max(yVals)) < 1e-8:
        yVals = pg.z(data)

    p = np.polyfit(pg.x(data), yVals, deg=1)  # slope-intercept form
    n = np.asarray([-p[0], 1.0])  # normal vector
    nLen = np.sqrt(np.dot(n, n))

    x = pg.x(mesh.cellCenters())
    z = pg.y(mesh.cellCenters())
    pos = np.column_stack((x, z))

    d = np.array([
        np.abs(np.dot(pos[i, :], n) - p[1]) / nLen for i in range(pos.shape[0])
    ])

    return 1.0 / np.interp(d, [min(d), max(d)], [vTop, vBot])
Exemple #31
0
    def test_createPartMesh(self):
        mesh = pg.meshtools.createMesh1D(np.linspace(0, 1, 10))
        self.assertEqual(mesh.cellCount(), 9)

        mesh2 = mesh.createMeshByCellIdx(
            pg.find(pg.x(mesh.cellCenters()) < 0.5))
        self.assertEqual(mesh2.cellCount(), 4)
        self.assertEqual(mesh2.cellCenters()[-1][0] < 0.5, True)
    def test_createPartMesh(self):
        mesh = pg.createMesh1D(np.linspace(0, 1, 10))
        self.assertEqual(mesh.cellCount(), 9)

        mesh2 = mesh.createMeshByCellIdx(
            pg.find(pg.x(mesh.cellCenters()) < 0.5))
        self.assertEqual(mesh2.cellCount(), 4)
        self.assertEqual(mesh2.cellCenters()[-1][0] < 0.5, True)
Exemple #33
0
def createTriangles(mesh):
    """Generate triangle objects for later drawing.

    Creates triangle for each 2D triangle cell or 3D boundary.
    Quads will be split into two triangles.
    Result will be cached into mesh._triData.

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

    Returns
    -------
    x : numpy array
        x position of nodes
    y : numpy array
        x position of nodes
    triangles : numpy array Cx3
        cell indices for each triangle, quad or boundary face
    z : numpy array
        z position for given indices
    dataIdx : list of int
        List of indices for a data array
    """
    if hasattr(mesh, '_triData'):
        if hash(mesh) == mesh._triData[0]:
            return mesh._triData[1:]

    x = pg.x(mesh)
    y = pg.y(mesh)
    z = pg.z(mesh)
    #    x.round(1e-1)
    #    y.round(1e-1)

    if mesh.dim() == 2:
        ents = mesh.cells()
    else:
        ents = mesh.boundaries(mesh.boundaryMarkers() != 0)
        if len(ents) == 0:
            for b in mesh.boundaries():
                if b.leftCell() is None or b.rightCell() is None:
                    ents.append(b)

    triangles = []
    dataIdx = []

    for c in ents:
        triangles.append([c.node(0).id(), c.node(1).id(), c.node(2).id()])
        dataIdx.append(c.id())

        if c.shape().nodeCount() == 4:
            triangles.append([c.node(0).id(), c.node(2).id(), c.node(3).id()])
            dataIdx.append(c.id())

    mesh._triData = [hash(mesh), x, y, triangles, z, dataIdx]

    return x, y, triangles, z, dataIdx
Exemple #34
0
    def getMidpoint(self, data=None):
        """Return vector of offsets (in m) between shot and receiver."""
        if data is None:
            data = self.dataContainer

        px = pg.x(data.sensorPositions())
        gx = np.array([px[int(g)] for g in data("g")])
        sx = np.array([px[int(s)] for s in data("s")])
        return (gx + sx) / 2
Exemple #35
0
    def getMidpoint(self, data=None):
        """Return vector of offsets (in m) between shot and receiver."""
        if data is None:
            data = self.dataContainer

        px = pg.x(data.sensorPositions())
        gx = np.array([px[int(g)] for g in data("g")])
        sx = np.array([px[int(s)] for s in data("s")])
        return (gx + sx) / 2
Exemple #36
0
        def _testP1_(mesh, show=False):
            """ Laplace u = 0 solves u = x for u(r=0)=0 and u(r=1)=1
                Test for u == exact x for P1 base functions
            """
            u = pg.solve(mesh, a=1, b=0, f=0, 
                         bc={'Dirichlet': [[1, 0], [2, 1]]})

            if show:
                if mesh.dim()==1:    
                    pg.plt.plot(pg.x(mesh), u)
                    pg.wait()
                elif mesh.dim()==2:
                    pg.show(mesh, u, label='u')
                    pg.wait()

            xMin = mesh.xmin()
            xSpan = (mesh.xmax() - xMin)
            np.testing.assert_allclose(u, (pg.x(mesh)-xMin)/ xSpan)
            return u
Exemple #37
0
        def _testP1_(mesh, show=False):
            """ Laplace u = 0 solves u = x for u(r=0)=0 and u(r=1)=1
                Test for u == exact x for P1 base functions
            """
            u = pg.solve(mesh, a=1, b=0, f=0, 
                         bc={'Dirichlet': [[1, 0], [2, 1]]})

            if show:
                if mesh.dim()==1:    
                    pg.plt.plot(pg.x(mesh), u)
                    pg.wait()
                elif mesh.dim()==2:
                    pg.show(mesh, u, label='u')
                    pg.wait()

            xMin = mesh.xmin()
            xSpan = (mesh.xmax() - xMin)
            np.testing.assert_allclose(u, (pg.x(mesh)-xMin)/ xSpan)
            return u
Exemple #38
0
def calcInvBlock(mesh, dens, out='gravInv'):

    # extract block delta density
    densBlock = pg.RVector(dens)
    densMarker2 = dens[pg.find(mesh.cellMarker() == 2)[0]]
#    densBlock[(mesh.cellMarker() == 1)|(mesh.cellMarker() == 3)] = densMarker2
    densBlock[pg.find((mesh.cellMarker() == 1) | (mesh.cellMarker() == 3))] = \
        densMarker2
    densBlock -= densMarker2

    # define meausrement positions
    gravPointsX = np.linspace(-20, 20, 41)
    sensorPositions = np.vstack((gravPointsX, np.zeros(len(gravPointsX)))).T

    # solve analytical
    gz = solveGravimetry(mesh, densBlock, pnts=sensorPositions, complete=False)

    # noisyfy
    errAbs = 0.00001
    dzerr = np.random.randn(len(sensorPositions)) * errAbs
    gz = gz + dzerr

    # createParamesh
    paraMesh = pg.createGrid(x=np.linspace(-20, 20, 41),
                             y=np.linspace(-20, 0, 21))

    # init Gravimetry manager (should do meshing, simulation and noisying)
    Grav = Gravimetry(verbose=True)

    model = Grav.invert(sensorPositions, gz, errAbs, verbose=1, mesh=paraMesh)

    fig, ax = plt.subplots()
    ax.plot(pg.x(sensorPositions), gz, label='gz')
    ax.plot(pg.x(sensorPositions), Grav.inv.response(), label='response')
    ax.legend()
    ax.grid()
    ax.set_xlabel('$x$ [m]')
    ax.set_ylabel('$\partial u / \partial z$ [mGal]')
    plt.show(block=False)
    ax.figure.savefig(out, bbox_inches='tight')

    return Grav, densBlock
Exemple #39
0
def calcInvBlock(mesh, dens, out='gravInv'):

    # extract block delta density
    densBlock = pg.RVector(dens)
    densMarker2 = dens[pg.find(mesh.cellMarker() == 2)[0]]
    #densBlock[(mesh.cellMarker() == 1) | (mesh.cellMarker() == 3)] = densMarker2
    densBlock[pg.find((mesh.cellMarker() == 1)
                      | (mesh.cellMarker() == 3))] = densMarker2
    densBlock -= densMarker2

    # define meausrement positions
    gravPointsX = np.linspace(-20, 20, 41)
    sensorPositions = np.vstack((gravPointsX, np.zeros(len(gravPointsX)))).T

    # solve analytical
    gz = solveGravimetry(mesh, densBlock, pnts=sensorPositions, complete=False)

    # noisyfy
    errAbs = 0.00001
    dzerr = np.random.randn(len(sensorPositions)) * errAbs
    gz = gz + dzerr

    # createParamesh
    paraMesh = pg.createGrid(x=np.linspace(-20, 20, 41),
                             y=np.linspace(-20, 0, 21))

    # init Gravimetry manager (should do meshing, simulation and noisying)
    Grav = Gravimetry(verbose=True)

    model = Grav.invert(sensorPositions, gz, errAbs, verbose=1, mesh=paraMesh)

    fig, ax = plt.subplots()
    ax.plot(pg.x(sensorPositions), gz, label='gz')
    ax.plot(pg.x(sensorPositions), Grav.inv.response(), label='response')
    ax.legend()
    ax.grid()
    ax.set_xlabel('$x$ [m]')
    ax.set_ylabel('$\partial u / \partial z$ [mGal]')
    plt.show(block=False)
    ax.figure.savefig(out, bbox_inches='tight')

    return Grav, densBlock
Exemple #40
0
    def showVA(self,
               data=None,
               t=None,
               name='va',
               pseudosection=False,
               squeeze=True,
               full=True,
               ax=None,
               cmap=None,
               **kwargs):
        """Show apparent velocity as image plot.

        TODO showXXX commands need to return ax and cbar .. if there is one
        """
        if data is None:
            data = self.dataContainer

        if ax is None:
            fig, ax = plt.subplots()
            self.figs[name] = fig

        self.axs[name] = ax
        if t is None:
            t = data('t')

        px = pg.x(data.sensorPositions())
        py = pg.y(data.sensorPositions())
        if len(np.unique(py)) > len(np.unique(px)):  # probably crosshole
            px = py

        gx = np.array([px[int(g)] for g in data("g")])
        sx = np.array([px[int(s)] for s in data("s")])
        offset = self.getOffset(data=data, full=full)
        kwargs.setdefault('vals', offset / t)

        if pseudosection:
            midpoint = (gx + sx) / 2
            _, cb = showVecMatrix(midpoint,
                                  offset,
                                  squeeze=True,
                                  ax=ax,
                                  label='Apparent slowness [s/m]',
                                  cmap=cmap,
                                  **kwargs)
        else:
            _, cb = showVecMatrix(gx,
                                  sx,
                                  squeeze=squeeze,
                                  ax=ax,
                                  label='Apparent velocity [m/s]',
                                  cmap=cmap,
                                  **kwargs)
        ax.figure.show()
        return ax, cb
Exemple #41
0
def invertGravimetry(gravPoints, dz):

    dzerr = np.random.randn(len(gravPoints)) * 0.0001
    dz = dz + dzerr

    mesh = pg.createGrid(x=np.linspace(-20, 20, 41), y=np.linspace(-20, 0, 21))

    grav = Gravimetry(verbose=True)

    model = grav.invert(gravPoints, dz, verbose=1, mesh=mesh)

    plt.plot(pg.x(gravPoints), dz)
    plt.plot(pg.x(gravPoints), grav.inv.response())

    paraDomain = grav.fop.regionManager().paraDomain()
    pg.show(paraDomain, model, colorBar=1, hold=1)

    pg.showNow()
    plt.show()
    pass
Exemple #42
0
def tapeMeasureToCoordinates(tape, pos):
    """Interpolate 2D tape measured topography to 2D Cartesian coordinates.

    Tape and pos value are expected to be sorted along distance to the orign.

    TODO optional smooth curve with harmfit

    Parameters
    ----------
    tape : [[x,z]] | [RVector3] | R3Vector
        List of tape measured topography points with measured distance (x)
        from origin and height (z)

    pos : iterable
        Query positions along the tape measured profile

    Returns
    -------
    res : ndarray(N, 2)
        Same as pos but with interpolated height values.
        The Distance between pos points and res (along curve) points remains.

    Examples
    --------
    >>> # no need to import matplotlib. pygimli's show does
    >>> import numpy as np
    >>> import pygimli as pg
    >>> import pygimli.meshtools as mt
    >>> elec = np.arange(11.)
    >>> topo = np.array([[0., 0.], [3., 2.], [4., 2.], [6., 1.], [10., 1.]])
    >>> _= pg.plt.plot(topo[:,0], topo[:,1])
    >>> p = mt.tapeMeasureToCoordinates(topo, elec)
    >>> pg.plt.gca().plot(p[:,0], p[:,1], 'o') #doctest: +ELLIPSIS
    [...]
    >>> pg.plt.gca().set_aspect(1)
    >>> pg.wait()
    """
    if isinstance(tape, pg.R3Vector) or isinstance(tape, pg.stdVectorRVector3):
        xTape = pg.x(tape)
        zTape = pg.z(tape)
    else:
        xTape = tape[:, 0]
        zTape = tape[:, 1]

    t = pg.utils.cumDist(pos)
    # print(t)
    tTape = pg.utils.cumDist(tape)
    xt = np.interp(t, tTape, xTape)
    zt = np.interp(t, tTape, zTape)

    pg.plt.plot(xTape, zTape)
    pg.plt.plot(xt, zt, 'o')
    pg.wait()
    return np.vstack([xt, zt]).T
Exemple #43
0
def solveDarcy(mesh, k=None, p0=1, verbose=False):
    """Darcy flow."""
    if verbose:
        print("Solve darcy")

    uDir = [
        [2, p0],  # left aquiver
        [3, p0],  # left bedrock
        #[4, 0],  # bottom (paper)
        [5, 0],  # right bedrock
        [6, 0],  # right aquiver
        [7, 0],  # right top
    ]

    p = pg.solver.solve(mesh, a=k, uB=uDir)
    vel = -pg.solver.grad(mesh, p) * np.asarray([k, k, k]).T
    return mesh, mt.cellDataToNodeData(
        mesh,
        np.asarray([pg.x(vel),
                    pg.y(vel)]).T), p, k, np.asarray([pg.x(vel),
                                                      pg.y(vel)])
Exemple #44
0
def invertGravimetry(gravPoints, dz):

    dzerr = np.random.randn(len(gravPoints)) * 0.0001
    dz = dz + dzerr

    mesh = pg.createGrid(x=np.linspace(-20, 20, 41),
                         y=np.linspace(-20, 0, 21))

    grav = Gravimetry(verbose=True)

    model = grav.invert(gravPoints, dz, verbose=1, mesh=mesh)

    plt.plot(pg.x(gravPoints), dz)
    plt.plot(pg.x(gravPoints), grav.inv.response())

    paraDomain=grav.fop.regionManager().paraDomain()
    pg.show(paraDomain, model, colorBar=1, hold=1)

    pg.showNow()
    plt.show()
    pass
Exemple #45
0
def drawTravelTimeData(ax, data, t=None):
    """Draw first arrival traveltime data into mpl ax a.

    data of type pg.DataContainer must contain sensorIdx 's' and 'g'
    and thus being numbered internally [0..n)
    """
    x = pg.x(data.sensorPositions())
    # z = pg.z(data.sensorPositions())

    shots = pg.unique(pg.sort(data('s')))
    geoph = pg.unique(pg.sort(data('g')))

    startOffsetIDX = 0

    if min(min(shots), min(geoph)) == 1:
        startOffsetIDX = 1

    tShow = data('t')
    if t is not None:
        tShow = t

    ax.set_xlim([min(x), max(x)])
    ax.set_ylim([max(tShow), -0.002])
    ax.figure.show()

    for shot in shots:
        gIdx = pg.find(data('s') == shot)
        sensorIdx = [int(i__ - startOffsetIDX) for i__ in data('g')[gIdx]]
        ax.plot(x[sensorIdx], tShow[gIdx], 'x-')

    yPixel = ax.transData.inverted().transform_point((1, 1))[1] - \
        ax.transData.inverted().transform_point((0, 0))[1]
    xPixel = ax.transData.inverted().transform_point((1, 1))[0] - \
        ax.transData.inverted().transform_point((0, 0))[0]

    # draw shot points
    ax.plot(x[[int(i__ - startOffsetIDX) for i__ in shots]],
            np.zeros(len(shots)) + 8. * yPixel,
            'gv',
            markersize=8)

    # draw geophone points
    ax.plot(x[[int(i__ - startOffsetIDX) for i__ in geoph]],
            np.zeros(len(geoph)) + 3. * yPixel,
            'r^',
            markersize=8)

    ax.grid()
    ax.set_ylim([max(tShow), +16. * yPixel])
    ax.set_xlim([min(x) - 5. * xPixel, max(x) + 5. * xPixel])

    ax.set_xlabel('x-Coordinate [m]')
    ax.set_ylabel('Traveltime [ms]')
Exemple #46
0
def createGradientModel2D(data, mesh, VTop, VBot):
    """
    Create 2D velocity gradient model.

    Creates a smooth, linear, starting model that takes the slope
    of the topography into account. This is done by fitting a straight line
    and using the distance to that as the depth value.
    Known as "The Marcus method"


    Parameters
    ----------
    data : pygimli DataContainer
        The topography list is in here.
    mesh : pygimli.Mesh
        The parametric mesh used for the inversion
    VTop : float
        The velocity at the surface of the mesh
    VBot : float
        The velocity at the bottom of the mesh

    Returns
    -------
    model : pygimli Vector, length M
        A numpy array with slowness values that can be used to start
        the inversion.
    """

    p = np.polyfit(pg.x(data.sensorPositions()), pg.y(data.sensorPositions()),
                   deg=1)  # slope-intercept form
    n = np.asarray([-p[0], 1.0])  # normal vector
    nLen = np.sqrt(np.dot(n, n))

    x = pg.x(mesh.cellCenters())
    z = pg.y(mesh.cellCenters())
    pos = np.column_stack((x, z))
    d = np.array([np.abs(np.dot(pos[i, :], n) - p[1]) / nLen
                  for i in range(pos.shape[0])])

    return np.interp(d, [min(d), max(d)], [1.0 / VTop, 1.0 / VBot])
Exemple #47
0
 def getOffset(self, full=False):
     """return vector of offsets (in m) between shot and receiver"""
     if full:
         pos = self.dataContainer.sensorPositions()
         s, g = self.dataContainer('s'), self.dataContainer('g')
         nd = self.dataContainer.size()
         off = [pos[int(s[i])].distance(pos[int(g[i])]) for i in range(nd)]
         return np.absolute(off)
     else:
         px = pg.x(self.dataContainer.sensorPositions())
         gx = np.array([px[int(g)] for g in self.dataContainer("g")])
         sx = np.array([px[int(s)] for s in self.dataContainer("s")])
         return np.absolute(gx - sx)
Exemple #48
0
 def getOffset(self, full=False):
     """Return vector of offsets (in m) between shot and receiver."""
     if full:
         pos = self.dataContainer.sensorPositions()
         s, g = self.dataContainer('s'), self.dataContainer('g')
         nd = self.dataContainer.size()
         off = [pos[int(s[i])].distance(pos[int(g[i])]) for i in range(nd)]
         return np.absolute(off)
     else:
         px = pg.x(self.dataContainer.sensorPositions())
         gx = np.array([px[int(g)] for g in self.dataContainer("g")])
         sx = np.array([px[int(s)] for s in self.dataContainer("s")])
         return np.absolute(gx - sx)
Exemple #49
0
def createTriangles(mesh, data=None):
    """
        What is this?
    """
    x = pg.x(mesh.positions())
#    x.round(1e-1)
    y = pg.y(mesh.positions())
#    y.round(1e-1)

    triCount = 0

    for c in mesh.cells():
        if c.shape().nodeCount() == 4:
            triCount = triCount + 2
        else:
            triCount = triCount + 1

    triangles = np.zeros((triCount, 3))
    dataIdx = list(range(triCount))

    triCount = 0
    for c in mesh.cells():
        if c.shape().nodeCount() == 4:
            triangles[triCount, 0] = c.node(0).id()
            triangles[triCount, 1] = c.node(1).id()
            triangles[triCount, 2] = c.node(2).id()
            dataIdx[triCount] = c.id()
            triCount = triCount + 1

            triangles[triCount, 0] = c.node(0).id()
            triangles[triCount, 1] = c.node(2).id()
            triangles[triCount, 2] = c.node(3).id()
            dataIdx[triCount] = c.id()
            triCount = triCount + 1
        else:
            triangles[triCount, 0] = c.node(0).id()
            triangles[triCount, 1] = c.node(1).id()
            triangles[triCount, 2] = c.node(2).id()
            dataIdx[triCount] = c.id()
            triCount = triCount + 1

    z = None
    if data is not None:
        if len(data) == mesh.cellCount():
            # strange behavior if we just use these slice
            z = np.array(data[dataIdx])
        else:
            z = np.array(data)

    return x, y, triangles, z, dataIdx
Exemple #50
0
def drawTravelTimeData(axes, data, t=None):
    """
        Draw first arrival traveltime data into mpl axes a.
        data of type \ref DataContainer must contain sensorIdx 's' and 'g'
        and thus being numbered internally [0..n)
    """

    x = pg.x(data.sensorPositions())
#    z = pg.z(data.sensorPositions())

    shots = pg.unique(pg.sort(data('s')))
    geoph = pg.unique(pg.sort(data('g')))

    startOffsetIDX = 0

    if min(min(shots), min(geoph)) == 1:
        startOffsetIDX = 1

    tShow = data('t')
    if t is not None:
        tShow = t

    axes.set_xlim([min(x), max(x)])
    axes.set_ylim([max(tShow), -0.002])
    axes.figure.show()

    for shot in shots:
        gIdx = pg.find(data('s') == shot)
        sensorIdx = [int(i__ - startOffsetIDX) for i__ in data('g')[gIdx]]
        axes.plot(x[sensorIdx], tShow[gIdx], 'x-')

    yPixel = axes.transData.inverted().transform_point((1, 1))[1] - \
        axes.transData.inverted().transform_point((0, 0))[1]
    xPixel = axes.transData.inverted().transform_point((1, 1))[0] - \
        axes.transData.inverted().transform_point((0, 0))[0]

    # draw shot points
    axes.plot(x[[int(i__ - startOffsetIDX) for i__ in shots]],
           np.zeros(len(shots)) + 8. * yPixel, 'gv', markersize=8)

    # draw geophone points
    axes.plot(x[[int(i__ - startOffsetIDX) for i__ in geoph]],
           np.zeros(len(geoph)) + 3. * yPixel, 'r^', markersize=8)

    axes.grid()
    axes.set_ylim([max(tShow), +16. * yPixel])
    axes.set_xlim([min(x) - 5. * xPixel, max(x) + 5. * xPixel])

    axes.set_xlabel('x-Coordinate [m]')
    axes.set_ylabel('Traveltime [ms]')
Exemple #51
0
def cellDataToBoundaryData(mesh, vec):
    """
        DOCUMENT_ME
    """
    if len(data) != mesh.cellCount():
        raise BaseException("Dimension mismatch, expecting cellCount(): " 
                            + str(mesh.cellCount()) 
                            + "got: " + str(len(vec)), str(len(vec[0])))
    
    CtB = mesh.cellToBoundaryInterpolation()
    
    if type(vec) == pg.R3Vector():
        return np.array([CtB*pg.x(vec), CtB*pg.y(vec), CtB*pg.z(vec)]).T
    else:
        return CtB*vec
Exemple #52
0
def cellDataToBoundaryData(mesh, data):
    """ TODO DOCUMENT_ME """
    if len(data) != mesh.cellCount():
        raise BaseException("Dimension mismatch, expecting cellCount(): " +
                            str(mesh.cellCount()) +
                            "got: " + str(len(data)), str(len(data[0])))

    CtB = mesh.cellToBoundaryInterpolation()

    if isinstance(data, pg.R3Vector()):
        return np.array([CtB * pg.x(data),
                         CtB * pg.y(data),
                         CtB * pg.z(data)]).T
    else:
        return CtB * data
Exemple #53
0
def solveDarcy(mesh, k=None, p0=1, verbose=False):
    """Darcy flow."""
    if verbose:
        print("Solve Darcy equation ...")

    uDir = [[2, p0],  # left aquiver
            [3, p0],  # left bedrock
            # [4, 0],  # bottom (paper)
            [5, 0],  # right bedrock
            [6, 0],  # right aquiver
            [7, 0],  # right top
            ]

    p = pg.solver.solve(mesh, a=k, bc={'Dirichlet': uDir}, verbose=True)
    vel = -pg.solver.grad(mesh, p) * np.asarray([k, k, k]).T
    mvel = mt.cellDataToNodeData(mesh, vel)
    return mesh, mvel, p, k, np.asarray([pg.x(vel), pg.y(vel)])
Exemple #54
0
def createFinePoly( coarseMesh, ePos ):
    paraBoundary = 10
    mesh = g.Mesh()
    
    n1 = None; n2 = None; n3 = None; n4 = None
    for n in coarseMesh.nodes():
        if n.marker() == 1:
            n1 = mesh.createNode( n.pos(), 1 )
        elif n.marker() == 2:
            n2 = mesh.createNode( n.pos(), 2 )
        elif n.marker() == 3:
            n3 = mesh.createNode( n.pos(), 3 )
        elif n.marker() == 4:
            n4 = mesh.createNode( n.pos(), 4 )

    mesh.createEdge( n1, n2, 12 );
    mesh.createEdge( n2, n3, 23 );
    mesh.createEdge( n3, n4, 34 );
    mesh.createEdge( n4, n1, 41 );

    x = g.x( ePos )
    y = g.y( ePos )
    z = g.z( ePos )

    xMin = min( x ); xMax = max( x )    
    yMin = min( y ); yMax = max( y )
    zMin = min( z ); zMax = max( z )

    maxSpan = max( xMax - xMin, yMax - yMin );
    borderPara = maxSpan * paraBoundary / 100.0;

    n5 = mesh.createNode( xMin - borderPara, yMin - borderPara , 0.0, 5 );
    n6 = mesh.createNode( xMax + borderPara, yMin - borderPara , 0.0, 6 );
    n7 = mesh.createNode( xMax + borderPara, yMax + borderPara , 0.0, 7 );
    n8 = mesh.createNode( xMin - borderPara, yMax + borderPara , 0.0, 8 );

    mesh.createEdge( n5, n6, 56 );
    mesh.createEdge( n6, n7, 67 );
    mesh.createEdge( n7, n8, 78 );
    mesh.createEdge( n8, n5, 85 );

    for p in ePos:
        mesh.createNode( p )

    return mesh;
Exemple #55
0
        def _test_(mesh, show=False):
            vTest = 0.1
            u = pg.solve(mesh, a=1, f=0,
                         bc={'Node': [mesh.findNearestNode([0.0, 0.0]), 0.],
                             'Neumann': [[1, -vTest], [2, vTest]]}, verbose=0)

            if show:
                if mesh.dim() == 1:
                    pg.plt.plot(pg.x(mesh), u)
                elif mesh.dim() == 2:
                    pg.show(grid, pg.abs(v))
                    pg.show(grid, v, showMesh=1)
                pg.wait()
            
            v = pg.solver.grad(mesh, u)
            #print("|v|:", min(pg.abs(v)), max(pg.abs(v)), pg.mean(pg.abs(v)))
            np.testing.assert_allclose(pg.abs(v), np.ones(mesh.cellCount())*vTest)
            return v
Exemple #56
0
def exportHDF5Mesh(mesh, exportname, group='mesh', indices='cell_indices',
                   pos='coordinates', cells='topology', marker='values'):
    """Writes given :gimliapi:`GIMLI::Mesh` in a hdf5 format file.

    3D tetrahedron meshes only! Boundary markers are ignored.

    Keywords are explained in :py:mod:`pygimli.meshtools.readHDFS`
    """
    h5py = pg.optImport('h5py',
                        requiredFor='export mesh in .h5 data format')

    if not isinstance(mesh, pg.Mesh):
        mesh = pg.Mesh(mesh)

    # prepare output for writing in hdf data container
    pg_pos = mesh.positions()
    mesh_pos = np.array((np.array(pg.x(pg_pos)), np.array(pg.y(pg_pos)),
                         np.array(pg.z(pg_pos)))).T

    mesh_cells = np.zeros((mesh.cellCount(), 4))  # hard coded for tetrahedrons
    for i, cell in enumerate(mesh.cells()):
        mesh_cells[i] = cell.ids()

    mesh_indices = np.arange(0, mesh.cellCount() + 1, 1, dtype=np.int64)
    mesh_markers = np.array(mesh.cellMarkers())

    with h5py.File(exportname, 'w') as out:
        for grp in np.atleast_1d(group):  # can use more than one group
            # writing indices
            idx_name = '{}/{}'.format(grp, indices)
            out.create_dataset(idx_name, data=mesh_indices, dtype=int)
            # writing node positions
            pos_name = '{}/{}'.format(grp, pos)
            out.create_dataset(pos_name, data=mesh_pos, dtype=float)
            # writing cells via indices
            cells_name = '{}/{}'.format(grp, cells)
            out.create_dataset(cells_name, data=mesh_cells, dtype=int)
            # writing marker
            marker_name = '{}/{}'.format(grp, marker)
            out.create_dataset(marker_name, data=mesh_markers, dtype=int)
            out[grp][cells].attrs['celltype'] = np.string_('tetrahedron')
            out[grp][cells].attrs.create('partition', [0])
    return True
Exemple #57
0
def plotFirstPicks(ax, data, tt=None, plotva=False, marker='x-'):
    """plot first arrivals as lines"""
    px = pg.x(data.sensorPositions())
    gx = np.array([px[int(g)] for g in data("g")])
    sx = np.array([px[int(s)] for s in data("s")])
    if tt is None:
        tt = np.array(data("t"))
    if plotva:
        tt = np.absolute(gx - sx) / tt

    uns = np.unique(sx)
    cols = 'brgcmyk'
    for i, si in enumerate(uns):
        ti = tt[sx == si]
        gi = gx[sx == si]
        ii = gi.argsort()
        ax.plot(gi[ii], ti[ii], marker, color=cols[i % 7])
        ax.plot(si, 0., 's', color=cols[i % 7], markersize=8)

    ax.grid(True)
Exemple #58
0
def showVA(ax, data, usepos=True):
    """show apparent velocity as image plot"""
    px = pg.x(data.sensorPositions())
    gx = np.asarray([px[int(g)] for g in data("g")])
    sx = np.asarray([px[int(s)] for s in data("s")])
    va = np.absolute(gx - sx) / data('t')
    A = np.ones((data.sensorCount(), data.sensorCount())) * np.nan
    for i in range(data.size()):
        A[int(data('s')[i]), int(data('g')[i])] = va[i]

    gci = ax.imshow(A, interpolation='nearest')
    ax.grid(True)
    xt = np.arange(0, data.sensorCount(), 50)
    if usepos:
        ax.set_xticks(xt)
        ax.set_xticklabels([str(int(px[xti])) for xti in xt])
        ax.set_yticks(xt)
        ax.set_yticklabels([str(int(px[xti])) for xti in xt])

    plt.colorbar(gci, ax=ax)
    return va
Exemple #59
0
    def createMesh(self, quality=34.6, maxarea=0.1, addpoints=None):
        """Create (inversion) mesh by circumventing PLC"""
        data = self.dataContainer
        sx = list(pg.x(data.sensorPositions()))
        sz = list(pg.y(data.sensorPositions()))

        if addpoints is not None:
            for po in addpoints:
                sx.append(po[0])
                sz.append(po[1])

        iS = np.argsort(np.arctan2(sx-np.mean(sx), sz-np.mean(sz)))
        plc = pg.Mesh(2)
        nodes = [plc.createNode(sx[i], sz[i], 0) for i in iS]
        for i in range(len(nodes)-1):
            plc.createEdge(nodes[i], nodes[i+1])

        plc.createEdge(nodes[-1], nodes[0])
        tri = pg.TriangleWrapper(plc)
        tri.setSwitches("-pzFq"+str(quality)+"a"+str(maxarea))
        self.setMesh(tri.generate())