示例#1
0
 def test_createGrid(self):
     mesh = pg.createGrid(3)
     self.assertEqual(mesh.xmax(), 2.0)
     mesh = pg.createGrid(3, 3)
     self.assertEqual(mesh.ymax(), 2.0)
     mesh = pg.createGrid(3, 3, 3)
     self.assertEqual(mesh.zmax(), 2.0)
示例#2
0
    def test_Neumann(self):
        """
        """
        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

        _test_(pg.createGrid(x=np.linspace(-2, 1, 11)), show=False) #1D
        _test_(pg.createGrid(x=np.linspace(-2, 2, 41), y=np.linspace(0, 1, 21))) #2D reg
        _test_(pg.createGrid(x=np.linspace(-0.04, 0.01, 21), y=np.linspace(-0.4, 0, 21))) #2D scaled
        _test_(pg.createGrid(x=np.linspace(-2, 1, 11), y=np.linspace( 0, 1, 11),
                             z=np.linspace( 0, 1, 11))) #3D

        grid = pg.createGrid(x=np.linspace(-2, 2, 41), y=np.linspace(0, 1, 21))
        grid.rotate([0, 0, np.pi/4])
        v = _test_(grid) #2D reg - rotated
示例#3
0
    def test_Neumann(self):
        """
        """
        def _test_(mesh):
            vTest = 0.1
            u = pg.solve(mesh,
                         a=1,
                         bc={
                             'Node': [mesh.findNearestNode([0.0, 0.0]), 0.],
                             'Neumann': [[1, -vTest], [2, vTest]]
                         })

            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

        _test_(pg.createGrid(x=np.linspace(-2, 1, 11)))  #1D
        _test_(pg.createGrid(x=np.linspace(-2, 2, 41),
                             y=np.linspace(0, 1, 21)))  #2D reg
        _test_(
            pg.createGrid(x=np.linspace(-0.04, 0.01, 21),
                          y=np.linspace(-0.4, 0, 21)))  #2D scaled
        _test_(
            pg.createGrid(x=np.linspace(-2, 1, 11),
                          y=np.linspace(0, 1, 11),
                          z=np.linspace(0, 1, 11)))  #3D

        grid = pg.createGrid(x=np.linspace(-2, 2, 41), y=np.linspace(0, 1, 21))
        grid.rotate([0, 0, np.pi / 4])
        v = _test_(grid)  #2D reg - rotated
示例#4
0
    def test_Neumann(self):
        """
        """
        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

        _test_(pg.createGrid(x=np.linspace(-2, 1, 11)), show=False) #1D
        _test_(pg.createGrid(x=np.linspace(-2, 2, 41), y=np.linspace(0, 1, 21))) #2D reg
        _test_(pg.createGrid(x=np.linspace(-0.04, 0.01, 21), y=np.linspace(-0.4, 0, 21))) #2D scaled
        _test_(pg.createGrid(x=np.linspace(-2, 1, 11), y=np.linspace( 0, 1, 11),
                             z=np.linspace( 0, 1, 11))) #3D

        grid = pg.createGrid(x=np.linspace(-2, 2, 41), y=np.linspace(0, 1, 21))
        grid.rotate([0, 0, np.pi/4])
        v = _test_(grid) #2D reg - rotated
示例#5
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)
示例#6
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)
def createModel2(maxArea=0.2, nx=20, grid=True):
    mesh = None
    if grid:
        nx = nx
        ny = nx
        mesh = pg.createGrid(x=np.linspace(-10, 10, nx),
                             y=np.linspace(0, 20, ny))

    else:
        layer1 = pt.createRectangle(start=[-10, 20],
                                    end=[10, 10],
                                    marker=2,
                                    boundaryMarker=[1, -1, 2, 4])
        layer2 = pt.createRectangle(start=[-10, 10],
                                    end=[10, 0],
                                    marker=1,
                                    boundaryMarker=[1, 3, 2, -1])

        mesh = createMesh([layer1, layer2],
                          quality=32,
                          area=maxArea,
                          smooth=[1, 10])

    density = mesh.cellAttributes() * 0.0 + 2.0

    for c in mesh.cells():
        if c.center().y() > 0 and c.center().x() < 0:
            density[c.id()] = 1.0

    return mesh, density
示例#8
0
文件: test_show.py 项目: rf1991/gimli
def testColRange():
    n = 5
    mesh = pg.createGrid(n, n)

    fig, ax = plt.subplots(2,3, figsize=(8,8))

    ax[0][0].set_title("pyGIMLi (CellData)")
    data = np.arange(mesh.cellCount())
    pg.show(mesh, data, ax=ax[0][0], label='default (nLevs=5, nCols=256)')
    pg.show(mesh, data, ax=ax[1][0], nCols=4, nLevs=5, label="nLevs=5 nCols=4, \n(aka. poor man's contour)")

    ax[0][1].set_title("pyGIMLi (CellData) shading='gouraud'")
    data = np.arange(mesh.cellCount())
    pg.show(mesh, data, ax=ax[0][1], shading='gouraud', label='default (nLevs=5, nCols=256)')
    pg.show(mesh, data, ax=ax[1][1], shading='gouraud', nCols=4, nLevs=5, label="nLevs=5 nCols=4, \n(aka. poor man's contour)")

    ax[0][2].set_title("pyGIMLi (NodeData)")
    data = np.arange(mesh.nodeCount())
    pg.show(mesh, data, ax=ax[0][2],
            label='default (nLevs=5, nCols=4)')
    pg.show(mesh, data, ax=ax[1][2], nCols=12, nLevs=4,
            label='nLevs=4, nCols=12')

    for a in ax.flatten():
        a.yaxis.set_visible(False)
        a.xaxis.set_visible(False)

    fig.tight_layout()
示例#9
0
    def test_Interpolate(self):
        grid = pg.createGrid(x=[0.0, 1.0], y=[0.0, 1.0])
        u = pg.RVector(grid.nodeCount(), 1.)

        # test with pg.interpolate
        queryPos = [0.2, 0.2]
        uI = pg.interpolate(srcMesh=grid,
                            inVec=u,
                            destPos=[queryPos, queryPos])

        np.testing.assert_allclose(uI[0], 1.)

        # test manual interpolation
        c = grid.findCell(queryPos)
        uI = c.pot(queryPos, u)
        np.testing.assert_allclose(uI, 1.)

        # test with manual interpolationMatrix generation
        I = pg.RSparseMapMatrix(1, grid.nodeCount())
        cI = c.N(c.shape().rst(queryPos))
        for i in range(c.nodeCount()):
            I.addVal(0, c.node(i).id(), cI[i])

        uI = I.mult(u)
        np.testing.assert_allclose(uI[0], 1)

        # test with automatic interpolationMatrix generation
        I = grid.interpolationMatrix([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0],
                                      [0.0, 1.0]])
        uI = I * u
        np.testing.assert_allclose(uI, u)

        # api test https://github.com/gimli-org/gimli/issues/131
        x = np.linspace(grid.xmin(), grid.xmax(), 11)
        np.testing.assert_allclose(pg.interpolate(grid, pg.x(grid), x), x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x=x), x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x, x * 0.), x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x=x, y=x * 0), x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x, x * 0, x * 0), x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x=x, y=x * 0,
                           z=x * 0), x)
        x = pg.Vector(x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x), x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x=x), x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x, x * 0.), x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x=x, y=x * 0), x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x, x * 0, x * 0), x)
        np.testing.assert_allclose(
            pg.interpolate(grid, pg.x(grid.positions()), x=x, y=x * 0,
                           z=x * 0), x)
