Exemple #1
0
def run_test():
    #meshfile = expanduser(join(mfem_path, 'data', 'semi_circle.mesh'))
    meshfile = "../data/amr-quad.mesh"
    mesh = mfem.Mesh(meshfile, 1, 1)
    dim = mesh.Dimension()
    sdim = mesh.SpaceDimension()
    fec = mfem.H1_FECollection(1, dim)
    fespace = mfem.FiniteElementSpace(mesh, fec, 1)
    print('Number of finite element unknowns: ' + str(fespace.GetTrueVSize()))

    c = mfem.ConstantCoefficient(1.0)
    gf = mfem.GridFunction(fespace)
    gf.ProjectCoefficient(c)

    print("write mesh to STDOUT")
    mesh.Print(mfem.STDOUT)
    print("creat VTK file to file")
    mesh.PrintVTK('mesh.vtk', 1)
    print("creat VTK to STDOUT")
    mesh.PrintVTK(mfem.STDOUT, 1)
    print("save GridFunction to file")
    gf.Save('out_test_gridfunc.gf')
    gf.SaveVTK(mfem.wFILE('out_test_gridfunc1.vtk'), 'data', 1)
    print("save GridFunction to file in VTK format")
    gf.SaveVTK('out_test_gridfunc2.vtk', 'data', 1)
    print("Gridfunction to STDOUT")
    gf.Save(mfem.STDOUT)

    o = io.StringIO()
    count = gf.Save(o)
    count2 = gf.SaveVTK(o, 'data', 1)
    print("length of data ", count, count2)
    print('result: ', o.getvalue())
Exemple #2
0
def save_scaled_jacobian(filename, mesh, sd=-1):

    sj = get_scaled_jacobian(mesh, sd=sd)

    fec = mfem.L2_FECollection(0, mesh.Dimension())
    fes = mfem.FiniteElementSpace(mesh, fec)

    vec = mfem.Vector(sj)
    gf = mfem.GridFunction(fes, vec.GetData())

    gf.Save(filename)
Exemple #3
0
def run_test():
    #meshfile =expanduser(join(mfem_path, 'data', 'beam-tri.mesh'))
    meshfile = expanduser(join(mfem_path, 'data', 'semi_circle.mesh'))
    mesh = mfem.Mesh(meshfile, 1, 1)
    dim = mesh.Dimension()
    sdim = mesh.SpaceDimension()
    fec = mfem.H1_FECollection(1, dim)
    fespace = mfem.FiniteElementSpace(mesh, fec, 1)
    print('Number of finite element unknowns: ' + str(fespace.GetTrueVSize()))

    c = mfem.ConstantCoefficient(1.0)
    gf = mfem.GridFunction(fespace)
    gf.ProjectCoefficient(c)

    gf.Save('out_test_gridfunc.gf')
