Exemple #1
0
    def ImplicitSolve(self, dt, vx, dvx_dt):
        sc = self.Height() / 2
        v = mfem.Vector(vx, 0, sc)
        x = mfem.Vector(vx, sc, sc)
        dv_dt = mfem.Vector(dvx_dt, 0, sc)
        dx_dt = mfem.Vector(dvx_dt, sc, sc)
        #print("v = ")
        #v.Print()
        #print("x = ")
        #x.Print()
        # By eliminating kx from the coupled system:
        # kv = -M^{-1}*[H(x + dt*kx) + S*(v + dt*kv)]
        # kx = v + dt*kv
        # we reduce it to a linear equation for kv,
        # represented by the backward_euler_oper
        ndt = -1 * dt
        self.VX = mfem.Add(1.0, self.Mmat, ndt, self.Smat)
        self.VX_solver.SetOperator(self.VX)

        #add_vector(x, dt, dv_dt, self.w)
        self.Kmat.Mult(x, self.z)
        #self.S.TrueAddMult(v, self.z)
        self.Smat.Mult(v, self.tmpVec)
        add_vector(self.z, 1.0, self.tmpVec, self.z)
        self.z.Neg()
        self.z += self.Bx
        self.z += self.Bv
        self.VX_solver.Mult(self.z, dv_dt)
        add_vector(v, dt, dv_dt, dx_dt)
Exemple #2
0
 def __init__(self, M, S, H):
     mfem.PyOperator.__init__(self, M.ParFESpace().TrueVSize())
     self.M = M
     self.S = S
     self.H = H
     self.Jacobian = None
     h = M.ParFESpace().TrueVSize()
     self.w = mfem.Vector(h)
     self.z = mfem.Vector(h)
     self.dt = 0.0
Exemple #3
0
    def Mult(self, vx, vx_dt):    
        sc = self.Height()/2
        v = mfem.Vector(vx, 0,  sc)
        x = mfem.Vector(vx, sc,  sc)
        dv_dt = mfem.Vector(dvx_dt, 0, sc)
        dx_dt = mfem.Vector(dvx_dt, sc,  sc)

        self.H.Mult(x, z);
        if (self.viscosity != 0.0):  S.TrueAddMult(v, z)
        z.Neg()
        self.M_solver.Mult(z, dv_dt);
        dx_dt = v
Exemple #4
0
 def Mult(self, vx, dvx_dt):
     sc = self.Height() / 2
     v = mfem.Vector(vx, 0, sc)
     x = mfem.Vector(vx, sc, sc)
     dv_dt = mfem.Vector(dvx_dt, 0, sc)
     dx_dt = mfem.Vector(dvx_dt, sc, sc)
     self.K.Mult(x, self.z)
     if (self.viscosity != 0.0):
         self.S.TrueAddMult(v, self.z)
     self.z.Neg()
     self.M_solver.Mult(self.z, dv_dt)
     dx_dt = v
Exemple #5
0
    def Mult(self, vx, vx_dt):
        sc = self.Height() // 2
        v = mfem.Vector(vx, 0, sc)
        x = mfem.Vector(vx, sc, sc)
        dv_dt = mfem.Vector(dvx_dt, 0, sc)
        dx_dt = mfem.Vector(dvx_dt, sc, sc)

        self.H.Mult(x, z)
        if (self.viscosity != 0.0):
            S.TrueAddMult(v, z)
            z.SetSubVector(self.ess_tdof_list, 0.0)
        z.Neg()
        self.M_solver.Mult(z, dv_dt)
        dx_dt = v