def createModel(maxArea=0.2, nx=80, grid=True):

    mesh=None
    dens=None
    if grid:
        nx = nx
        ny = nx/2
        mesh = pg.createGrid(x=np.linspace(-10, 10, nx),
                            y=np.linspace(-10, 0, ny))
   
        density = mesh.cellAttributes()*0.0 + 1.0
        xstart = (nx-1)*int(ny/1.3) + int(nx/2)
        yoff =nx-1
        for i in range(int(ny/20)):
            density[xstart-nx*0.35+i*yoff: xstart+nx*0.35+i*yoff] *= 2
    else:
        layer1 = pt.createRectangle(start=[-10, 0], end=[10, -10], 
                                 marker=1, boundaryMarker=[1, 3, 2, 4])
        
        block = pt.createRectangle(start=[-10+0.35*10, -1.8918918918918912], 
                                end=[10-0.35*10, -2.2972972972972965], 
                                    marker=2)
        mesh = createMesh([layer1, block], quality=32, area=maxArea,
                          smooth=[1,10])
    
        density = mesh.cellAttributes()*0.0 + 1.0
        density[mesh.cellMarker()==2] = 2
    
    return mesh, density
def createModel2(maxArea=0.2, nx=20, grid=True):
    mesh=None
    if grid:
        nx = nx
        ny = nx
        mesh = pg.createGrid(x=np.linspace(-10, 10, nx),
                             y=np.linspace(0, 20, ny))
   
    else:
        layer1 = pt.createRectangle(start=[-10, 20], end=[10, 10], 
                                    marker=2, boundaryMarker=[1, -1, 2, 4])
        layer2 = pt.createRectangle(start=[-10, 10], end=[10, 0], 
                                    marker=1, boundaryMarker=[1, 3, 2, -1])
        
        mesh = createMesh([layer1, layer2], quality=32, area=maxArea,
                          smooth=[1,10])
        
    density = mesh.cellAttributes()*0.0 + 2.0
    
    for c in mesh.cells():
        if c.center().y() > 0 and c.center().x() < 0:
            density[c.id()] = 1.0
    
    
    return mesh, density
示例#12
0
    def test_meshAccess(self):

        x = [.5, 1, 2, 3, 42]
        y = [.5, 1, 2, 3]
        z = [.5, 1, 3]

        mesh = pg.createGrid(x, y, z)
示例#13
0
    def test_ComplexMatrix(self):
        verbose = False
        grid = pg.createGrid(3, 3)
        # print(grid)

        alpha = pg.math.toComplex(np.ones(grid.cellCount()),
                                  np.ones(grid.cellCount()) * 1.0)

        A = pg.solver.createStiffnessMatrix(grid, a=alpha)
        pg.solver.solver._assembleUDirichlet(A, None, [0], [0.0])
        #pg.solver.showSparseMatrix(A)
        #pg.solver.assembleDirichletBC(A, [[grid.boundary(0), 0.0]])

        b = pg.math.toComplex(np.ones(A.rows()), np.ones(A.rows()) * 0.0)
        x = pg.solver.linSolve(A, b, verbose=verbose, solver='pg')
        np.testing.assert_allclose(A.mult(x), b, rtol=1e-10)

        x2 = pg.solver.linSolve(A, b, verbose=verbose, solver='scipy')
        np.testing.assert_allclose(x2, x, rtol=1e-10)

        x3 = pg.solver.linSolve(pg.utils.squeezeComplex(A),
                                pg.utils.squeezeComplex(b),
                                verbose=verbose,
                                solver='pg')

        np.testing.assert_allclose(pg.utils.toComplex(x3), x, rtol=1e-10)
示例#14
0
    def test_Interpolate(self):
        grid = pg.createGrid(x=[0.0, 1.0], y=[0.0, 1.0])
        u = pg.RVector(grid.nodeCount(), 1.)

        # test with pg.interpolate
        queryPos = [0.2, 0.2]
        uI = pg.interpolate(srcMesh=grid,
                            inVec=u,
                            destPos=[queryPos, queryPos])

        np.testing.assert_allclose(uI[0], 1.)

        # test manual interpolation
        c = grid.findCell(queryPos)
        uI = c.pot(queryPos, u)
        np.testing.assert_allclose(uI, 1.)

        # test with manual interpolationMatrix generation
        I = pg.RSparseMapMatrix(1, grid.nodeCount())
        cI = c.N(c.shape().rst(queryPos))
        for i in range(c.nodeCount()):
            I.addVal(0, c.node(i).id(), cI[i])

        uI = I.mult(u)
        np.testing.assert_allclose(uI[0], 1)

        # test with automatic interpolationMatrix generation
        I = grid.interpolationMatrix([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0],
                                      [0.0, 1.0]])
        uI = I * u
        np.testing.assert_allclose(uI, u)
def createModel(maxArea=0.2, nx=80, grid=True):

    mesh = None
    dens = None
    if grid:
        nx = nx
        ny = nx / 2
        mesh = pg.createGrid(x=np.linspace(-10, 10, nx),
                             y=np.linspace(-10, 0, ny))

        density = mesh.cellAttributes() * 0.0 + 1.0
        xstart = (nx - 1) * int(ny / 1.3) + int(nx / 2)
        yoff = nx - 1
        for i in range(int(ny / 20)):
            density[xstart - nx * 0.35 + i * yoff:xstart + nx * 0.35 +
                    i * yoff] *= 2
    else:
        layer1 = pt.createRectangle(start=[-10, 0],
                                    end=[10, -10],
                                    marker=1,
                                    boundaryMarker=[1, 3, 2, 4])

        block = pt.createRectangle(
            start=[-10 + 0.35 * 10, -1.8918918918918912],
            end=[10 - 0.35 * 10, -2.2972972972972965],
            marker=2)
        mesh = createMesh([layer1, block],
                          quality=32,
                          area=maxArea,
                          smooth=[1, 10])

        density = mesh.cellAttributes() * 0.0 + 1.0
        density[mesh.cellMarker() == 2] = 2

    return mesh, density
示例#16
0
    def test_Constraints(self):
        """ Test FOP """

        grid = pg.createGrid(x=[0., 1., 2.], y=[0., 1., 2.])
        fop = TestMod(grid)

        fop.createConstraints()
        #pg.solver.showSparseMatrix(fop.constraints(), full=True)

        fop.regionManager().setConstraintType(2)
        fop.createConstraints()