Exemple #4
0
def run_test():
    #meshfile = expanduser(join(mfem_path, 'data', 'semi_circle.mesh'))
    meshfile = "../data/amr-quad.mesh"
    mesh = mfem.Mesh(meshfile, 1, 1)
    dim = mesh.Dimension()
    sdim = mesh.SpaceDimension()
    fec = mfem.H1_FECollection(1, dim)
    fespace = mfem.FiniteElementSpace(mesh, fec, 1)
    print('Number of finite element unknowns: ' + str(fespace.GetTrueVSize()))

    c = mfem.ConstantCoefficient(1.0)
    gf = mfem.GridFunction(fespace)
    gf.ProjectCoefficient(c)

    odata = gf.GetDataArray().copy()

    gf.Save("out_test_gz.gf")
    gf2 = mfem.GridFunction(mesh, "out_test_gz.gf")
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, "text file does not agree with original")

    gf.Save("out_test_gz.gz")
    gf2.Assign(0.0)
    gf2 = mfem.GridFunction(mesh, "out_test_gz.gz")
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, ".gz file does not agree with original")

    gf.Print("out_test_gz.dat")
    gf2.Assign(0.0)
    gf2.Load("out_test_gz.dat", gf.Size())
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, ".dat file does not agree with original")

    gf.Print("out_test_gz.dat.gz")
    gf2.Assign(0.0)
    gf2.Load("out_test_gz.dat.gz", gf.Size())
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, ".dat file does not agree with original (gz)")

    import gzip
    import io
    gf.Print("out_test_gz.dat2.gz")
    with gzip.open("out_test_gz.dat2.gz", 'rt') as f:
        sio = io.StringIO(f.read())
    gf3 = mfem.GridFunction(fespace)
    gf3.Load(sio, gf.Size())
    odata3 = gf3.GetDataArray().copy()
    check(odata, odata3, ".dat file does not agree with original(gz-io)")

    c = mfem.ConstantCoefficient(2.0)
    gf.ProjectCoefficient(c)
    odata = gf.GetDataArray().copy()

    o = io.StringIO()
    gf.Print(o)
    gf2.Load(o, gf.Size())
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, "StringIO does not agree with original")

    print("GridFunction .gf, .gz .dat and StringIO agree with original")

    mesh2 = mfem.Mesh()
    mesh.Print("out_test_gz.mesh")
    mesh2.Load("out_test_gz.mesh")
    check_mesh(mesh, mesh2, ".mesh does not agree with original")

    mesh2 = mfem.Mesh()
    mesh.Print("out_test_gz.mesh.gz")
    mesh2.Load("out_test_gz.mesh.gz")

    check_mesh(mesh, mesh2, ".mesh.gz does not agree with original")

    mesh3 = mfem.Mesh()
    mesh.PrintGZ("out_test_gz3.mesh")
    mesh3.Load("out_test_gz3.mesh")
    check_mesh(mesh, mesh3,
               ".mesh (w/o .gz exntension) does not agree with original")

    o = io.StringIO()
    mesh2 = mfem.Mesh()
    mesh.Print(o)
    mesh2.Load(o)
    check_mesh(mesh, mesh2, ".mesh.gz does not agree with original")

    print("Mesh .mesh, .mesh.gz and StringIO agree with original")

    print("PASSED")
Exemple #5
0
for i in range(dim - 1):
    f.Set(i, mfem.ConstantCoefficient(0.0))

pull_force = mfem.Vector([0] * pmesh.bdr_attributes.Max())
pull_force[1] = -1.0e-2
f.Set(dim - 1, mfem.PWConstCoefficient(pull_force))

b = mfem.ParLinearForm(fespace)
b.AddBoundaryIntegrator(mfem.VectorBoundaryLFIntegrator(f))
print('r.h.s. ...')
b.Assemble()

# 10. Define the solution vector x as a parallel finite element grid
#     function corresponding to fespace. Initialize x with initial guess of
#     zero, which satisfies the boundary conditions.
x = mfem.GridFunction(fespace)
x.Assign(0.0)

# 11. Set up the parallel bilinear form a(.,.) on the finite element space
#     corresponding to the linear elasticity integrator with piece-wise
#     constants coefficient lambda and mu.