Exemple #6
0
def get_vshape(fes, ibdr, mode='Bdr'):
    mesh = fes.GetMesh()

    GetTrans = getattr(fes, methods[mode]['Transformation'])
    GetElement = getattr(fes, methods[mode]['Element'])
    GetVDofs = getattr(fes, methods[mode]['VDofs'])
    GetVDofTrans = getattr(fes, methods[mode]['VDofTransformation'])

    ret = [None]*len(ibdr)
    if len(ibdr) == 0:
        return ret

    # this is to make sure that IntegraitonPoint in Eltrans is
    # set once...
    tr1 = GetTrans(0)
    el = GetElement(0)
    nodes1 = el.GetNodes()
    doftrans = GetVDofTrans(0)
    tr1.SetIntPoint(nodes1.IntPoint(0))

    v0 = mfem.Vector(tr1.GetSpaceDim())

    use_weight = True
    for iii, k1 in enumerate(ibdr):
        tr1 = GetTrans(k1)
        el = GetElement(k1)
        nodes1 = el.GetNodes()
        doftrans = GetVDofTrans(k1)

        m = mfem.DenseMatrix(nodes1.GetNPoints(),
                             tr1.GetSpaceDim())
        shape = [None]*nodes1.GetNPoints()

        vv = mfem.Vector(nodes1.GetNPoints())

        for idx in range(len(shape)):
            tr1.SetIntPoint(nodes1.IntPoint(idx))
            el.CalcVShape(tr1, m)

            if doftrans is not None:
                vv.Assign(0.0)
                vv[idx] = 1
                doftrans.InvTransformPrimal(vv)
                m.MultTranspose(vv, v0)
                shape[idx] = v0.GetDataArray().copy()
            else:
                shape[idx] = m.GetDataArray()[idx, :].copy()
        ret[iii] = shape
    return ret
Exemple #7
0
def add_delta_contribution(obj, engine, a, real = True, is_trans=False, is_conj=False):
    self = obj
    c = self.vt_coeff.make_value_or_expression(self)
    if isinstance(c, str): c = [c]
        
    if real:       
       dprint1("Add "+self.integrator+ " delta (real)" + str(self._sel_index), "c", c)
    else:
       dprint1("Add "+self.integrator+ " delta(imag)" + str(self._sel_index), "c", c)

    cotype = self.coeff_type[0]

    if self.get_root_phys().vdim > 1:
        dim = self.get_root_phys().vdim
    else:
        el_name = self.get_root_phys().element
        dim = self.get_root_phys().geom_dim
    sdim = self.get_root_phys().geom_dim        
 
    integrator = getattr(mfem, self.integrator)
    adder = a.AddDomainIntegrator
            
    for pos in self.pos_value:
        args = list(pos[:sdim])
        if cotype == 'S':
             for b in self.itg_choice():
                if b[0] == self.integrator: break
               
             if not "S*2" in b[3]:
                 if real:
                     args.append(float(np.array(c[0])[0].real))
                 else:
                     args.append(float(np.array(c[0])[0].imag))
                 if args[-1] != 0:
                     d = mfem.DeltaCoefficient(*args)
                     adder(integrator(d))
             else: # so far this is only for an elastic integrator
                 if real:
                     args.append(float(np.array(c[0])[0].real))
                 else:
                     args.append(float(np.array(c[0])[0].imag))
                 d1 = mfem.DeltaCoefficient(*args)
                 if real:
                     args.append(float(np.array(c[0])[1].real))
                 else:
                     args.append(float(np.array(c[0])[1].imag))
                 d2 = mfem.DeltaCoefficient(*args)
                 adder(integrator(d1, d2))                 

        elif cotype == 'V':
            if real:
                direction = np.array(c[0]).real
            else:
                direction = np.array(c[0]).imag              
            args.append(1.0)
            dir = mfem.Vector(direction)
            d = mfem.VectorDeltaCoefficient(dir, *args)
            adder(integrator(d))            
        else:
            assert False, "M and D are not supported for delta coefficient"