示例#17
0
    def test_MeshCreateSecNodes(self):
        x = [0, 1, 2, 3, 42]
        y = [0, 1, 2, 3]
        z = [0, 1, 3]

        mesh = pg.createGrid(x, y, z)
        mesh.createSecondaryNodes(n=1)
        self.assertEqual(mesh.secondaryNodeCount(), mesh.boundaryCount() + \
                                                    (len(x)-1)*len(y)*len(z) + \
                                                    (len(y)-1)*len(z)*len(x) + \
                                                    (len(z)-1)*len(x)*len(y))
示例#18
0
    def test_Constraints(self):
        """ Test FOP """

        grid = pg.createGrid(x=[0., 1., 2.], y=[0., 1., 2.])
        fop = TestMod(grid)

        fop.createConstraints()
        #pg.solver.showSparseMatrix(fop.constraints(), full=True)

        fop.regionManager().setConstraintType(2)
        fop.createConstraints()
示例#19
0
def test(N):

    x = np.linspace(0, 1, N)

    pg.tic()
    mesh = pg.createGrid(x, x, x)
    print(mesh)
    pg.toc()

    A = pg.RSparseMatrix()
    A.fillStiffnessMatrix(mesh)
    pg.toc()
示例#20
0
    def test_SimpleMeshExport(self):

        mesh = pg.createGrid(3, 3)
        verts = mesh.positions()
        cellIds = [c.ids() for c in mesh.cells()]

        mesh2 = pg.Mesh(2)
        [mesh2.createNode(v) for v in verts]
        [mesh2.createCell(c) for c in cellIds]

        np.testing.assert_array_equal(mesh2.nodeCount(), mesh.nodeCount())
        np.testing.assert_array_equal(mesh2.cellCount(), mesh.cellCount())
示例#21
0
def test(N):
    
    x = np.linspace(0, 1, N)

    pg.tic()
    mesh = pg.createGrid(x, x, x)
    print(mesh)
    pg.toc()
    
    A = pg.RSparseMatrix()
    A.fillStiffnessMatrix(mesh)
    pg.toc()
示例#22
0
文件: test_show.py 项目: rf1991/gimli
def testColorbar():

    grid = pg.createGrid(x=np.linspace(10., 110., 11)-5, y=np.linspace(0., 20, 2))

    fig, axs = plt.subplots(nrows=3, ncols=3, figsize=((10,6)))
    ax, cbar = pg.show(grid, data=pg.x(grid.cellCenter()), label='log x',
                       ax=axs[0][0], showMesh=True, cMap='Paired', logScale=True)
    ax, cbar = pg.show(grid, data=pg.x(grid.cellCenter())+5., label='log x',
                       ax=axs[1][0], showMesh=True, cMap='Paired', logScale=True)
    pg.viewer.mpl.setMappableData(cbar.mappable, pg.x(grid.cellCenter()))

    ax, cbar = pg.show(grid, data=pg.x(grid.cellCenter()), logScale=True,
                       ax=axs[2][0], showMesh=True, cMap='Paired')
    ###########################################################################
    ax, cbar = pg.show(grid, data=pg.x(grid.cellCenter()), label='lin x',
                       ax=axs[0][1], logScale=False, cMap='Paired')
    ax, cbar = pg.show(grid, data=pg.x(grid.cellCenter())+5, label='lin x',
                       ax=axs[1][1], logScale=False, cMap='Paired')
    pg.viewer.mpl.setMappableData(cbar.mappable, pg.x(grid.cellCenter()))
    ###########################################################################
    grid = pg.createGrid(x=np.linspace(10., 110., 11)-25, y=np.linspace(0., 20, 2))
    ax, cbar = pg.show(grid, data=pg.x(grid.cellCenter()), label='log with neg. x',
                       ax=axs[0][2], showMesh=True, cMap='Paired', logScale=True)
    ax, cbar = pg.show(grid, data=pg.x(grid.cellCenter())-45, label='log with neg. x',
                       ax=axs[1][2], showMesh=True, cMap='Paired', logScale=True)
    pg.viewer.mpl.setMappableData(cbar.mappable, pg.x(grid.cellCenter()))
    ax.figure.tight_layout()

    pg.show(grid, pg.x(grid.cellCenter()), tri=True, shading='gouraud',
            cMap='Spectral_r', logScale=False, cMin=0.01, cMax=10,
            levels=[10, 55, 100],
            orientation="vertical",
            colorBar=True)


    pg.show(grid, pg.x(grid.cellCenter()), tri=True, shading='gouraud',
            cMap='Spectral_r', logScale=False, cMin=0.01, cMax=10,
            levels=[10, 55, 100],
            orientation="horizontal",
            colorBar=True)
示例#23
0
    def test_R3VectorToNumpy(self):
        '''
            implemented through hand_made_wrapper.py
        '''
        mesh = pg.createGrid(x=[0, 1, 2], y=[0, 1, 2])

        v = np.asarray(mesh.nodeCenters())

        self.assertEqual(type(v), np.ndarray)
        self.assertEqual(len(v), mesh.nodeCount())

        a = np.array(mesh.cellCenter())
        self.assertEqual(type(a), np.ndarray)
        self.assertEqual(len(a), mesh.cellCount())
示例#24
0
    def test_R3VectorToNumpy(self):
        '''
            implemented through hand_made_wrapper.py
        '''
        mesh = pg.createGrid(x=[0, 1, 2], y=[0, 1, 2])
            
        v = np.asarray(mesh.nodeCenters())

        self.assertEqual(type(v), np.ndarray)
        self.assertEqual(len(v), mesh.nodeCount())
        
        a = np.array(mesh.cellCenter())
        self.assertEqual(type(a), np.ndarray)
        self.assertEqual(len(a), mesh.cellCount())
示例#25
0
    def test_R3VectorToNumpy(self):
        """Implemented through hand_made_wrapper.py"""
        mesh = pg.createGrid(x=[0, 1, 2], y=[0, 1, 2], z=[1, 2])

        v = np.asarray(mesh.positions())

        self.assertEqual(type(v), np.ndarray)
        self.assertEqual(len(v), mesh.nodeCount())

        a = np.array(mesh.cellCenter())
        self.assertEqual(type(a), np.ndarray)
        self.assertEqual(len(a), mesh.cellCount())

        self.assertEqual(mesh.positions()[0], v[0])
示例#26
0
def testNumpyFromR3Vec():
    mesh = pg.createGrid(x=[0, 1, 2], y=[0, 1, 2])
    print(mesh)
    print((mesh.nodeCenters()))
    for i in mesh.nodeCenters():
        print(i)
        
    x = np.asarray(mesh.nodeCenters())
    print(x)
    x = np.array(mesh.nodeCenters())
    print(x)
    x = np.array(mesh.cellCenter())
    print(x)
    print((mesh.cell(0).center()))
    print((np.array(mesh.cell(0).center())))