lamb = mfem.Vector(pmesh.attributes.Max())
lamb.Assign(1.0)
lamb[0] = lamb[1] * 50
lambda_func = mfem.PWConstCoefficient(lamb)
mu = mfem.Vector(pmesh.attributes.Max())
mu.Assign(1.0)
mu[0] = mu[1] * 50
mu_func = mfem.PWConstCoefficient(mu)
a = mfem.ParBilinearForm(fespace)
def eval_shape(order = 1, refine = 5, elem_type = 0,
               fec = 'ND'):

    if fec == 'ND':
        fec_type = mfem.ND_FECollection
        if order < 1: assert False, "ND order is 1 and above"        
    elif fec == 'RT':
        fec_type = mfem.RT_FECollection
    elif fec == 'H1':
        fec_type = mfem.H1_FECollection
        if order < 1: assert False, "H1 order is 1 and above"
    elif fec == 'L2':
        fec_type = mfem.L2_FECollection
    else:
        assert False, "unknown basis"
        
    if elem_type == 0:
        Nvert = 3; Nelem = 1; spaceDim = 2
    elif elem_type == 1:    
        Nvert = 4; Nelem = 1; spaceDim = 2

    mesh = mfem.Mesh(2, Nvert, Nelem, 0, spaceDim)

    if elem_type == 0:
        tri_v = [[1.,  0.3 ], [0.,  1.,], [0, 0]]
        tri_e = [[0, 1, 2], ]
        for j in range(Nvert):
            mesh.AddVertex(tri_v[j])
        for j in range(Nelem):
            mesh.AddTriangle(tri_e[j], j+1)
        mesh.FinalizeTriMesh(1,1, True)
    else:
        quad_v = [[-1, -1.3, ], [+1, -1, ], [+1, +1, ], [-1, +1,]]
        quad_e = [[0, 1, 2, 3]]
        for j in range(Nvert):
            mesh.AddVertex(quad_v[j])
        for j in range(Nelem):
            mesh.AddQuad(quad_e[j], j+1)
        mesh.FinalizeQuadMesh(1,1, True)

    #mesh.PrintToFile('plot_basis.mesh', 8)

    fe_coll = fec_type(order, spaceDim)
    fespace = mfem.FiniteElementSpace(mesh, fe_coll)

    x = mfem.GridFunction(fespace)
    x.Assign(0.0)
    x[0] = 1.0

    idx = 0
    geom = mesh.GetElementBaseGeometry(idx)
    T = mesh.GetElementTransformation(idx)
    fe = fespace.GetFE(idx)
    fe_nd = fe.GetDof()

    ir = fe.GetNodes()
    npt = ir.GetNPoints()
    dof = np.vstack([T.Transform(ir.IntPoint(i)) for i in range(npt)])
    
    RefG = mfem.GlobGeometryRefiner.Refine(geom, refine, 1);
    ir = RefG.RefPts

    npt = ir.GetNPoints()
    ptx = np.vstack([T.Transform(ir.IntPoint(i)) for i in range(npt)])

    shape = []
    if fec == 'ND' or fec == 'RT':
        mat = mfem.DenseMatrix(fe_nd, spaceDim)
        shape_func = fe.CalcVShape
        for i in range(npt):
            ip = ir.IntPoint(i)
            T.SetIntPoint(ip)
            fe.CalcVShape(T, mat)
            shape.append(mat.GetDataArray().copy())
    else:
        vec = mfem.Vector(fe_nd)
        for i in range(npt):
            ip = ir.IntPoint(i)            
            fe.CalcShape(ip, vec)
            shape.append(vec.GetDataArray().copy())

    return dof, ptx, np.stack(shape)
Exemple #7
0
def run_test():
    #meshfile = expanduser(join(mfem_path, 'data', 'semi_circle.mesh'))
    mesh = mfem.Mesh(3, 3, 3, "TETRAHEDRON")
    mesh.ReorientTetMesh()

    order = 1

    dim = mesh.Dimension()
    sdim = mesh.SpaceDimension()
    fec1 = mfem.H1_FECollection(order, dim)
    fespace1 = mfem.FiniteElementSpace(mesh, fec1, 1)

    fec2 = mfem.ND_FECollection(order, dim)
    fespace2 = mfem.FiniteElementSpace(mesh, fec2, 1)

    print("Element order :", order)

    print('Number of H1 finite element unknowns: ' +
          str(fespace1.GetTrueVSize()))
    print('Number of ND finite element unknowns: ' +
          str(fespace2.GetTrueVSize()))

    print("Checking scalar")

    gf = mfem.GridFunction(fespace1)
    c1 = mfem.NumbaFunction(s_func, sdim).GenerateCoefficient()
    c2 = s_coeff()

    gf.Assign(0.0)
    start = time.time()
    gf.ProjectCoefficient(c1)
    end = time.time()
    data1 = gf.GetDataArray().copy()
    print("Numba time (scalar)", end - start)

    gf.Assign(0.0)
    start = time.time()
    gf.ProjectCoefficient(c2)
    end = time.time()
    data2 = gf.GetDataArray().copy()
    print("Python time (scalar)", end - start)

    check(data1, data2, "scalar coefficient does not agree with original")

    print("Checking vector")
    gf = mfem.GridFunction(fespace2)
    c3 = mfem.VectorNumbaFunction(v_func, sdim, dim).GenerateCoefficient()
    c4 = v_coeff(dim)

    gf.Assign(0.0)
    start = time.time()
    gf.ProjectCoefficient(c3)
    end = time.time()
    data1 = gf.GetDataArray().copy()
    print("Numba time (vector)", end - start)

    gf.Assign(0.0)
    start = time.time()
    gf.ProjectCoefficient(c4)
    end = time.time()
    data2 = gf.GetDataArray().copy()
    print("Python time (vector)", end - start)

    check(data1, data2, "vector coefficient does not agree with original")

    print("Checking matrix")
    a1 = mfem.BilinearForm(fespace2)
    a2 = mfem.BilinearForm(fespace2)
    c4 = mfem.MatrixNumbaFunction(m_func, sdim, dim).GenerateCoefficient()
    c5 = m_coeff(dim)

    a1.AddDomainIntegrator(mfem.VectorFEMassIntegrator(c4))
    a2.AddDomainIntegrator(mfem.VectorFEMassIntegrator(c5))

    start = time.time()
    a1.Assemble()
    end = time.time()
    a1.Finalize()
    M1 = a1.SpMat()

    print("Numba time (matrix)", end - start)

    start = time.time()
    a2.Assemble()
    end = time.time()
    a2.Finalize()
    M2 = a2.SpMat()
    print("Python time (matrix)", end - start)

    #from mfem.commmon.sparse_utils import sparsemat_to_scipycsr
    #csr1 = sparsemat_to_scipycsr(M1, float)
    #csr2 = sparsemat_to_scipycsr(M2, float)

    check(M1.GetDataArray(), M2.GetDataArray(),
          "matrix coefficient does not agree with original")
    check(M1.GetIArray(), M2.GetIArray(),
          "matrix coefficient does not agree with original")
    check(M1.GetJArray(), M2.GetJArray(),
          "matrix coefficient does not agree with original")

    print("PASSED")