Exemple #8
0
    def nodal_values(self, ibele=None, mesh=None, iverts_f=None, **kwargs):
        # iele = None, elattr = None, el2v = None,
        # wverts = None, locs = None, g = None

        g = mfem.Geometry()
        size = len(iverts_f)
        #wverts = np.zeros(size)
        ret = np.zeros((size, self.sdim))
        if ibele is None: return

        ibe = ibele[0]
        el = mesh.GetBdrElement(ibe)
        rule = g.GetVertices(el.GetGeometryType())
        nv = rule.GetNPoints()

        for ibe in ibele:
            T = mesh.GetBdrElementTransformation(ibe)
            bverts = mesh.GetBdrElement(ibe).GetVerticesArray()

            for i in range(nv):
                nor = mfem.Vector(self.sdim)
                T.SetIntPoint(rule.IntPoint(i))
                mfem.CalcOrtho(T.Jacobian(), nor)
                idx = np.searchsorted(iverts_f, bverts[i])

                ret[idx, :] += nor.GetDataArray().copy()
                #wverts[idx] = wverts[idx] + 1

        #for i in range(self.sdim): ret[:,i] /= wvert
        # normalize to length one.
        ret = ret / np.sqrt(np.sum(ret**2, 1)).reshape(-1, 1)

        if self.comp == -1: return ret
        return ret[:, self.comp - 1]
def schur(*names, **kwargs):
    # shucr("A1", "B1", scale=(1.0, 1e3))
    prc = kwargs.pop('prc')
    blockname = kwargs.pop('blockname')

    r0 = prc.get_row_by_name(blockname)
    c0 = prc.get_col_by_name(blockname)
    A0 = prc.get_operator_block(r0, c0)

    scales = kwargs.pop('scale', [1] * len(names))
    print_level = kwargs.pop('print_level', -1)
    for name, scale in zip(names, scales):
        r1 = prc.get_row_by_name(name)
        c1 = prc.get_col_by_name(name)
        B = prc.get_operator_block(r0, c1)
        Bt = prc.get_operator_block(r1, c0)
        Bt = Bt.Copy()
        B0 = get_block(A, r1, c1)
        if use_parallel:
            Md = mfem.HyprePaarVector(MPI.COMM_WORLD, B0.GetGlobalNumRows(),
                                      B0.GetColStarts())
        else:
            Md = mfem.Vector()
        A0.GetDiag(Md)
        Md *= scale
        if use_parallel:
            Bt.InvScaleRows(Md)
            S = mfem.ParMult(B, Bt)
            invA0 = mfem.HypreBoomerAMG(S)
        else:
            S = mfem.Mult(B, Bt)
            invA0 = mfem.DSmoother(S)
        invA0.iterative_mode = False
        invA0.SetPrintLevel(print_level)
    return invA0
Exemple #10
0
    def ncface_values(self,
                      ifaces=None,
                      irs=None,
                      gtypes=None,
                      locs=None,
                      mesh=None,
                      **kwargs):

        size = len(locs)
        ret = np.zeros((size, self.sdim))
        if ifaces is None: return

        nor = mfem.Vector(self.sdim)

        if mesh.Dimension() == 3:
            m = mesh.GetFaceTransformation
        elif mesh.Dimension() == 2:
            m = mesh.GetElementTransformation
        idx = 0
        for i, gtype, in zip(ifaces, gtypes):
            ir = irs[gtype]
            nv = ir.GetNPoints()
            T = m(i)
            for j in range(nv):
                T.SetIntPoint(ir.IntPoint(i))
                mfem.CalcOrtho(T.Jacobian(), nor)
                ret[idx, :] = nor.GetDataArray().copy()
                idx = idx + 1

        from petram.helper.right_broadcast import div

        ret = div(ret, np.sqrt(np.sum(ret**2, -1)))
        if self.comp == -1: return ret
        return ret[:, self.comp - 1]