示例#27
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)
示例#28
0
    def setUp(self):
        # Dummy data container
        self.data = pg.DataContainer()
        self.data.createSensor([0.0, 0.0])
        self.data.createSensor([1.0, 2.0])
        self.data.resize(1)
        self.data.set("s", pg.Vector(1, 1.0))
        self.data.set("g", pg.Vector(1, 2.0))
        self.data.registerSensorIndex("s")
        self.data.registerSensorIndex("g")

        # Without secondary nodes
        self.mesh = pg.createGrid([0, 1, 2], [0, 1, 2])

        # Slowness
        self.slo = [1, 2, 1, 4]

        self.mgr = TravelTimeManager()
示例#29
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
示例#30
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
def modelCavity0(maxArea=0.0025):
    mesh = pg.createGrid(x=np.linspace(.0, 1.0, 17),
                         y=np.linspace(.0, 1.0, 17))
    mesh = pg.meshtools.refineQuad2Tri(mesh, style=2)
    
    velBoundary=[[1,[0.0, 0.0]],
                 [2,[0.0, 0.0]],
                 [3,[1.0, 0.0]],
                 [4,[0.0, 0.0]],
                ]

    c = mesh.findCell((0.0, 0.0))
    for b in range(c.boundaryCount()):
        if c.boundary(b).marker()==4:
            c.boundary(b).setMarker(7)
    
    preBoundary=[[7, 0.0],]
    
    a = pg.RVector(mesh.cellCount(), 1.0)
    return mesh, velBoundary, preBoundary, a, 100
示例#32
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
示例#33
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
示例#34
0
def modelCavity0(maxArea=0.0025):
    mesh = pg.createGrid(x=np.linspace(.0, 1.0, 17),
                         y=np.linspace(.0, 1.0, 17))
    mesh = pg.meshtools.refineQuad2Tri(mesh, style=2)

    velBoundary = [
        [1, [0.0, 0.0]],
        [2, [0.0, 0.0]],
        [3, [1.0, 0.0]],
        [4, [0.0, 0.0]],
    ]

    c = mesh.findCell((0.0, 0.0))
    for b in range(c.boundaryCount()):
        if c.boundary(b).marker() == 4:
            c.boundary(b).setMarker(7)

    preBoundary = [
        [7, 0.0],
    ]

    a = pg.RVector(mesh.cellCount(), 1.0)
    return mesh, velBoundary, preBoundary, a, 100
示例#35
0
    def test_VTK_DataRead(self):
        grid = pg.createGrid(np.arange(4), np.arange(3), np.arange(2))
        cM = np.arange(grid.cellCount())
        grid.setCellMarkers(cM)

        import tempfile as tmp
        _, fn = tmp.mkstemp(suffix='.vtk')

        grid.exportVTK(fn)
        mesh = pg.load(fn)
        np.testing.assert_array_equal(mesh.cellMarkers(), cM)
        np.testing.assert_array_equal(mesh['Marker'], cM)

        mesh = pg.meshtools.readMeshIO(fn)
        np.testing.assert_array_equal(mesh['Marker'], cM)

        fn = pg.getExampleFile('meshes/test_tetgen_dataCol.vtk')
        mesh = pg.load(fn)
        np.testing.assert_array_equal(mesh.cellMarkers(), cM)
        np.testing.assert_array_equal(mesh['Marker'], cM)

        mesh = pg.meshtools.readMeshIO(fn)
        np.testing.assert_array_equal(mesh['Marker'], cM)
示例#36
0
def load_grav_pygimli_plate():

    # Half plate
    thickness = 1
    mesh = pg.createGrid(x=np.linspace(0, 5000),
                         y=[-depth - thickness / 2., -depth + thickness / 2.0])
    pg.show(mesh, ax=ax[0, 1])

    ga = gradUHalfPlateHoriz(pnts, thickness, rho, pos=[0, -depth])
    gza = gradGZHalfPlateHoriz(pnts, thickness, rho, pos=[0, -depth])
    g, gz = solveGravimetry(mesh, rho, pnts, complete=True)

    plot(x, ax[1, 1], ga, gza, ax[2, 1], g, gz)

    labels = ["Horizontal cylinder", "Half plate"]
    for ax, label in zip(ax[0], labels):
        ax.set_title(label)
        ax.set_aspect("equal")
        ax.set_xlim(left=x[0], right=x[-1])
        ax.set_ylim(bottom=-depth * 2, top=1)

    fig.tight_layout()

    return g
示例#37
0
# This yields:
#
# Now we know the name space :gimliapi:`GIMLI` and can create a first mesh.
# A mesh is represented by a collection of nodes, cells and boundaries, i.e., geometrical entities.
#
# .. note::
#
#     A regular spaced mesh consisting of rectangles or hexahedrons is usually called grid.
#     However, a grid is just a kind of a mesh and GIMLi does not separate between them.
#     The only difference is the way of mesh creation.
#
# GIMLi provides a collection of tools for mesh import, export and generation.
# A simple grid generation is built-in but we also provide wrappers for unstructured mesh generations, e.g., :term:`Triangle`, :term:`Tetgen` and :term:`Gmsh`.
# To create a 2d grid you need to give two arrays or lists for the sampling points in x and y direction, respectively.

grid = pg.createGrid(x=[-1.0, 0.0, 1.0, 4.0], y=(-1.0, 0.0, 1.0, 4.0))


###############################################################################
# The returned object ``grid`` is an instance of :gimliapi:`GIMLI::Mesh` and provides various methods for modification and io-operations. General informations can be simple printed.
#
print(grid)

###############################################################################
# yields:
#
# Or you can access them manually:
#
print('Mesh: Nodes:', grid.nodeCount(),
      'Cells:', grid.cellCount(),
      'Boundaries:', grid.boundaryCount())
示例#38
0
def _test_ConvectionAdvection():
    """Test agains a refernce solution."""
    N = 21  # 21 reference
    maxIter = 11  # 11 reference
    Nx = N
    Ny = N

    x = np.linspace(-1.0, 1.0, Nx + 1)
    y = np.linspace(-1.0, 1.0, Ny + 1)
    grid = pg.createGrid(x=x, y=y)

    a = pg.RVector(grid.cellCount(), 1.0)

    b7 = grid.findBoundaryByMarker(1)[0]
    for b in grid.findBoundaryByMarker(1):
        if b.center()[1] < b.center()[1]:
            b7 = b
    b7.setMarker(7)

    swatch = pg.Stopwatch(True)
    velBoundary = [[1, [0.0, 0.0]],
                   [2, [0.0, 0.0]],
                   [3, [1.0, 0.0]],
                   [4, [0.0, 0.0]],
                   [7, [0.0, 0.0]]]

    preBoundary = [[7, 0.0]]

    vel, pres, pCNorm, divVNorm = __solveStokes(grid, a,
                                              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.meshtools.cellDataToNodeData(grid, pres),
         logScale=False, showLater=True, colorBar=True, ax=ax1, cbar='b2r')
    show(grid, data=pg.logTransDropTol(
            pg.meshtools.cellDataToNodeData(grid, vel[:, 0]), 1e-2),
         logScale=False, showLater=True, colorBar=True, ax=ax2)
    show(grid, data=pg.logTransDropTol(
            pg.meshtools.cellDataToNodeData(grid, vel[:, 1]), 1e-2),
         logScale=False, showLater=True, colorBar=True, ax=ax3)

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

    plt.figure()
    plt.semilogy(pCNorm, label='norm')
    plt.legend()

    plt.ioff()
    plt.show()