def do_integration(expr, solvars, phys, mesh, kind, attrs,
                   order, num):
    from petram.helper.variables import (Variable,
                                         var_g,
                                         NativeCoefficientGenBase,
                                         CoefficientVariable)
    from petram.phys.coefficient import SCoeff

    st = parser.expr(expr)
    code= st.compile('<string>')
    names = code.co_names

    g = {}
    #print solvars.keys()
    for key in phys._global_ns.keys():
       g[key] = phys._global_ns[key]
    for key in solvars.keys():
       g[key] = solvars[key]

    l = var_g.copy()

    ind_vars = ','.join(phys.get_independent_variables())

    if kind == 'Domain':
        size = max(max(mesh.attributes.ToList()), max(attrs))
    else:
        size = max(max(mesh.bdr_attributes.ToList()), max(attrs))
        
    arr = [0]*(size)
    for k in attrs:
        arr[k-1] = 1
    flag = mfem.intArray(arr)

    s = SCoeff(expr, ind_vars, l, g, return_complex=False)

    ## note L2 does not work for boundary....:D
    if kind == 'Domain':
        fec = mfem.L2_FECollection(order, mesh.Dimension())
    else:
        fec = mfem.H1_FECollection(order, mesh.Dimension())

    fes = mfem.FiniteElementSpace(mesh, fec)
    one = mfem.ConstantCoefficient(1)

    gf = mfem.GridFunction(fes)
    gf.Assign(0.0)

    if kind == 'Domain':
        gf.ProjectCoefficient(mfem.RestrictedCoefficient(s, flag))
    else:
        gf.ProjectBdrCoefficient(mfem.RestrictedCoefficient(s, flag), flag)

    b = mfem.LinearForm(fes)
    one = mfem.ConstantCoefficient(1)
    if kind == 'Domain':
        itg = mfem.DomainLFIntegrator(one)
        b.AddDomainIntegrator(itg)
    else:
        itg = mfem.BoundaryLFIntegrator(one)
        b.AddBoundaryIntegrator(itg)

    b.Assemble()

    from petram.engine import SerialEngine
    en = SerialEngine()
    ans = mfem.InnerProduct(en.x2X(gf), en.b2B(b))
    
    if not np.isfinite(ans):
        print("not finite", ans, arr)
        print(size, mesh.bdr_attributes.ToList())
        from mfem.common.chypre import LF2PyVec, PyVec2PyMat, Array2PyVec, IdentityPyMat
        #print(list(gf.GetDataArray()))
        print(len(gf.GetDataArray()), np.sum(gf.GetDataArray()))
        print(np.sum(list(b.GetDataArray())))
    return ans