Exemple #11
0
def get_shape(fes, ibdr, mode='Bdr'):
    mesh = fes.GetMesh()

    use_weight = False
    fec_name = fes.FEColl().Name()
    if (fec_name.startswith('RT') and mode == 'Bdr'):
        use_weight = True
    if (fec_name.startswith('ND')):
        use_weight = False
        # mode == 'Bdr'):
        use_weight = True
        #use_weight = False

    GetTrans = getattr(fes, methods[mode]['Transformation'])
    GetElement = getattr(fes, methods[mode]['Element'])
    GetVDofs = getattr(fes, methods[mode]['VDofs'])

    ret = [None] * len(ibdr)
    for iii, k1 in enumerate(ibdr):
        tr1 = GetTrans(k1)

        weight = tr1.Weight() if use_weight else 1

        el = GetElement(k1)
        nodes1 = el.GetNodes()
        v = mfem.Vector(nodes1.GetNPoints())
        shape = [None] * nodes1.GetNPoints()
        for idx in range(len(shape)):
            el.CalcShape(nodes1.IntPoint(idx), v)
            shape[idx] = v.GetDataArray()[idx]
        ret[iii] = np.array(shape) * weight

    return ret
Exemple #12
0
 def set_point(self, T, ip, g, l, t=None):
     self.x = T.Transform(ip)
     self.t = t
     T.SetIntPoint(ip)
     nor = mfem.Vector(self.sdim)
     mfem.CalcOrtho(T.Jacobian(), nor)
     self.nor = nor.GetDataArray().copy()
Exemple #13
0
def check_inv_doftrans(doftrans):
    Mdoftrans = np.zeros((doftrans.Size(), doftrans.Size()))
    vv = mfem.Vector(doftrans.Size())
    for i in range(doftrans.Size()):
        vv.Assign(0)
        vv[i] = 1
        doftrans.InvTransformPrimal(vv)
        Mdoftrans[:, i] = vv.GetDataArray()
    print(Mdoftrans)
    Mdoftrans = np.zeros((doftrans.Size(), doftrans.Size()))
    for i in range(doftrans.Size()):
        vv.Assign(0)
        vv[i] = 1
        doftrans.TransformPrimal(vv)
        Mdoftrans[:, i] = vv.GetDataArray()
    print(Mdoftrans)
    Mdoftrans = np.zeros((doftrans.Size(), doftrans.Size()))
    for i in range(doftrans.Size()):
        vv.Assign(0)
        vv[i] = 1
        doftrans.InvTransformDual(vv)
        Mdoftrans[:, i] = vv.GetDataArray()
    print(Mdoftrans)

    Mdoftrans = np.zeros((doftrans.Size(), doftrans.Size()))
    for i in range(doftrans.Size()):
        vv.Assign(0)
        vv[i] = 1
        doftrans.TransformDual(vv)
        Mdoftrans[:, i] = vv.GetDataArray()
    print(Mdoftrans)
def schur(*names, **kwargs):
    # schur("A1", "B1", scale=(1.0, 1e3))
    prc = kwargs.pop('prc')
    blockname = kwargs.pop('blockname')

    r0 = prc.get_row_by_name(blockname)
    c0 = prc.get_col_by_name(blockname)

    scales = kwargs.pop('scale', [1] * len(names))
    print_level = kwargs.pop('print_level', -1)

    S = []
    for name, scale in zip(names, scales):
        r1 = prc.get_row_by_name(name)
        c1 = prc.get_col_by_name(name)
        B = prc.get_operator_block(r0, c1)
        Bt = prc.get_operator_block(r1, c0)

        B0 = prc.get_operator_block(r1, c1)
        if use_parallel:
            Bt = Bt.Transpose()
            Bt = Bt.Transpose()
            Md = mfem.HypreParVector(MPI.COMM_WORLD, B0.GetGlobalNumRows(),
                                     B0.GetColStarts())
        else:
            Bt = Bt.Copy()
            Md = mfem.Vector()
        B0.GetDiag(Md)
        Md *= scale
        if use_parallel:

            Bt.InvScaleRows(Md)
            S.append(mfem.ParMult(B, Bt))
        else:
            S.append(mfem.Mult(B, Bt))

    if use_parallel:
        from mfem.common.parcsr_extra import ToHypreParCSR, ToScipyCoo

        S2 = [ToScipyCoo(s) for s in S]
        for s in S2[1:]:
            S2[0] = S2[0] + s
        S = ToHypreParCSR(S2[0].tocsr())
        invA0 = mfem.HypreBoomerAMG(S)

    else:
        from mfem.common.sparse_utils import sparsemat_to_scipycsr

        S2 = [sparsemat_to_scipycsr(s).tocoo() for s in S]
        for s in S2[1:]:
            S2[0] = S2[0] + s
        S = mfem.SparseMatrix(S2.tocsr())
        invA0 = mfem.DSmoother(S)

    invA0.iterative_mode = False
    invA0.SetPrintLevel(print_level)
    invA0._S = S

    return invA0