示例#39
0
"""
This yields:

.. lastcout::

Now we know the gimli name space and can start creating a first mesh. A mesh is a collection of nodes, cells and boundaries, i.e, geometrical entities.

.. note::

    A regular spaced mesh consisting of rectangles or hexahedrons is usually called grid. However, internal grids are just special meshes.

Gimli provides a collection of tools for mesh import and generation. Easy grid generation is built-in but we also provide wrappers for unstructured mesh generations. e.g. :term:`triangle` and :term:`tetgen`. Incorporation of other generators should be straightforward, e.g., :py:mod:`pygimli.meshtools`
"""
import numpy as np
grid = pg.createGrid(x=np.linspace(-1.0, 1.0, 3), y=-np.linspace(-1.0, 1.0, 3))
#grid = pg.createGrid(x=[-1.0, 0.0, 1.0, 4.0], y=[-1.0, 0.0, 1.0, 4.0])


"""
``grid`` is an instance of :gimliapi:`GIMLI::Mesh` and provides various methods for modification and io-operations.

"""
print(grid)

"""
yields:

.. lastcout::

For instance, you can iterate through all elements of the general type :gimliapi:`GIMLI::Cell`, which in turn also provides a lot of methods:
示例#40
0
#!/usr/bin/env python
import numpy as np
import pygimli as pg

# Dummy data container
data = pg.DataContainer()
data.createSensor([0.0, 0.0])
data.createSensor([1.0, 2.0])
data.resize(1)
data.set("s", pg.RVector(1, 1.0))
data.set("g", pg.RVector(1, 2.0))
data.registerSensorIndex("s")
data.registerSensorIndex("g")

# Without secondary nodes
mesh = pg.createGrid([0,1,2],[0,1,2])

# Slowness
slo = [1,2,1,4]

def test_withoutSecNodes():
    fop = pg.TravelTimeDijkstraModelling(mesh, data)
    t_normal = fop.response(slo)
    np.testing.assert_allclose(t_normal, 1 + np.sqrt(2))

def test_withSecNodes():
    mesh2 = mesh.createMeshWithSecondaryNodes(n=3)
    fop = pg.TravelTimeDijkstraModelling(mesh2, data)
    t_refined = fop.response(slo)
    np.testing.assert_allclose(t_refined, np.sqrt(5)) # only works if n_secNodes is odd number
示例#41
0
Again, we first import numpy and pygimli, the solver and post processing
functionality.
"""

import numpy as np
import pygimli as pg

from pygimli.solver import solve
from pygimli.viewer import show
from pygimli.mplviewer import drawStreams

###############################################################################
# We create a 50x50 node grid to solve on.

grid = pg.createGrid(x=np.linspace(-1.0, 1.0, 21),
                     y=np.linspace(-1.0, 1.0, 21))

###############################################################################
# We start considering inhomogeneous Dirchlet boundary conditions (BC).
# There are different ways of specifying BCs. They can be maps from markers to
# values, explicit functions or implicit (lambda) functions.
#
# The boundary 1 (top) and 2 (left) are directly mapped to the values 1 and 2.
# On side 3 (bottom) a lambda function 3+x is used (p is the boundary position
# and p[0] its x coordinate. On side 4 (right) a function uDirichlet is used
# that simply returns 4 in this example but can compute anything as a function
# of the individual boundaries b.

###############################################################################
# Short test: setting single node dirichlet BC
u = solve(grid, f=1., uB=[grid.node(2), 0.])
import pygimli as pg
import pygimli.solver as solver

import matplotlib.pyplot as plt
import numpy as np


dx = 0.005
x = np.arange(0, 1., dx )

"""
    Start modelling code
"""

h = 1./20.
grid = pg.createGrid(x=np.arange(-1.0, 1.0+h, h))
#grid = grid.createP2()
times = np.arange(0, 2., (h)*0.5)
print(grid)

dirichletBC = [[1, 0], # top
               [2, 0]] #bottom

u = np.zeros((len(times), grid.nodeCount()))
v = np.zeros((len(times), grid.nodeCount()))
k = times[1]-times[0]

u[0,0] = 0.0
v[0,0] = 0.0
e = np.zeros(len(times))
A = solver.createStiffnessMatrix(grid)
示例#43
0
import pygimli as pg
import pygimli.solver as solver

import matplotlib.pyplot as plt
import numpy as np


dx = 0.005
x = np.arange(0, 1., dx )

"""
    Start modelling code
"""

h = 1./20.
grid = pg.createGrid(x=np.arange(-1.0, 1.0+h, h))
#grid = grid.createP2()
times = np.arange(0, 2., (h)*0.5)
print(grid)

dirichletBC = [[1, 0], # top
               [2, 0]] #bottom

u = np.zeros((len(times), grid.nodeCount()))
v = np.zeros((len(times), grid.nodeCount()))
k = times[1]-times[0]

u[0,0] = 0.0
v[0,0] = 0.0
e = np.zeros(len(times))
A = solver.createStiffnessMatrix(grid)
from pygimli.mplviewer import drawMesh, drawModel, drawField, drawStreams
from pygimli.meshtools import createMesh
from solverFVM import solveFiniteVolume, createFVPostProzessMesh, diffusionConvectionKernel

import matplotlib.pyplot as plt
import numpy as np

swatch = pg.Stopwatch(True)

x = np.linspace(-1.0, 1.0, 41)
y = np.linspace( 0.0, 1.0, 21)
dx = x[1] - x[0]
dy = y[1] - y[0]
print(dx,dy)

grid = pg.createGrid(x=x, y=y)

# force vector per cell
f = pg.RVector(grid.cellCount(), 0.0)
#f[grid.findCell([-0.85, 0.55]).id()]=10.0

# velocity per cell [x-direction, y-direction]
vC = np.array(list(map(lambda p_: [ (2.*p_[1] *(1.0 -p_[0]**2)),
                                   (-2.*p_[0] *(1.0 -p_[1]**2))],
                       grid.cellCenters())))

vB = np.array(list(map(lambda p_: [ (2.*p_[1] *(1.0 -p_[0]**2)),
                                   (-2.*p_[0] *(1.0 -p_[1]**2))],
                       grid.boundaryCenters())))

ud0=10
示例#45
0
    poly = pg.Mesh(2)
    nodes = [poly.createNode(b) for b in boundary]

    poly.createEdge(nodes[0], nodes[1], 1) # dirichlet (inflow)
    poly.createEdge(nodes[1], nodes[2], 3) # hom neumann (outflow)
    poly.createEdge(nodes[2], nodes[3], 2) # hom dirichlet (isolation)
    poly.createEdge(nodes[3], nodes[0], 4) # hom dirichlet (isolation)

    mesh = createMesh(poly, quality=34, area=0.05, smooth=[0,10])
    return mesh

dx = 0.2
x = np.arange(-20, 20., dx)
y = np.arange(-20, 0.0, dx)[::-1]

mesh = pg.createGrid(x=x, y=y)
mesh = createMesh2()
print(mesh)

h = pg.median(mesh.boundarySizes())

v1 = 1000
v2 = 3000
tmax = 10.1/v1

z = 2.
f0 = 1000.0 # A low wavelength of 50 Hz

velocities = pg.RVector(mesh.cellCount(), v1)

for c in mesh.cells():
    S[1, 1] += aE

    S[N + 1, N + 1] += 1.0
    S[N, N + 1] += -aW
    S[N, N] += aW

    rhs[0] += uDir[0]
    rhs[N + 1] += uDir[1]

    return S, rhs


x = np.linspace(0.0, 1.0, 11)
dx = x[1] - x[0]

grid = pg.createGrid(x=x)
N = grid.cellCount()

# force vector per cell
f = pg.RVector(grid.cellCount(), 0.0)
# diffusions coefficient
a = pg.RVector(grid.cellCount(), 2.1)
# velocity per cell [x-direction]
v = pg.RVector(grid.cellCount(), 20.1)

print("Peclet-number:", v[0] / (a[0] / dx))

ud0 = 0
udN = 1

示例#47
0
We use the preceding example (Poisson equation on the unit square) but want to specify different boundary conditions on the four sides.

Again, we first import numpy and pyplot, pygimli, the solver and some plotting functions.
Then we create a 50x50 node grid to solve on.
"""

import numpy as np
import matplotlib.pyplot as plt

import pygimli as pg
from pygimli.solver import solvePoisson
from pygimli.viewer import showMesh
from pygimli.mplviewer import drawMesh, drawStreamLines

grid = pg.createGrid(x=np.linspace(-1.0, 1.0, 50), y=np.linspace(-1.0, 1.0, 50))

"""
We start considering inhomogeneous Dichlet boundary conditions (BC).
There are different ways of specifying BCs. 
They can be maps from markers to values, explicit functions or implicit (lambda) functions as exemplified in the next example.