Exemple #15
0
    def preprocess_params(self, engine):
        ### find normal (outward) vector...
        mesh = engine.get_emesh(mm=self)
        fespace = engine.fespaces[self.get_root_phys().dep_vars[0]]
        nbe = mesh.GetNBE()
        ibe = np.array([
            i for i in range(nbe)
            if mesh.GetBdrElement(i).GetAttribute() == self._sel_index[0]
        ])
        dprint1("idb", ibe)
        el = mesh.GetBdrElement(ibe[0])
        Tr = fespace.GetBdrElementTransformation(ibe[0])
        rules = mfem.IntegrationRules()
        ir = rules.Get(el.GetGeometryType(), 1)
        Tr.SetIntPoint(ir.IntPoint(0))
        nor = mfem.Vector(2)
        mfem.CalcOrtho(Tr.Jacobian(), nor)

        self.norm = nor.GetDataArray().copy()
        self.norm = self.norm / np.sqrt(np.sum(self.norm**2))

        dprint1("Normal Vector " + list(self.norm).__repr__())

        ### find rectangular shape

        edges = np.array([mesh.GetBdrElementEdges(i)[0]
                          for i in ibe]).flatten()
        d = {}
        for x in edges:
            d[x] = x in d
        edges = [x for x in d.keys() if not d[x]]
        ivert = [mesh.GetEdgeVertices(x) for x in edges]
        ivert = connect_pairs2(ivert)[0]

        vv = np.vstack([mesh.GetVertexArray(i) for i in ivert])
        self.ctr = (vv[0] + vv[-1]) / 2.0
        dprint1("Center " + list(self.ctr).__repr__())

        ### rectangular port
        self.a_vec = (vv[0] - vv[-1])
        self.a = np.sqrt(np.sum(self.a_vec**2))
        self.a_vec /= self.a
        self.c = vv[-1]
        dprint1("Cornor " + self.c.__repr__())
        dprint1("Edge  " + self.a.__repr__())
        dprint1("Edge Vec." + list(self.a_vec).__repr__())

        Erz, Ephi = self.get_e_coeff_cls()
        Hrz, Hphi = self.get_h_coeff_cls()

        if self.mode == 'TE':
            dprint1("E field pattern")
            c1 = Ephi(self, real=True)
            c2 = Hphi(0.0, self, real=False)
            for p in vv:
                dprint1(p.__repr__() + ' : ' + c1.EvalValue(p).__repr__())
            dprint1("H field pattern")
            for p in vv:
                dprint1(p.__repr__() + ' : ' + c2.EvalValue(p).__repr__())
Exemple #16
0
 def updStiffMatMS(self, elmLst, elmCompStiffMat):
     self.K = mfem.ParBilinearForm(self.fespace)
     lambVec = mfem.Vector(self.fespace.GetMesh().attributes.Max())
     lambVec.Assign(self.lmbda)
     lambVec[0] = lambVec[1]
     lambda_func = mfem.PWConstCoefficient(lambVec)
     muVec = mfem.Vector(self.fespace.GetMesh().attributes.Max())
     muVec.Assign(self.mu)
     muVec[0] = muVec[1]
     mu_func = mfem.PWConstCoefficient(muVec)
     self.K.AddDomainIntegrator(
         mfem.ElasticityIntegrator(lambda_func, mu_func))
     self.K.Assemble(0, elmLst, elmCompStiffMat, False, True)
     self.Kmat = mfem.HypreParMatrix()
     empty_tdof_list = intArray()
     self.K.FormLinearSystem(empty_tdof_list, self.x_gfBdr, self.bx,
                             self.Kmat, self.vx.GetBlock(1), self.Bx, 1)