The boundary 1 (top) and 2 (left) are directly mapped to the values 1.0 and 2.0.
On side 3 (bottom) a lambda function 3+x is used (p is the boundary position and p[0] its x coordinate.
On side 4 (right) a function uDirichlet is used that simply returns 4.0 in this example but can compute everything as a function of the individual boundaries b.
"""

def uDirichlet(b):
    '''
        Return a solution value for coordinate p.
    '''
示例#48
0
#!/usr/bin/env python
import numpy as np
import pygimli as pg

# Dummy data container
data = pg.DataContainer()
data.createSensor([0.0, 0.0])
data.createSensor([1.0, 2.0])
data.resize(1)
data.set("s", pg.RVector(1, 1.0))
data.set("g", pg.RVector(1, 2.0))
data.registerSensorIndex("s")
data.registerSensorIndex("g")

# Without secondary nodes
mesh = pg.createGrid([0, 1, 2], [0, 1, 2])

# Slowness
slo = [1, 2, 1, 4]


def test_withoutSecNodes():
    fop = pg.TravelTimeDijkstraModelling(mesh, data)
    t_normal = fop.response(slo)
    np.testing.assert_allclose(t_normal, 1 + np.sqrt(2))


def test_withSecNodes():
    mesh2 = mesh.createMeshWithSecondaryNodes(n=3)
    fop = pg.TravelTimeDijkstraModelling(mesh2, data)
    t_refined = fop.response(slo)
示例#49
0
nu = .1
dt = .001

u = np.zeros((ny, nx))
v = np.zeros((ny, nx))
p = np.zeros((ny, nx))
b = np.zeros((ny, nx))

nt = 200
u, v, p = cavityFlow(nt, u, v, dt, dx, dy, p, rho, nu)
# fig = plt.figure(figsize=(11,7), dpi=100)
# ax1 = fig.add_subplot(1,3,1)
# ax2 = fig.add_subplot(1,3,2)
# ax3 = fig.add_subplot(1,3,3)

grid = pg.createGrid(x, y)
fig = plt.figure()
ax1 = fig.add_subplot(1, 3, 1)
ax2 = fig.add_subplot(1, 3, 2)
ax3 = fig.add_subplot(1, 3, 3)

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

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

vel = np.vstack([np.array((u.T).flat), np.array((v.T).flat)]).T
示例#50
0

###############################################################################
#
# Define function for the current source term
# :math:`\delta(x-pos), \int f(x) \delta(x-pos)=f(pos)=N(pos)`
# Right hand side entries will be shape functions(pos)
#

def pointSource(cell, f, userData):
    sourcePos = userData['sourcePos']

    if cell.shape().isInside(sourcePos):
        f.setVal(cell.N(cell.shape().rst(sourcePos)), cell.ids())

grid = pg.createGrid(x=np.linspace(-10.0, 10.0, 21), y=np.linspace(-15.0, .0, 16))

#grid = grid.createH2()
grid = grid.createP2()

sourcePosA = [-5.0, -4.0]
sourcePosB = [ 5.0, -4.0]

neumannBC = [[1, mixedBC], #left boundary
             [2, mixedBC], #right boundary
             [4, mixedBC]] #bottom boundary

k = 1e-3
u = solve(grid, a=1, b=k*k, f=pointSource,
          duB=neumannBC,
          userData={'sourcePos': sourcePosA, 'k': k},
See: :py:mod:`pygimli.viewer`

Discussion: FEM is less suited for problems with piece-wise (element) constant
solutions, because linear shape functions demand twice differentiable solution.
For diffusion and wave equation with partially starting gradients = 0 you can
obtain numeric undulations (acausal overshoots) caused by the shape functions.

"""

import pygimli as pg
import pygimli.solver as solver
import matplotlib.pyplot as plt
import numpy as np

grid = pg.createGrid(x=np.linspace(0.0, 1.0, 100))
times = np.arange(0, 1.0, 0.04)

dirichletBC = [[1, 0],  # top
               [2, 0]]  # bottom

probeID = int(grid.nodeCount() / 2)

###############################################################################
# For this case we have an analytical solution:
#
# .. math::
#
#     u(t,x) = \e^{-\pi^2 t} \sin(\pi x)
#
#
            break

    if verbose:
        print(str(i) + ": " + str(preCNorm[-1]))
    return velocity, pressure, preCNorm, divVNorm

if __name__ == '__main__':

    N = 21  # 21 reference
    maxIter = 11  # 11 reference
    Nx = N
    Ny = N

    x = np.linspace(-1.0, 1.0, Nx + 1)
    y = np.linspace(-1.0, 1.0, Ny + 1)
    grid = pg.createGrid(x=x, y=y)

    a = pg.RVector(grid.cellCount(), 1.0)

    b7 = grid.findBoundaryByMarker(1)[0]
    for b in grid.findBoundaryByMarker(1):
        if b.center()[1] < b.center()[1]:
            b7 = b
    b7.setMarker(7)

    swatch = pg.Stopwatch(True)
    velBoundary = [[1, [0.0, 0.0]],
                   [2, [0.0, 0.0]],
                   [3, [1.0, 0.0]],
                   [4, [0.0, 0.0]],
                   [7, [0.0, 0.0]]]
示例#53
0
def createFopWithParaDomain(paraRefine=0, ncpu=6):
    """Create Forward operator and synthetic data."""
    tMax = 345600 * 3
    satSteps = 800 * 2
    ertSteps = 10

    synthPath = 'synth/'

    synthArea = 0.1
    paraArea = 0.1

    simulateSynth(model=[1e-8, 5e-3, 1e-4, 8e-4],
                  tMax=tMax,
                  satSteps=satSteps,
                  ertSteps=ertSteps,
                  area=synthArea,
                  synthPath=synthPath)

    fop = HydroGeophysicalModelling(mesh=None, tMax=tMax,
                                    satSteps=satSteps,
                                    ertSteps=ertSteps,
                                    verbose=1)

    rhoaR = np.load(synthPath + 'synthRhoaRatio.npy')
    err = np.load(synthPath + 'synthErr.npy')

    fop.setVerbose(True)
    fop.setMultiThreadJacobian(ncpu)

    paraMesh = pg.createGrid(x=[-20, -10, 0, 10, 20], y=[-16, -8, -2, 0])
    # top Boundary Marker
    for i, b in enumerate(paraMesh.findBoundaryByMarker(4)):
        b.setMarker(8)
    # right Boundary Marker
    for i, b in enumerate(paraMesh.findBoundaryByMarker(2)):
        b.setMarker(7 - i)
    # bottom Boundary Marker
    for i, b in enumerate(paraMesh.findBoundaryByMarker(3)):
        b.setMarker(4)
    # left boundary Marker
    for i, b in enumerate(paraMesh.findBoundaryByMarker(1)):
        b.setMarker(3-i)

#    ax, _ = pg.show(paraMesh)
#    pg.mplviewer.drawMeshBoundaries(ax=ax, mesh=paraMesh)
#    pg.wait()

    paraMesh.cell(0).setMarker(0)  # bottom
    paraMesh.cell(1).setMarker(0)  # bottom
    paraMesh.cell(2).setMarker(0)  # bottom
    paraMesh.cell(3).setMarker(0)  # bottom
    paraMesh.cell(4).setMarker(2)  # center
    paraMesh.cell(5).setMarker(2)  # center
    paraMesh.cell(6).setMarker(2)  # center
    paraMesh.cell(7).setMarker(2)  # center
    paraMesh.cell(8).setMarker(1)  # top
    paraMesh.cell(9).setMarker(1)  # top
    paraMesh.cell(10).setMarker(1)  # top
    paraMesh.cell(11).setMarker(1)  # top

    if paraRefine:
        for i in range(paraRefine):
            paraMesh = paraMesh.createH2()

        paraCount = 2
        for c in paraMesh.cells():
            if c.marker() > 1:
                c.setMarker(paraCount)
                paraCount += 1

        fop.setMesh(paraMesh)

        for i in range(fop.regionManager().regionCount()):
            fop.regionManager().region(i).setSingle(1)
    else:
        fop.setMesh(paraMesh)
        fop.createRefinedForwardMesh(refine=False, pRefine=False)

    fopMesh = pg.meshtools.createMesh(fop.regionManager().paraDomain(),
                                      area=paraArea, smooth=[1, 10])

    fop.setVerbose(True)
    fop.setMesh(fopMesh, ignoreRegionManager=False)
    for i in range(fop.regionManager().regionCount()):
        fop.regionManager().region(i).setSingle(1)

    return fop, rhoaR, err, paraMesh
示例#54
0
        b = pg.findBoundary(c.boundaryNodes(bi))
        # print(b.norm(c).dot(F[b.id()]))
        ret += b.norm(c).dot(F[b.id()]) * b.size()

    return ret


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)
示例#55
0
 def test_MeshStr(self):
     mesh = pg.createGrid(2, 2, 2)
     print(mesh.node(0))
def calc(out, mesh, density, viscosity):
    print(mesh)
            
    velBoundary=[
                [1, [0.0,  'nan']],
                [2, [0.0,  'nan']],
                [3, ['nan',  0.0]],
                [4, ['nan',  0.0]]
                ]
    preBoundary=[[1, 0.0],
                [2, 0.0],
                [3, 0.0],
                [4, 0.0],
                ]


    densMatrix = pg.RMatrix()
    vels = []

    swatch = pg.Stopwatch(True)
    class WS():
        pass

    wsfv = WS()

    ax,_ = pg.show(mesh, density)

    v = 1
    nSteps = 3000
        
    dt = 0.1 * v
    dtSteps = 20
    
    meshC = pg.createGrid(x=np.linspace(-10, 10, 21),
                          y=np.linspace(0, 20, 21))

    vel=None
    pre=None
    
    
    for i in range(nSteps):
        print(i, 'dens', min(density), max(density), "t:", dt*i)
        
        densMatrix.push_back(density)
        
        if v > 1:
            viscosity=1.0 * density #v3
        elif v < 1:
            viscosity=1.0 / density #v3
        else:
            viscosity=1.0
            
        vel, pre, pCNorm, divVNorm = solver.solveStokes(mesh, 
                                                        velBoundary=velBoundary,
                                                        preBoundary=preBoundary,
                                                        viscosity=viscosity,
                                                        density=density,
                                                        pre0 = pre,
                                                        vel0 = vel,
                                                        f=[density*0, (density-1.0)*-9.81],
                                                        maxIter=1000,
                                                        tol=1e-6,
                                                        verbose=1,
                                                        vRelax=0.1,
                                                        pRelax=0.1,
                                                        ws=wsfv)
        vels.append(vel)
        
        print("stokes:" , swatch.duration(True), "div V: ", divVNorm[-1])
        dens2 = solver.solveFiniteVolume(mesh, a=1./500, b=0.0, u0=density, vel=vel,
                                        times=np.linspace(0, dt, dtSteps), 
                                        #uBoundary=[4, 0],
                                        scheme='PS', verbose=0)
        print("Convekt:" , swatch.duration(True))
        density=dens2[-1]
        
        ax.clear()
        pg.show(mesh, density, axes=ax)
        pg.show(mesh, vel, coarseMesh=meshC, axes=ax, color='white')

    mesh.save(out)
    meshC.save(out + 'C')
    densMatrix.save(out + 'density.bmat')
    np.save(out+'velo.bmat', vels)