Exemple #17
0
    def ImplicitSolve(self, dt, vx, dvx_dt):
        sc = self.Height() // 2
        v = mfem.Vector(vx, 0, sc)
        x = mfem.Vector(vx, sc, sc)
        dv_dt = mfem.Vector(dvx_dt, 0, sc)
        dx_dt = mfem.Vector(dvx_dt, sc, sc)

        # By eliminating kx from the coupled system:
        # kv = -M^{-1}*[H(x + dt*kx) + S*(v + dt*kv)]
        # kx = v + dt*kv
        # we reduce it to a nonlinear equation for kv, represented by the
        # backward_euler_oper. This equation is solved with the newton_solver
        # object (using J_solver and J_prec internally).
        self.reduced_oper.SetParameters(dt, v, x)
        zero = mfem.Vector()  # empty vector is interpreted as
        # zero r.h.s. by NewtonSolver
        self.newton_solver.Mult(zero, dv_dt)
        add_vector(v, dt, dv_dt, dx_dt)
def surface_weight(refine, gtype):
    if (refine, gtype) in globals()['weight']:
        return globals()['weight'][(refine, gtype)]
    
    quad_v = [[0, 0], [1, 0], [1, 1], [0, 3]]
    quad_e = [[0, 1, 2, 3]]
    tri_v =   [[0, 0], [1, 0], [0, 1]]
    tri_e = [[0, 1, 2,]]
    seg_v =   [[0,], [1, ],]
    seg_e = [[0, 1,]]

    if gtype == mfem.Geometry.TRIANGLE:
        mesh = mfem.Mesh(2, 3, 1, 0, 2)
        for j in range(3):
            mesh.AddVertex(tri_v[j])
        for j in range(1):
            mesh.AddTri(tri_e[j], 11)
        mesh.FinalizeTriMesh(1,1, True)

    elif gtype == mfem.Geometry.SQUARE:
        mesh = mfem.Mesh(2, 4, 1, 0, 2)
        for j in range(4):
            mesh.AddVertex(quad_v[j])
        for j in range(1):
            mesh.AddQuad(quad_e[j], 11)
        mesh.FinalizeQuadMesh(1,1, True)
    elif gtype == mfem.Geometry.SEGMENT:
        mesh = mfem.Mesh(1, 2, 1, 0, 1)
        for j in range(2):
            mesh.AddVertex(seg_v[j])
        for j in range(1):
            seg = mfem.Segment(seg_e[j], j+1)
            mesh.AddElement(seg)
            seg.thisown = False        
            mesh.FinalizeTopology()         
            mesh.Finalize(False, False)

    fec_type = mfem.H1_FECollection
    fe_coll = fec_type(1, 2)
    fes = mfem.FiniteElementSpace(mesh, fe_coll, 2)
    el = fes.GetFE(0)
    npt = Geom.GetVertices(gtype).GetNPoints()
    RefG = GR.Refine(gtype, refine)

    shape = mfem.Vector(el.GetDof())              
    ir = RefG.RefPts

    shapes =[]
    for i in range(ir.GetNPoints()):
        el.CalcShape(ir.IntPoint(i), shape)
        shapes.append(shape.GetDataArray().copy())
        
    w = np.vstack(shapes)
    globals()['weight'][(refine, gtype)] = w

    return w
Exemple #19
0
    def Mult(self, k, y):
        # Extract the blocks from the input and output vectors
        block_offsets = self.block_offsets
        disp_in = k[block_offsets[0]:block_offsets[1]]
        pres_in = k[block_offsets[1]:block_offsets[2]]

        disp_out = y[block_offsets[0]:block_offsets[1]]
        pres_out = y[block_offsets[1]:block_offsets[2]]

        temp = mfem.Vector(block_offsets[1] - block_offsets[0])
        temp2 = mfem.Vector(block_offsets[1] - block_offsets[0])

        # Perform the block elimination for the preconditioner
        self.mass_pcg.Mult(pres_in, pres_out)
        pres_out *= -self.gamma

        self.jacobian.GetBlock(0, 1).Mult(pres_out, temp)
        mfem.subtract_vector(disp_in, temp, temp2)
        self.stiff_pcg.Mult(temp2, disp_out)
Exemple #20
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 #21
0
def SnapNodes(mesh):
    nodes = mesh.GetNodes()
    node = mfem.Vector(mesh.SpaceDimension())

    for i in np.arange(nodes.FESpace().GetNDofs()):
        for d in np.arange(mesh.SpaceDimension()):
            node[d] = nodes[nodes.FESpace().DofToVDof(i, d)]

        node /= node.Norml2()
        for d in range(mesh.SpaceDimension()):
            nodes[nodes.FESpace().DofToVDof(i, d)] = node[d]
Exemple #22
0
 def eval_local_from_T_ip(self):
     if not self.isDerived: self.set_funcs()
     if self.isVectorFE:
         if self.func_i is None:
             v = mfem.Vector()
             self.func_r.Eval(v, self.T, self.ip)
             return v.GetDataArray()[self.comp - 1]
         else:
             v1 = mfem.Vector()
             v2 = mfem.Vector()
             self.func_r.Eval(v1, self.T, self.ip)
             self.func_i.Eval(v2, self.T, self.ip)
             return (v1.GetDataArray() + 1j * v2.GetDataArray())[self.comp -
                                                                 1]
     else:
         if self.func_i is None:
             return self.func_r.Eval(self.T, self.ip)
         else:
             return (self.func_r.Eval(self.T, self.ip) +
                     1j * self.func_i.Eval(self.T, self.ip))
 def get_shape_all(fes, k1):
     tr1 = fes.GetBdrElementTransformation(k1)
     el = fes.GetBE(k1)
     nodes1 = el.GetNodes()
     v = mfem.Vector(nodes1.GetNPoints())
     shape = []
     for idx in range(nodes1.GetNPoints()):
        el.CalcShape(nodes1.IntPoint(idx), v)
        shape.append(v.GetDataArray()[idx])
     shape = np.stack(shape)    # shape seems all 1, length = num int-point
     return shape
Exemple #24
0
def run_test():
    a = mfem.Vector(np.arange(20.0))
    a.Print()

    a *= 30.
    a.Print()

    a[-15:].Print()
    a[-15:].Print_HYPRE()

    a.Print("vector.dat")
    a.Print_HYPRE("vector_hypre.dat")
Exemple #25
0
def run_test():
    m = mfem.DenseMatrix(3, 3)
    m.Assign(np.arange(9.).reshape(3, 3))
    m.Print()
    print(np.arange(9.).reshape(3, 3))

    x = np.zeros(5) + 1
    y = np.zeros(5) + 2
    z = np.zeros(5) + 3
    mm = mfem.DenseMatrix(3, 5)
    mm.Assign(np.vstack([x, y, z]))
    mm.Print()
    mfem.Vector(mm.GetData(), 15).Print()
Exemple #26
0
 def eval_local_from_T_ip(self):
     if not self.isDerived: self.set_funcs()
     if self.isVectorFE:
         if self.func_i is None:
             v = mfem.Vector()
             self.func_r.Eval(v, self.T, self.ip)
             return v.GetDataArray().copy()
         else:
             v1 = mfem.Vector()
             v2 = mfem.Vector()
             self.func_r.Eval(v1, self.T, self.ip)
             self.func_i.Eval(v2, self.T, self.ip)
             return v1.GetDataArray().copy() + 1j * v2.GetDataArray().copy()
     else:
         if self.func_i is None:
             return np.array(
                 [func_r.Eval(self.T, self.ip) for func_r in self.func_r])
         else:
             return np.array([
                 (func_r.Eval(self.T, self.ip) +
                  1j * func_i.Eval(self.T, self.ip))
                 for func_r, func_i in zip(self.func_r, self.func_i)
             ])