示例#57
0
from matplotlib.patheffects import withStroke

def circle(x, y, text=None, radius=0.15, c="blue"):
    circle = Circle((x, y), radius, clip_on=False, zorder=10, linewidth=1,
                    edgecolor='black', facecolor=(0, 0, 0, .0125),
                    path_effects=[withStroke(linewidth=5, foreground='w')])
    ax.add_artist(circle)
    ax.plot(x, y, color=c, marker=".")
    ax.text(x, y - (radius + 0.05), text, backgroundcolor="white",
            ha='center', va='top', weight='bold', color=c)

################################################################################
# We now import pygimli and create simple grid/mesh with 3x3 cells.

import pygimli as pg
m = pg.createGrid(4,4)

################################################################################
# The following code creates the main plot and shows how the different mesh
# entities can be called.

# Create matplotlib figure and set size
fig, ax = plt.subplots(figsize=(8,8), dpi=90)
ax.set_title("The anatomy of a pyGIMLi mesh", fontweight="bold")

# Visualize mesh with the generic pg.show command
pg.show(m, ax=ax)

# Number all cells
for cell in m.cells():
    node = cell.allNodes()[2]
示例#58
0
    def test_Dirichlet(self):
        """
        """
        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

        def _testP2_(mesh, show=False):
            """ Laplace u = 2 solves u = x² for u(r=0)=0 and u(r=1)=1
                Test for u == exact x² for P2 base functions
            """
            meshp2 = mesh.createP2()
            u = pg.solve(meshp2, f=-2, bc={'Dirichlet': [[1, 0], [2, 1]]})

            # find test pos different from node pos
            meshTests = mesh.createH2()
            meshTests = meshTests.createH2()

            c = [c.center() for c in meshTests.cells()]
            startPos = meshTests.node(0).pos()

            if mesh.dim() == 2:
                c = [b.center() for b in meshTests.boundaries(meshTests.boundaryMarkers()==4)]

            c.sort(key=lambda c_: c_.distance(startPos))
            ui = pg.interpolate(meshp2, u, c)
            xi = pg.utils.cumDist(c) + startPos.distance(c[0])       

            if show:
                pg.plt.plot(xi, ui)
                pg.plt.plot(xi, xi**2)
                pg.wait()
            
            np.testing.assert_allclose(ui, xi**2)
     
        _testP1_(pg.createGrid(x=np.linspace(0, 1, 11)), show=False) #1D
        _testP1_(pg.createGrid(x=np.linspace(-2, 1, 11), y=np.linspace(0, 1, 11))) #2D reg quad
        _testP1_(pg.createGrid(x=np.linspace(-0.04, 0.01, 11), y=np.linspace(-0.4, 0, 11))) #2D scaled
        _testP1_(pg.createGrid(x=np.linspace(-2, 1, 11), y=np.linspace( 0, 1, 11),
                             z=np.linspace( 0, 1, 11))) #3D

        mesh = pg.meshtools.createMesh(pg.meshtools.createWorld(start=[4, -4], end=[6, -6], worldMarker=0), area=0.1)
        mesh.setBoundaryMarkers(np.array([0,1,3,2,4])[mesh.boundaryMarkers()])
        _testP1_(mesh, show=False) #2D tri

        grid = pg.createGrid(x=np.linspace(-2, 2, 11), y=np.linspace(0, 1, 11))
        grid.rotate([0, 0, np.pi/4])
        #can't find proper test for this rotated case
        #v = _testP1_(grid, show=False) #2D reg - rotated
        
        # P2 tests
        mesh = pg.meshtools.createMesh(pg.meshtools.createWorld(start=[0, -4], end=[1, -6], worldMarker=0), area=0.1)
        mesh.setBoundaryMarkers(np.array([0,1,3,2,4])[mesh.boundaryMarkers()])
        _testP2_(mesh, show=False) #2D tri
        _testP2_(pg.createGrid(x=np.linspace(0, 1, 11)), show=0) #1D
        _testP2_(pg.createGrid(x=np.linspace(0, 1, 11), y=np.linspace(0, 1, 11)), show=0) #2D reg quad
        grid = pg.createGrid(x=np.linspace(0, 1, 11), y=np.linspace(0, 1, 11))
        grid.rotate([0, 0, np.pi/4])
        v = _testP2_(grid, show=False) #2D reg - rotated
示例#59
0
                (r2A * r1A * (r1A + r2A))
                   
    elif r1A > 1e-12 and r2A > 1e-12:
        return k * ((r1.dot(n)) / r1A * pg.math.besselK1(r1A * k) +
                    (r2.dot(n)) / r2A * pg.math.besselK1(r2A * k)) / \
        (pg.math.besselK0(r1A * k) + pg.math.besselK0(r2A * k))
    else:
        return 0.

def pointSource(cell, f, userData):
    sourcePos = userData['sourcePos']

    if cell.shape().isInside(sourcePos):
        f.setVal(cell.N(cell.shape().rst(sourcePos)), cell.ids())
        
grid = pg.createGrid(x=np.linspace(-10.0, 10.0, 50.),
                     y=np.linspace(-15.0,   .0, 50.))

#a = pg.Vector(grid.cellCount(),1)
a = np.ones(grid.cellCount())
for c in grid.cells():
    if c.center()[1] < -5:
        a[c.id()] = 0.1        

#grid = grid.createH2()
#grid = grid.createP2()

sourcePosA = [-5.0, -4.0]
sourcePosB = [ 5.0, -4.0]

neumannBC = [[1, mixedBC], #left boundary
             [2, mixedBC], #right boundary
    a2.legend(loc='best')


fig = pg.plt.figure(figsize=(8,8))
ax = [fig.add_subplot(2, 2, i) for i in range(1, 5)]

# Horizontal cylinder

ga = gradUCylinderHoriz(pnts, radius, rho, pos=pos)
gza = gradGZCylinderHoriz(pnts, radius, rho, pos=pos)

circ = createCircle([0, -depth], radius=radius, marker=2, area=0.1,
                    segments=32)
g, gz = solveGravimetry(circ, rho, pnts, complete=True)

plot(x, ax[0], ga, gza, ax[1], g, gz)

# Half plate

thickness = 0.1

# mesh = pg.createGrid(x=[-2,2], y=[-2,2], z=[-3,-7])
mesh = pg.createGrid(x=np.linspace(0, 5000, 2),
                     y=[-depth-thickness/2.0, -depth+thickness/2.0])

ga = gradUHalfPlateHoriz(pnts, thickness, rho, pos=[0, -depth])
gza = gradGZHalfPlateHoriz(pnts, thickness, rho, pos=[0, -depth])
g, gz = solveGravimetry(mesh, rho, pnts, complete=True)

plot(x, ax[2], ga, gza, ax[3], g, gz)