Exemple #27
0
    def assemble(self, *args, **kwargs):
        engine = self._engine()
        direction = kwargs.pop("direction", 0)
        
        self.process_kwargs(engine, kwargs)

        x = args[0]
        y = args[1] if len(args)>1 else 0
        z = args[2] if len(args)>2 else 0        
        
        sdim = self.fes1.GetMesh().SpaceDimension()
        if direction == 0:
            if sdim == 3:
               d = mfem.DeltaCoefficient(x, y, z, 1)
            elif sdim == 2:
               d = mfem.DeltaCoefficient(x, y, 1)
            elif sdim == 1:
               d = mfem.DeltaCoefficient(x, 1)
            else:
                assert False, "unsupported dimension"
            intg = mfem.DomainLFIntegrator(d)                
        else:
            dir = mfem.Vector(direction)
            if sdim == 3:
               d = mfem.VectorDeltaCoefficient(dir, x, y, z, 1)
            elif sdim == 2:
               d = mfem.VectorDeltaCoefficient(dir, x, y, 1)
            elif sdim == 1:
               d = mfem.VectorDeltaCoefficient(dir,x, 1)
            else:
                assert False, "unsupported dimension"
                
            if self.fes1.FEColl().Name().startswith('ND'):
                intg = mfem.VectorFEDomainLFIntegrator(d)                
            elif self.fes1.FEColl().Name().startswith('RT'):
                intg = mfem.VectorFEDomainLFIntegrator(d)            
            else:    
                intg = mfem.VectorDomainLFIntegrator(d)                                

        lf1 = engine.new_lf(self.fes1)
        lf1.AddDomainIntegrator(intg)
        lf1.Assemble()
        
        from mfem.common.chypre import LF2PyVec, PyVec2PyMat, MfemVec2PyVec
        v1 = MfemVec2PyVec(engine.b2B(lf1), None)

        v1 = PyVec2PyMat(v1)
        if not self._transpose:        
            v1 = v1.transpose()
        return v1
    def Mult(self, x, y):
        '''
        call cycle_max times of perform_one_cycle
        '''
        y.Assign(0.0)

        lvl = len(self.ess_tdofs) - 1

        correction = mfem.Vector(y.Size())
        correction.Assign(0.0)
        err = mfem.Vector(x.Size())
        err.Assign(x)
        tmp = mfem.Vector(x.Size())

        for i in range(self.cycle_max[lvl]):
            self.perform_one_cycle(err, correction)

            self.operators[lvl].Mult(correction, tmp)
            tmp *= -1
            tmp += err
            err.Assign(tmp)

            y += correction
Exemple #29
0
def do_findpoints(mesh, *args):
    sdim = mesh.SpaceDimension()
    
    shape = args[0].shape
    size= len(args[0].flatten())
    ptx = np.vstack([t.flatten() for t in args]).transpose().flatten()
    
    ptx2 = mfem.Vector(ptx)
    point_mat = mfem.DenseMatrix(ptx2.GetData(), size, sdim)
    elem_id = mfem.intArray()
    ips = mfem.IntegrationPointArray()
        
    num_found = mesh.FindPoints(point_mat, elem_id, ips, True)
    elem_id = np.array(elem_id.ToList())
    return v, elem_id, ips
Exemple #30
0
def get_inv_doftrans(doftrans, sign1):
    Msign = np.diag(sign1.flatten())
    if doftrans is not None:
        Mdoftrans = np.zeros((doftrans.Size(), doftrans.Size()))
        vv = mfem.Vector(doftrans.Size())
        for i in range(doftrans.Size()):
            vv.Assign(0)
            vv[i] = 1
            doftrans.InvTransformPrimal(vv)
            Mdoftrans[:, i] = vv.GetDataArray()

        #if myid == 1: print(Mdoftrans.astype(int))
        return Mdoftrans.dot(Msign)
    else:
        return Msign