Пример #1
0
 def __init__(self,ghosted_csr_mat=None,par_bs=None,par_n=None,par_N=None,par_nghost=None,subdomain2global=None,blockVecType="simple",pde=None, par_nc=None, par_Nc=None, proteus_jacobian=None, nzval_proteus2petsc=None):
     p4pyPETSc.Mat.__init__(self)
     if ghosted_csr_mat is None:
         return#when duplicating for petsc usage
     self.pde = pde
     if par_nc is None:
         par_nc = par_n
     if par_Nc is None:
         par_Nc = par_N
     self.proteus_jacobian=proteus_jacobian
     self.nzval_proteus2petsc = nzval_proteus2petsc
     self.ghosted_csr_mat=ghosted_csr_mat
     self.blockVecType = blockVecType
     assert self.blockVecType == "simple", "petsc4py wrappers require self.blockVecType=simple"
     self.create(p4pyPETSc.COMM_WORLD)
     self.blockSize = max(1,par_bs)
     if self.blockSize > 1 and blockVecType != "simple":
         ## \todo fix block aij in ParMat_petsc4py
         self.setType('baij')
         self.setSizes([[self.blockSize*par_n,self.blockSize*par_N],[self.blockSize*par_nc,self.blockSize*par_Nc]],bsize=self.blockSize)
         self.setBlockSize(self.blockSize)
         self.subdomain2global = subdomain2global #no need to include extra block dofs?
     else:
         self.setType('aij')
         self.setSizes([[par_n*self.blockSize,par_N*self.blockSize],[par_nc*self.blockSize,par_Nc*self.blockSize]],bsize=1)
         if self.blockSize > 1: #have to build in block dofs
             subdomain2globalTotal = numpy.zeros((self.blockSize*subdomain2global.shape[0],),'i')
             for j in range(self.blockSize):
                 subdomain2globalTotal[j::self.blockSize]=subdomain2global*self.blockSize+j
             self.subdomain2global=subdomain2globalTotal
         else:
             self.subdomain2global=subdomain2global
     from proteus import Comm
     comm = Comm.get()
     logEvent("ParMat_petsc4py comm.rank= %s blockSize = %s par_n= %s par_N=%s par_nghost=%s par_jacobian.getSizes()= %s "
              % (comm.rank(),self.blockSize,par_n,par_N,par_nghost,self.getSizes()))
     self.csr_rep = ghosted_csr_mat.getCSRrepresentation()
     if self.proteus_jacobian is not None:
         self.proteus_csr_rep = self.proteus_jacobian.getCSRrepresentation()
     if self.blockSize > 1:
         blockOwned = self.blockSize*par_n
         self.csr_rep_local = ghosted_csr_mat.getSubMatCSRrepresentation(0,blockOwned)
     else:
         self.csr_rep_local = ghosted_csr_mat.getSubMatCSRrepresentation(0,par_n)
     self.petsc_l2g = p4pyPETSc.LGMap()
     self.petsc_l2g.create(self.subdomain2global)
     self.setUp()
     self.setLGMap(self.petsc_l2g)
     #
     self.colind_global = self.petsc_l2g.apply(self.csr_rep_local[1]) #prealloc needs global indices
     self.setPreallocationCSR([self.csr_rep_local[0],self.colind_global,self.csr_rep_local[2]])
     self.setFromOptions()
Пример #2
0
def test_2D_line_integral_gauge_output():
    filename = 'test_2D_line_integral_gauge_output.csv'
    silent_rm(filename)

    lines = (((0, 0, 0), (1, 1, 0)),
             ((0, 0, 0), (1, 0, 0)),
             ((0, 0, 0), (0, 1, 0)),
             ((0, 0.5, 0), (1, 0.5, 0)),
             ((0, 1, 0), (1, 1, 0)),
             ((0.5, 0, 0), (0.5, 1, 0)))
    fields = ('u0', )

    l = LineIntegralGauges(gauges=((fields, lines),),
                   fileName=filename)

    time_list=[0.0, 1.0, 2.0, 2.5]
    run_gauge(l, time_list)

    correct_gauge_names = ['u0 [        0         0         0] - [        1         1         0]',
                           'u0 [        0         0         0] - [        1         0         0]',
                           'u0 [        0         0         0] - [        0         1         0]',
                           'u0 [        0       0.5         0] - [        1       0.5         0]',
                           'u0 [        0         1         0] - [        1         1         0]',
                           'u0 [      0.5         0         0] - [      0.5         1         0]']

    correct_data = np.asarray([[0.,   7.77817459,  0.5,   5.,   5.5,  10.5,   5.5],
                               [1.,  15.55634919,  1.,   10.,  11.,   21.,   11.],
                               [2.,  23.33452378,  1.5,  15.,  16.5,  31.5,  16.5],
                               [2.5, 27.22361108,  1.75, 17.5, 19.25, 36.75, 19.25]])

    # synchronize processes before attempting to read file

    Comm.get().barrier()

    gauge_names, data = parse_gauge_output(filename)
    eq_(correct_gauge_names, gauge_names)

    npt.assert_allclose(correct_data, data)
    delete_file(filename)
Пример #3
0
def test_line_gauge_output():
    filename = 'test_line_output.csv'
    silent_rm(filename)

    lines = (((0, 0, 0), (1, 1, 1)),)
    fields = ('u0', )

    l = LineGauges(gauges=((fields, lines),),
                   fileName=filename)

    time_list=[0.0, 1.0, 2.0]
    # good hard-code for up to 1,024 processes or so, but slow (about 8 seconds on single process).
    run_gauge(l, time_list, total_nodes=2048)
    correct_gauge_names = ['u0 [        0         0         0]', 'u0 [ 0.076923  0.076923  0.076923]',
                           'u0 [  0.15385   0.15385   0.15385]', 'u0 [  0.23077   0.23077   0.23077]',
                           'u0 [  0.30769   0.30769   0.30769]', 'u0 [  0.38462   0.38462   0.38462]',
                           'u0 [  0.46154   0.46154   0.46154]', 'u0 [  0.53846   0.53846   0.53846]',
                           'u0 [  0.61538   0.61538   0.61538]', 'u0 [  0.69231   0.69231   0.69231]',
                           'u0 [  0.76923   0.76923   0.76923]', 'u0 [  0.84615   0.84615   0.84615]',
                           'u0 [  0.92308   0.92308   0.92308]', 'u0 [        1         1         1]']
    correct_data = np.asarray([[0., 0., 8.53846154, 17.07692308, 25.61538462,
                                34.15384615, 42.69230769, 51.23076923, 59.76923077, 68.30769231,
                                76.84615385, 85.38461538, 93.92307692, 102.46153846, 111.],
                               [1., 0., 17.07692308, 34.15384615, 51.23076923,
                                68.30769231, 85.38461538, 102.46153846, 119.53846154, 136.61538462,
                                153.69230769, 170.76923077, 187.84615385, 204.92307692, 222.],
                               [2., 0., 25.61538462, 51.23076923, 76.84615385,
                                102.46153846, 128.07692308, 153.69230769, 179.30769231, 204.92307692,
                                230.53846154, 256.15384615, 281.76923077, 307.38461538, 333.]])

    # synchronize processes before attempting to read file

    Comm.get().barrier()

    gauge_names, data = parse_gauge_output(filename)

    eq_(correct_gauge_names, gauge_names)
    npt.assert_allclose(correct_data, data)
    delete_file(filename)
Пример #4
0
def test_point_gauge_output():
    filename = 'test_gauge_output.csv'
    silent_rm(filename)

    p = PointGauges(gauges=((('u0',), ((0, 0, 0), (1, 1, 1))),),
                    fileName=filename)
    time_list=[0.0, 1.0, 2.0]
    run_gauge(p, time_list)

    correct_gauge_names = ['u0 [        0         0         0]', 'u0 [        1         1         1]']
    correct_data = np.asarray([[   0.,    0.,  111.],
                               [   1.,    0.,  222.],
                               [   2.,    0.,  333.]])

    # synchronize processes before attempting to read file

    Comm.get().barrier()

    gauge_names, data = parse_gauge_output(filename)

    eq_(correct_gauge_names, gauge_names)
    npt.assert_allclose(correct_data, data)
Пример #5
0
def init_mpi_petsc(opts):
    log("Initializing MPI")
    if opts.petscOptions != None:
        petsc_argv = sys.argv[:1]+opts.petscOptions.split()
        log("PETSc options from commandline")
        log(str(petsc_argv))
    else:
        petsc_argv=sys.argv[:1]
    if opts.petscOptionsFile != None:
        petsc_argv=[sys.argv[0]]
        petsc_argv += open(opts.petscOptionsFile).read().split()
        log("PETSc options from commandline")
        log(str(petsc_argv))
    return Comm.init(argv=petsc_argv)
Пример #6
0
def test_line_integral_gauge_output():
    filename = 'test_line_integral_gauge_output.csv'
    silent_rm(filename)

    lines = (((0, 0, 0), (1, 1, 1)),)
    fields = ('u0', )

    l = LineIntegralGauges(gauges=((fields, lines),),
                   fileName=filename)
    time_list=[0.0, 1.0, 2.0]
    run_gauge(l, time_list)

    correct_gauge_names = ['u0 [        0         0         0] - [        1         1         1]']
    correct_data = np.asarray([[   0., 96.128819820072678],
                               [   1., 192.25763964014536],
                               [   2., 288.38645946021808]])

    # synchronize processes before attempting to read file
    Comm.get().barrier()

    gauge_names, data = parse_gauge_output(filename)
    eq_(correct_gauge_names, gauge_names)
    npt.assert_allclose(correct_data, data)
Пример #7
0
def test_2DparallelLoadPUMI(verbose=0):
    """Test to load 2D parallel PUMI model and mesh"""
    comm = Comm.init()
    eq(comm.size(),2)
    testDir=os.path.dirname(os.path.abspath(__file__))
    domain = Domain.PUMIDomain(dim=2)
    Model=testDir+ '/Rectangle.dmg'
    Mesh=testDir + '/Rectangle.smb'
    domain.PUMIMesh=MeshAdaptPUMI.MeshAdaptPUMI()
    domain.PUMIMesh.loadModelAndMesh(Model, Mesh)
    mesh = MeshTools.TriangularMesh()
    mesh.cmesh = cmeshTools.CMesh()
    mesh.convertFromPUMI(domain.PUMIMesh, domain.faceList, domain.regList,parallel = comm.size() > 1, dim = domain.nd)
    eq(mesh.nElements_global,8)
    eq(mesh.nNodes_global,10)
    eq(mesh.nEdges_global,17)
    eq(mesh.nElementBoundaries_global,17)
Пример #8
0
def test_3DparallelLoadPUMI(verbose=0):
    """Test to load 3D parallel PUMI model and mesh"""
    comm = Comm.init()
    eq(comm.size(),2)
    testDir=os.path.dirname(os.path.abspath(__file__))
    domain = Domain.PUMIDomain()
    Model=testDir+ '/Prism.dmg'
    Mesh=testDir + '/Prism.smb'
    domain.PUMIMesh=MeshAdaptPUMI.MeshAdaptPUMI()
    domain.PUMIMesh.loadModelAndMesh(Model, Mesh)
    mesh = MeshTools.TetrahedralMesh()
    mesh.cmesh = cmeshTools.CMesh()
    mesh.convertFromPUMI(domain.PUMIMesh, domain.faceList, domain.regList,parallel = comm.size() > 1, dim = domain.nd)
    eq(mesh.nElements_global,8148)
    eq(mesh.nNodes_global,1880)
    eq(mesh.nEdges_global,11001)
    eq(mesh.nElementBoundaries_global,17270)
Пример #9
0
def test_2DmultiRegion(verbose=0):
    """Test for loading gmsh mesh through PUMI with multiple-regions"""
    testDir=os.path.dirname(os.path.abspath(__file__))
    Model=testDir + '/TwoQuads.dmg'
    Mesh=testDir + '/TwoQuads.smb'
    domain = Domain.PUMIDomain(dim=2) #initialize the domain
    domain.PUMIMesh=MeshAdaptPUMI.MeshAdaptPUMI()
    domain.PUMIMesh.loadModelAndMesh(Model, Mesh)
    domain.faceList=[[14],[12],[11],[13],[15],[16]]
    domain.regList=[[41],[42]]

    mesh = MeshTools.TriangularMesh()
    mesh.cmesh = cmeshTools.CMesh()
    comm = Comm.init()

    mesh.convertFromPUMI(domain.PUMIMesh, domain.faceList,domain.regList, parallel = comm.size() > 1, dim = domain.nd)
    ok(mesh.elementMaterialTypes[0]==1)
    ok(mesh.elementMaterialTypes[-1]==2)
Пример #10
0
def test_wdot():
    """
    test_wdot

    Verifies that the proteus.LinearAlgebraTools.wdot computes dot product correctly.
    """
    import numpy as np
    import numpy.testing as npt
    from proteus.LinearAlgebraTools import wDot
    from proteus import Comm
    comm = Comm.init()
    x = np.array([-1, 2, 3])
    y = np.array([5, 6, 10])
    h = np.array([0.5, 1.2, 6.0])
    t1 = 191.9        
    t2 = wDot(x, y, h)
    test = npt.assert_almost_equal
    test.description = 'test_wdot'
    assert t1 == approx(t2)
Пример #11
0
def gauge_setup(nd, total_nodes=None):
    comm = Comm.get()

    #Simplified Physics
    p.name="test_gauges"

    p.nd = nd

    class LinearSolution:
        def uOfXT(self,x,t):
            return (x[0]+10*x[1]+100*x[2])*(t+1.0)

    p.initialConditions = {0:LinearSolution()}
    p.dirichletConditions = {0: lambda x,flag: None}
    p.domain = Domain.RectangularDomain(name="test_gauges_domain")
    p.coefficients = TransportCoefficients.PoissonEquationCoefficients(aOfX = [lambda x: np.eye(p.nd, p.nd)],
                                                                       fOfX = [lambda x: 0], nc=1, nd=p.nd)
    #Simplified and Incomplete Numerics
    n.femSpaces = {0:FemTools.C0_AffineLinearOnSimplexWithNodalBasis}
    n.elementQuadrature = Quadrature.SimplexGaussQuadrature(p.nd,3)
    n.elementBoundaryQuadrature = Quadrature.SimplexGaussQuadrature(p.nd-1,3)
    n.numericalFluxType = NumericalFlux.NoFlux
    n.cfluxtag = None
    n.conservativeFlux = None

    if total_nodes is None:
        total_nodes = 2*comm.size()

    if p.nd == 1:
        mlMesh = build1DMesh(p, total_nodes+1)
    elif p.nd == 2:
        nnx = nny = int(ceil(sqrt(total_nodes)))+1
        mlMesh = build2DMesh(p, nnx, nny)
    elif p.nd == 3:
        nnx = nny = nnz = int(ceil(pow(total_nodes, 1.0/3.0)))+1
        mlMesh = build3DMesh(p, nnx, nny, nnz)

    model = Transport.MultilevelTransport(p, n, mlMesh)

    return model, p.initialConditions
Пример #12
0
    def __init__(self,
                 uDict,
                 phiDict,
                 testSpaceDict,
                 matType,
                 dofBoundaryConditionsDict,
                 dofBoundaryConditionsSetterDict,
                 coefficients,
                 elementQuadrature,
                 elementBoundaryQuadrature,
                 fluxBoundaryConditionsDict=None,
                 advectiveFluxBoundaryConditionsSetterDict=None,
                 diffusiveFluxBoundaryConditionsSetterDictDict=None,
                 stressFluxBoundaryConditionsSetterDict=None,
                 stabilization=None,
                 shockCapturing=None,
                 conservativeFluxDict=None,
                 numericalFluxType=None,
                 TimeIntegrationClass=None,
                 massLumping=False,
                 reactionLumping=False,
                 options=None,
                 name='Plasticity',
                 reuse_trial_and_test_quadrature=True,
                 sd=True,
                 movingDomain=False,
                 bdyNullSpace=False):
        #
        # set the objects describing the method and boundary conditions
        #
        self.bdyNullSpace = bdyNullSpace
        self.moveCalls = 0
        self.movingDomain = movingDomain
        self.tLast_mesh = None
        self.bdyNullSpace = bdyNullSpace
        #
        # cek todo clean up these flags in the optimized version
        self.bcsTimeDependent = options.bcsTimeDependent
        self.bcsSet = False
        self.name = name
        self.sd = sd
        self.lowmem = True
        self.timeTerm = True  # allow turning off  the  time derivative
        self.testIsTrial = True
        self.phiTrialIsTrial = True
        self.u = uDict
        self.Hess = False
        if isinstance(self.u[0].femSpace,
                      FemTools.C0_AffineQuadraticOnSimplexWithNodalBasis):
            self.Hess = True
        self.ua = {}  # analytical solutions
        self.phi = phiDict
        self.dphi = {}
        self.matType = matType
        # mwf try to reuse test and trial information across components if spaces are the same
        self.reuse_test_trial_quadrature = reuse_trial_and_test_quadrature  # True#False
        if self.reuse_test_trial_quadrature:
            for ci in range(1, coefficients.nc):
                assert self.u[ci].femSpace.__class__.__name__ == self.u[
                    0].femSpace.__class__.__name__, "to reuse_test_trial_quad all femSpaces must be the same!"
        # Simplicial Mesh
        self.mesh = self.u[
            0].femSpace.mesh  # assume the same mesh for  all components for now
        self.testSpace = testSpaceDict
        self.dirichletConditions = dofBoundaryConditionsDict
        self.dirichletNodeSetList = None  # explicit Dirichlet  conditions for now, no Dirichlet BC constraints
        self.coefficients = coefficients
        self.coefficients.initializeMesh(self.mesh)
        self.nc = self.coefficients.nc
        self.stabilization = stabilization
        self.shockCapturing = shockCapturing
        self.conservativeFlux = conservativeFluxDict  # no velocity post-processing for now
        self.fluxBoundaryConditions = fluxBoundaryConditionsDict
        self.stressFluxBoundaryConditionsSetterDict = stressFluxBoundaryConditionsSetterDict
        # determine whether  the stabilization term is nonlinear
        self.stabilizationIsNonlinear = False
        # cek come back
        if self.stabilization is not None:
            for ci in range(self.nc):
                if ci in coefficients.mass:
                    for flag in list(coefficients.mass[ci].values()):
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if ci in coefficients.advection:
                    for flag in list(coefficients.advection[ci].values()):
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if ci in coefficients.diffusion:
                    for diffusionDict in list(
                            coefficients.diffusion[ci].values()):
                        for flag in list(diffusionDict.values()):
                            if flag != 'constant':
                                self.stabilizationIsNonlinear = True
                if ci in coefficients.potential:
                    for flag in list(coefficients.potential[ci].values()):
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if ci in coefficients.reaction:
                    for flag in list(coefficients.reaction[ci].values()):
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if ci in coefficients.hamiltonian:
                    for flag in list(coefficients.hamiltonian[ci].values()):
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
        # determine if we need element boundary storage
        self.elementBoundaryIntegrals = {}
        for ci in range(self.nc):
            self.elementBoundaryIntegrals[ci] = (
                (self.conservativeFlux is not None)
                or (numericalFluxType is not None)
                or (self.fluxBoundaryConditions[ci] == 'outFlow')
                or (self.fluxBoundaryConditions[ci] == 'mixedFlow')
                or (self.fluxBoundaryConditions[ci] == 'setFlow'))
        #
        # calculate some dimensions
        #
        self.nSpace_global = self.u[
            0].femSpace.nSpace_global  # assume same space dim for all variables
        self.nDOF_trial_element = [
            u_j.femSpace.max_nDOF_element for u_j in list(self.u.values())
        ]
        self.nDOF_phi_trial_element = [
            phi_k.femSpace.max_nDOF_element
            for phi_k in list(self.phi.values())
        ]
        self.n_phi_ip_element = [
            phi_k.femSpace.referenceFiniteElement.interpolationConditions.
            nQuadraturePoints for phi_k in list(self.phi.values())
        ]
        self.nDOF_test_element = [
            femSpace.max_nDOF_element
            for femSpace in list(self.testSpace.values())
        ]
        self.nFreeDOF_global = [
            dc.nFreeDOF_global
            for dc in list(self.dirichletConditions.values())
        ]
        self.nVDOF_element = sum(self.nDOF_trial_element)
        self.nFreeVDOF_global = sum(self.nFreeDOF_global)
        #
        NonlinearEquation.__init__(self, self.nFreeVDOF_global)
        #
        # build the quadrature point dictionaries from the input (this
        # is just for convenience so that the input doesn't have to be
        # complete)
        #
        elementQuadratureDict = {}
        elemQuadIsDict = isinstance(elementQuadrature, dict)
        if elemQuadIsDict:  # set terms manually
            for I in self.coefficients.elementIntegralKeys:
                if I in elementQuadrature:
                    elementQuadratureDict[I] = elementQuadrature[I]
                else:
                    elementQuadratureDict[I] = elementQuadrature['default']
        else:
            for I in self.coefficients.elementIntegralKeys:
                elementQuadratureDict[I] = elementQuadrature
        if self.stabilization is not None:
            for I in self.coefficients.elementIntegralKeys:
                if elemQuadIsDict:
                    if I in elementQuadrature:
                        elementQuadratureDict[('stab', ) +
                                              I[1:]] = elementQuadrature[I]
                    else:
                        elementQuadratureDict[
                            ('stab', ) + I[1:]] = elementQuadrature['default']
                else:
                    elementQuadratureDict[('stab', ) +
                                          I[1:]] = elementQuadrature
        if self.shockCapturing is not None:
            for ci in self.shockCapturing.components:
                if elemQuadIsDict:
                    if ('numDiff', ci, ci) in elementQuadrature:
                        elementQuadratureDict[(
                            'numDiff', ci, ci)] = elementQuadrature[('numDiff',
                                                                     ci, ci)]
                    else:
                        elementQuadratureDict[(
                            'numDiff', ci, ci)] = elementQuadrature['default']
                else:
                    elementQuadratureDict[('numDiff', ci,
                                           ci)] = elementQuadrature
        if massLumping:
            for ci in list(self.coefficients.mass.keys()):
                elementQuadratureDict[(
                    'm', ci)] = Quadrature.SimplexLobattoQuadrature(
                        self.nSpace_global, 1)
            for I in self.coefficients.elementIntegralKeys:
                elementQuadratureDict[
                    ('stab', ) + I[1:]] = Quadrature.SimplexLobattoQuadrature(
                        self.nSpace_global, 1)
        if reactionLumping:
            for ci in list(self.coefficients.mass.keys()):
                elementQuadratureDict[(
                    'r', ci)] = Quadrature.SimplexLobattoQuadrature(
                        self.nSpace_global, 1)
            for I in self.coefficients.elementIntegralKeys:
                elementQuadratureDict[
                    ('stab', ) + I[1:]] = Quadrature.SimplexLobattoQuadrature(
                        self.nSpace_global, 1)
        elementBoundaryQuadratureDict = {}
        if isinstance(elementBoundaryQuadrature, dict):  # set terms manually
            for I in self.coefficients.elementBoundaryIntegralKeys:
                if I in elementBoundaryQuadrature:
                    elementBoundaryQuadratureDict[
                        I] = elementBoundaryQuadrature[I]
                else:
                    elementBoundaryQuadratureDict[
                        I] = elementBoundaryQuadrature['default']
        else:
            for I in self.coefficients.elementBoundaryIntegralKeys:
                elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature
        #
        # find the union of all element quadrature points and
        # build a quadrature rule for each integral that has a
        # weight at each point in the union
        # mwf include tag telling me which indices are which quadrature rule?
        (self.elementQuadraturePoints, self.elementQuadratureWeights,
         self.elementQuadratureRuleIndeces
         ) = Quadrature.buildUnion(elementQuadratureDict)
        self.nQuadraturePoints_element = self.elementQuadraturePoints.shape[0]
        self.nQuadraturePoints_global = self.nQuadraturePoints_element * self.mesh.nElements_global
        #
        # Repeat the same thing for the element boundary quadrature
        #
        (self.elementBoundaryQuadraturePoints,
         self.elementBoundaryQuadratureWeights,
         self.elementBoundaryQuadratureRuleIndeces
         ) = Quadrature.buildUnion(elementBoundaryQuadratureDict)
        self.nElementBoundaryQuadraturePoints_elementBoundary = self.elementBoundaryQuadraturePoints.shape[
            0]
        self.nElementBoundaryQuadraturePoints_global = (
            self.mesh.nElements_global * self.mesh.nElementBoundaries_element *
            self.nElementBoundaryQuadraturePoints_elementBoundary)
        #
        # simplified allocations for test==trial and also check if space is mixed or not
        #
        self.q = {}
        self.ebq = {}
        self.ebq_global = {}
        self.ebqe = {}
        self.phi_ip = {}
        # mesh
        self.ebqe['x'] = np.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary, 3), 'd')
        self.q['bodyForce'] = np.zeros(
            (self.mesh.nElements_global, self.nQuadraturePoints_element,
             self.nSpace_global), 'd')
        self.ebqe[('u', 0)] = np.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
        self.ebqe[('u', 1)] = np.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
        self.ebqe[('u', 2)] = np.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
        self.ebqe[('stressFlux_bc_flag', 0)] = np.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary), 'i')
        self.ebqe[('stressFlux_bc_flag', 1)] = np.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary), 'i')
        self.ebqe[('stressFlux_bc_flag', 2)] = np.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary), 'i')
        self.ebqe[('stressFlux_bc', 0)] = np.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
        self.ebqe[('stressFlux_bc', 1)] = np.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
        self.ebqe[('stressFlux_bc', 2)] = np.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
        self.points_elementBoundaryQuadrature = set()
        self.scalars_elementBoundaryQuadrature = set([
            ('u', ci) for ci in range(self.nc)
        ])
        self.vectors_elementBoundaryQuadrature = set()
        self.tensors_elementBoundaryQuadrature = set()
        #
        # show quadrature
        #
        logEvent("Dumping quadrature shapes for model %s" % self.name, level=9)
        logEvent("Element quadrature array (q)", level=9)
        for (k, v) in list(self.q.items()):
            logEvent(str((k, v.shape)), level=9)
        logEvent("Element boundary quadrature (ebq)", level=9)
        for (k, v) in list(self.ebq.items()):
            logEvent(str((k, v.shape)), level=9)
        logEvent("Global element boundary quadrature (ebq_global)", level=9)
        for (k, v) in list(self.ebq_global.items()):
            logEvent(str((k, v.shape)), level=9)
        logEvent("Exterior element boundary quadrature (ebqe)", level=9)
        for (k, v) in list(self.ebqe.items()):
            logEvent(str((k, v.shape)), level=9)
        logEvent(
            "Interpolation points for nonlinear diffusion potential (phi_ip)",
            level=9)
        for (k, v) in list(self.phi_ip.items()):
            logEvent(str((k, v.shape)), level=9)
        #
        # allocate residual and Jacobian storage
        #
        self.elementResidual = [
            np.zeros((self.mesh.nElements_global, self.nDOF_test_element[ci]),
                     'd') for ci in range(self.nc)
        ]
        self.elementSpatialResidual = [
            np.zeros((self.mesh.nElements_global, self.nDOF_test_element[ci]),
                     'd') for ci in range(self.nc)
        ]
        self.inflowBoundaryBC = {}
        self.inflowBoundaryBC_values = {}
        self.inflowFlux = {}
        for cj in range(self.nc):
            self.inflowBoundaryBC[cj] = np.zeros(
                (self.mesh.nExteriorElementBoundaries_global, ), 'i')
            self.inflowBoundaryBC_values[cj] = np.zeros(
                (self.mesh.nExteriorElementBoundaries_global,
                 self.nDOF_trial_element[cj]), 'd')
            self.inflowFlux[cj] = np.zeros(
                (self.mesh.nExteriorElementBoundaries_global,
                 self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
        self.internalNodes = set(range(self.mesh.nNodes_global))
        # identify the internal nodes this is ought to be in mesh
        # \todo move this to mesh
        for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
            ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
            eN_global = self.mesh.elementBoundaryElementsArray[ebN, 0]
            ebN_element = self.mesh.elementBoundaryLocalElementBoundariesArray[
                ebN, 0]
            for i in range(self.mesh.nNodes_element):
                if i != ebN_element:
                    I = self.mesh.elementNodesArray[eN_global, i]
                    self.internalNodes -= set([I])
        self.nNodes_internal = len(self.internalNodes)
        self.internalNodesArray = np.zeros((self.nNodes_internal, ), 'i')
        for nI, n in enumerate(self.internalNodes):
            self.internalNodesArray[nI] = n
        #
        del self.internalNodes
        self.internalNodes = None
        logEvent("Updating local to global mappings", 2)
        self.updateLocal2Global()
        logEvent("Building time integration object", 2)
        logEvent(memory("inflowBC, internalNodes,updateLocal2Global",
                        "OneLevelTransport"),
                 level=4)
        # mwf for interpolating subgrid error for gradients etc
        if self.stabilization and self.stabilization.usesGradientStabilization:
            self.timeIntegration = TimeIntegrationClass(
                self, integrateInterpolationPoints=True)
        else:
            self.timeIntegration = TimeIntegrationClass(self)

        if options is not None:
            self.timeIntegration.setFromOptions(options)
        logEvent(memory("TimeIntegration", "OneLevelTransport"), level=4)
        logEvent("Calculating numerical quadrature formulas", 2)
        self.calculateQuadrature()
        self.setupFieldStrides()

        comm = Comm.get()
        self.comm = comm
        if comm.size() > 1:
            assert numericalFluxType is not None and numericalFluxType.useWeakDirichletConditions, "You must use a numerical flux to apply weak boundary conditions for parallel runs"

        logEvent(memory("stride+offset", "OneLevelTransport"), level=4)
        if numericalFluxType is not None:
            if options is None or options.periodicDirichletConditions is None:
                self.numericalFlux = numericalFluxType(
                    self, dofBoundaryConditionsSetterDict,
                    advectiveFluxBoundaryConditionsSetterDict,
                    diffusiveFluxBoundaryConditionsSetterDictDict)
            else:
                self.numericalFlux = numericalFluxType(
                    self, dofBoundaryConditionsSetterDict,
                    advectiveFluxBoundaryConditionsSetterDict,
                    diffusiveFluxBoundaryConditionsSetterDictDict,
                    options.periodicDirichletConditions)
        else:
            self.numericalFlux = None
        # set penalty terms
        # cek todo move into numerical flux initialization
        if 'penalty' in self.ebq_global:
            for ebN in range(self.mesh.nElementBoundaries_global):
                for k in range(
                        self.nElementBoundaryQuadraturePoints_elementBoundary):
                    self.ebq_global['penalty'][ebN, k] = old_div(self.numericalFlux.penalty_constant, \
                        (self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power))
        # penalty term
        # cek move  to Numerical flux initialization
        if 'penalty' in self.ebqe:
            for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
                ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
                for k in range(
                        self.nElementBoundaryQuadraturePoints_elementBoundary):
                    self.ebqe['penalty'][ebNE, k] = old_div(self.numericalFlux.penalty_constant, \
                        self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power)
        logEvent(memory("numericalFlux", "OneLevelTransport"), level=4)
        self.elementEffectiveDiametersArray = self.mesh.elementInnerDiametersArray
        # use post processing tools to get conservative fluxes, None by default
        # helper for writing out data storage
        import proteus.Archiver
        self.elementQuadratureDictionaryWriter = Archiver.XdmfWriter()
        self.elementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
        self.exteriorElementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter(
        )
        for ci, sbcObject in list(
                self.stressFluxBoundaryConditionsObjectsDict.items()):
            self.ebqe[('stressFlux_bc_flag',
                       ci)] = np.zeros(self.ebqe[('stressFlux_bc', ci)].shape,
                                       'i')
            for t, g in list(
                    sbcObject.stressFluxBoundaryConditionsDict.items()):
                self.ebqe[('stressFlux_bc',
                           ci)][t[0], t[1]] = g(self.ebqe[('x')][t[0], t[1]],
                                                self.timeIntegration.t)
                self.ebqe[('stressFlux_bc_flag', ci)][t[0], t[1]] = 1
        self.numericalFlux.setDirichletValues(self.ebqe)
        if self.mesh.nodeVelocityArray is None:
            self.mesh.nodeVelocityArray = np.zeros(self.mesh.nodeArray.shape,
                                                   'd')
        compKernelFlag = 0
        if self.nSpace_global == 2:
            import copy
            self.u[2] = self.u[1].copy()
            self.u[2].name = 'hz'
            self.offset.append(self.offset[1])
            self.stride.append(self.stride[1])
            self.numericalFlux.isDOFBoundary[
                2] = self.numericalFlux.isDOFBoundary[1].copy()
            self.numericalFlux.ebqe[('u',
                                     2)] = self.numericalFlux.ebqe[('u',
                                                                    1)].copy()
            logEvent("calling cMoveMesh2D_base ctor")
            self.moveMesh = cMoveMesh2D_base(
                self.nSpace_global, self.nQuadraturePoints_element,
                self.u[0].femSpace.elementMaps.localFunctionSpace.dim, self.
                u[0].femSpace.referenceFiniteElement.localFunctionSpace.dim,
                self.testSpace[0].referenceFiniteElement.localFunctionSpace.
                dim, self.nElementBoundaryQuadraturePoints_elementBoundary,
                compKernelFlag)
        else:
            logEvent("calling cMoveMesh_base ctor")
            self.moveMesh = cMoveMesh_base(
                self.nSpace_global, self.nQuadraturePoints_element,
                self.u[0].femSpace.elementMaps.localFunctionSpace.dim, self.
                u[0].femSpace.referenceFiniteElement.localFunctionSpace.dim,
                self.testSpace[0].referenceFiniteElement.localFunctionSpace.
                dim, self.nElementBoundaryQuadraturePoints_elementBoundary,
                compKernelFlag)

        self.disp0 = np.zeros(self.nSpace_global, 'd')
        self.disp1 = np.zeros(self.nSpace_global, 'd')
        self.vel0 = np.zeros(self.nSpace_global, 'd')
        self.vel1 = np.zeros(self.nSpace_global, 'd')
        self.rot0 = np.eye(self.nSpace_global, dtype=float)
        self.rot1 = np.eye(self.nSpace_global, dtype=float)
        self.angVel0 = np.zeros(self.nSpace_global, 'd')
        self.angVel1 = np.zeros(self.nSpace_global, 'd')

        self.forceStrongConditions = True  # False#True
        self.dirichletConditionsForceDOF = {}
        if self.forceStrongConditions:
            for cj in range(self.nc):
                self.dirichletConditionsForceDOF[
                    cj] = FemTools.DOFBoundaryConditions(
                        self.u[cj].femSpace,
                        dofBoundaryConditionsSetterDict[cj],
                        weakDirichletConditions=False)
        from proteus import PostProcessingTools
        self.velocityPostProcessor = PostProcessingTools.VelocityPostProcessingChooser(
            self)
        logEvent(memory("velocity postprocessor", "OneLevelTransport"),
                 level=4)
Пример #13
0
 def getResidual(self, u, r):
     import pdb
     import copy
     """
     Calculate the element residuals and add in to the global residual
     """
     r.fill(0.0)
     # Load the unknowns into the finite element dof
     for dofN, g in list(self.dirichletConditionsForceDOF[0].
                         DOFBoundaryConditionsDict.items()):
         # load the BC valu        # Load the unknowns into the finite element dof
         u[self.offset[0] + self.stride[0] * dofN] = g(
             self.dirichletConditionsForceDOF[0].DOFBoundaryPointDict[dofN],
             self.timeIntegration.t)
     self.setUnknowns(u)
     self.Aij[:, :, self.added_mass_i] = 0.0
     self.addedMass.calculateResidual(  # element
         self.u[0].femSpace.elementMaps.psi,
         self.u[0].femSpace.elementMaps.grad_psi,
         self.mesh.nodeArray,
         self.mesh.elementNodesArray,
         self.elementQuadratureWeights[('u', 0)],
         self.u[0].femSpace.psi,
         self.u[0].femSpace.grad_psi,
         self.u[0].femSpace.psi,
         self.u[0].femSpace.grad_psi,
         # element boundary
         self.u[0].femSpace.elementMaps.psi_trace,
         self.u[0].femSpace.elementMaps.grad_psi_trace,
         self.elementBoundaryQuadratureWeights[('u', 0)],
         self.u[0].femSpace.psi_trace,
         self.u[0].femSpace.grad_psi_trace,
         self.u[0].femSpace.psi_trace,
         self.u[0].femSpace.grad_psi_trace,
         self.u[0].femSpace.elementMaps.boundaryNormals,
         self.u[0].femSpace.elementMaps.boundaryJacobians,
         # physics
         self.mesh.nElements_global,
         self.mesh.nElementBoundaries_owned,
         self.u[0].femSpace.dofMap.l2g,
         self.u[0].dof,
         self.coefficients.q_rho,
         self.offset[0],
         self.stride[0],
         r,
         self.mesh.nExteriorElementBoundaries_global,
         self.mesh.exteriorElementBoundariesArray,
         self.mesh.elementBoundaryElementsArray,
         self.mesh.elementBoundaryLocalElementBoundariesArray,
         self.mesh.elementBoundaryMaterialTypes,
         self.Aij,
         self.added_mass_i,
         self.barycenters,
         self.flags_rigidbody)
     # sum of residual should be zero
     # but it is sometimes not exactly zero with certain meshes in parallel
     # hack
     comm = Comm.get().comm.tompi4py()
     if comm.size > 1:
         r_sum_local = np.sum(r[:self.mesh.nNodes_owned])
         r_sum_global = comm.reduce(r_sum_local, op=MPI.SUM, root=0)
         if comm.rank == 0:
             r[0] -= r_sum_global
             logEvent('R SUM: local: {r_sum_local} global: {r_sum_global}'.
                      format(r_sum_local=r_sum_local,
                             r_sum_global=r_sum_global))
         logEvent('ACCELERATION INDEX: {id}'.format(id=self.added_mass_i))
     # end hack
     for k in range(self.Aij.shape[0]):
         for j in range(self.Aij.shape[2]):
             self.Aij[k, j, self.added_mass_i] = globalSum(
                 self.Aij[k, j, self.added_mass_i])
     for i, flag in enumerate(self.flags_rigidbody):
         if flag == 1:
             numpy.set_printoptions(precision=2, linewidth=160)
             logEvent("Added Mass Tensor for rigid body i" + repr(i))
             logEvent("Aij = \n" + str(self.Aij[i]))
     for dofN, g in list(self.dirichletConditionsForceDOF[0].
                         DOFBoundaryConditionsDict.items()):
         r[self.offset[0] + self.stride[0] * dofN] = self.u[0].dof[dofN] - \
             g(self.dirichletConditionsForceDOF[0].DOFBoundaryPointDict[dofN], self.timeIntegration.t)
     logEvent("Global residual", level=9, data=r)
     self.nonlinear_function_evaluations += 1
Пример #14
0
"""
convenience script to generate xdmf and vtk output from tetgen files
"""
from proteus import Comm
Comm.init()
comm = Comm.get()
def refine_uniform_from_tetgen(filebase,refinementLevels,index_base=0,EB=False):
    from proteus import MeshTools,Archiver
    mesh = MeshTools.TetrahedralMesh()
    mesh.generateFromTetgenFiles(filebase,index_base,skipGeometricInit=False)

    MLMesh = MeshTools.MultilevelTetrahedralMesh(0,0,0,skipInit=True)

    MLMesh.generateFromExistingCoarseMesh(mesh,refinementLevels)

    MLMesh.meshList[-1].writeTetgenFiles(filebase+'_out',index_base)

    ar = Archiver.XdmfArchive('.',filebase+'_out')
    import xml.etree.ElementTree as ElementTree
    ar.domain = ElementTree.SubElement(ar.tree.getroot(),"Domain")
    mesh.writeMeshXdmf(ar,'mesh_coarse'+'_out',init=True,EB=EB,tCount=0)
    MLMesh.meshList[-1].writeMeshXdmf(ar,'mesh_fine'+'_out',init=True,EB=EB,tCount=1)
    ar.close()
    
def refine_uniform_from_triangle(filebase,refinementLevels,index_base=0,EB=False):
    from proteus import MeshTools,Archiver
    mesh = MeshTools.TriangularMesh()
    mesh.generateFromTriangleFiles(filebase,index_base)

    MLMesh = MeshTools.MultilevelTriangularMesh(0,0,0,skipInit=True)
Пример #15
0
#import sys
#from proteus import Comm
import os
import sys
import socket
import cPickle
import numpy
import proteus
#remove blankent import statements until after Comm initialized for petsc4py
# from proteus import *
from proteus import Profiling,Comm
from warnings import *
import optparse
import sys
import pstats
import pdb
import petsc4py
Profiling.openLog("proteus.log",7)
print sys.argv[:1]
comm = Comm.init(argv=sys.argv[:1])
comm = Comm.init(argv=sys.argv[:1])
#petsc4py.init(sys.argv[:1])
print comm.rank(),comm.size()
print "Hellow World from",comm.rank()
from proteus import *
Profiling.procID=comm.rank()
Пример #16
0
def test_poiseuilleError(verbose=0):
    """Test for loading gmsh mesh through PUMI, estimating error for 
    a Poiseuille flow case. The estimated error should be larger than the
    exact error in the seminorm"""
    testDir=os.path.dirname(os.path.abspath(__file__))
    Model=testDir + '/Couette.null'
    Mesh=testDir + '/Couette.msh'

    domain = Domain.PUMIDomain() #initialize the domain
    domain.PUMIMesh=MeshAdaptPUMI.MeshAdaptPUMI(hmax=0.01, hmin=0.008, numIter=1,sfConfig='ERM',maType='isotropic',logType='off')
    domain.PUMIMesh.loadModelAndMesh(Model, Mesh)
    domain.faceList=[[80],[76],[42],[24],[82],[78]]

    mesh = MeshTools.TetrahedralMesh()
    mesh.cmesh = cmeshTools.CMesh()
    comm = Comm.init()

    nElements_initial = mesh.nElements_global
    mesh.convertFromPUMI(domain.PUMIMesh, domain.faceList, domain.regList,parallel = comm.size() > 1, dim = domain.nd)

    domain.PUMIMesh.transferFieldToPUMI("coordinates",mesh.nodeArray)


    rho = numpy.array([998.2,998.2])
    nu = numpy.array([1.004e-6, 1.004e-6])
    g = numpy.asarray([0.0,0.0,0.0])
    deltaT = 1.0 #dummy number 
    domain.PUMIMesh.transferPropertiesToPUMI(rho,nu,g,deltaT)

    #Poiseuille Flow
    Ly=0.2
    Lz = 0.05
    Re = 100
    Umax = Re*nu[0]/Lz

    def vOfX(x):
        return 4*Umax/(Lz**2)*(x[2])*(Lz-x[2])
    def dvOfXdz(x):
        return 4*Umax/(Lz**2)*(Lz-2*x[2])

    #hard code solution
    vector=numpy.zeros((mesh.nNodes_global,3),'d')
    dummy = numpy.zeros(mesh.nNodes_global); 

    vector[:,0] = dummy
    vector[:,1] = 4*Umax/(Lz**2)*(mesh.nodeArray[:,2])*(Lz-mesh.nodeArray[:,2]) #v-velocity
    vector[:,2] = dummy
    domain.PUMIMesh.transferFieldToPUMI("velocity", vector)

    scalar=numpy.zeros((mesh.nNodes_global,1),'d')
    domain.PUMIMesh.transferFieldToPUMI("p", scalar)

    scalar[:,0] = mesh.nodeArray[:,2]
    domain.PUMIMesh.transferFieldToPUMI("phi", scalar)
    del scalar

    scalar = numpy.zeros((mesh.nNodes_global,1),'d')+1.0
    domain.PUMIMesh.transferFieldToPUMI("vof", scalar)

    errorTotal=domain.PUMIMesh.get_local_error()


    # load the femspace with linear basis and get the quadrature points on a reference element
    elementQuadrature = Quadrature.SimplexGaussQuadrature(domain.nd,3)

    ok(mesh.nNodes_element==4) #confirm all of the elements have 4 nodes

    #hard code computation for H1 seminorm; ideally will be reformatted using the classes within proteus
    derivativeArrayRef = [[1,0,0],[0,1,0],[0,0,1],[-1,-1,-1]]
    error = 0
    for eID in range(mesh.nElements_global):
        nodes=mesh.elementNodesArray[eID]
        coords=[];
        for i in range(mesh.nNodes_element):
            coords.append(mesh.nodeArray[nodes[i]])
        J = numpy.matrix([[coords[0][0]-coords[3][0],coords[1][0]-coords[3][0],coords[2][0]-coords[3][0]],
                          [coords[0][1]-coords[3][1],coords[1][1]-coords[3][1],coords[2][1]-coords[3][1]],
                          [coords[0][2]-coords[3][2],coords[1][2]-coords[3][2],coords[2][2]-coords[3][2]]])
        invJ = J.I
        detJ = numpy.linalg.det(J)
        gradPhi_h = 0
        for k in range(len(elementQuadrature.points)):
            tempQpt = 0 
            zCoord = elementQuadrature.points[k][0]*coords[0][2] \
                +elementQuadrature.points[k][1]*coords[1][2] \
                +elementQuadrature.points[k][2]*coords[2][2] \
                +(1-elementQuadrature.points[k][0]-elementQuadrature.points[k][1]-elementQuadrature.points[k][2])*coords[3][2]
            for i in range(mesh.nNodes_element):
                temp = 0
                for j in range(domain.nd):
                    temp = temp + derivativeArrayRef[i][j]*invJ[j,2]
                tempQpt = tempQpt + vector[nodes[i]][1]*temp
            exactgradPhi = dvOfXdz([0,0,zCoord])
            gradPhi_h = gradPhi_h + tempQpt
            error = error + (exactgradPhi-gradPhi_h)**2*elementQuadrature.weights[k]*abs(detJ)

    error = sqrt(error)
    ok(error<errorTotal)
Пример #17
0
def setup_profiling():
    comm = Comm.get()
    Profiling.procID = comm.rank()
    Profiling.logLevel = 10
    Profiling.logFile = sys.stdout
    Profiling.logAllProcesses = True
Пример #18
0
    petsc_argv=[sys.argv[0]]
    with open(opts.petscOptionsFile) as petsc_file:
        data = petsc_file.readlines()
    def strip_comments(line):
        if '#' in line:
            line = line[:line.index('#')]
        return line

    stripped_data = [strip_comments(line) for line in data]
    petsc_argv += '\n'.join(stripped_data).split()
    log("PETSc options from commandline")
    log(str(petsc_argv))

Comm.argv = petsc_argv
comm = Comm.init()
Profiling.procID=comm.rank()
if opts.logLevel > 0:
    #mwf looks like just gets .py.log if no sso file given
    #Profiling.openLog(args[0][-3:]+".log",opts.logLevel)
    if len(args) == 0:
        Profiling.openLog("proteus.log",opts.logLevel)
    elif len(args[0].split(' ')) == 1:
        Profiling.openLog(args[0].split('.')[0]+".log",opts.logLevel)
    else:
        Profiling.openLog(args[0][-3:]+".log",opts.logLevel)
if opts.logAllProcesses:
    Profiling.logAllProcesses = True

#blanket import statements can go below here now that petsc4py should be initialized
from proteus import *
Пример #19
0
    def __init__(self,
                 uDict,
                 phiDict,
                 testSpaceDict,
                 matType,
                 dofBoundaryConditionsDict,
                 dofBoundaryConditionsSetterDict,
                 coefficients,
                 elementQuadrature,
                 elementBoundaryQuadrature,
                 fluxBoundaryConditionsDict=None,
                 advectiveFluxBoundaryConditionsSetterDict=None,
                 diffusiveFluxBoundaryConditionsSetterDictDict=None,
                 stressTraceBoundaryConditionsSetterDict=None,
                 stabilization=None,
                 shockCapturing=None,
                 conservativeFluxDict=None,
                 numericalFluxType=None,
                 TimeIntegrationClass=None,
                 massLumping=False,
                 reactionLumping=False,
                 options=None,
                 name='defaultName',
                 reuse_trial_and_test_quadrature=True,
                 sd=True,
                 movingDomain=False,
                 bdyNullSpace=True):
        self.bdyNullSpace = bdyNullSpace
        from proteus import Comm
        #
        # set the objects describing the method and boundary conditions
        #
        self.movingDomain = movingDomain
        self.tLast_mesh = None
        #
        self.name = name
        self.sd = sd
        self.Hess = False
        self.lowmem = True
        self.timeTerm = True  # allow turning off  the  time derivative
        # self.lowmem=False
        self.testIsTrial = True
        self.phiTrialIsTrial = True
        self.u = uDict
        self.ua = {}  # analytical solutions
        self.phi = phiDict
        self.dphi = {}
        self.matType = matType
        # mwf try to reuse test and trial information across components if
        # spaces are the same
        self.reuse_test_trial_quadrature = reuse_trial_and_test_quadrature  # True#False
        if self.reuse_test_trial_quadrature:
            for ci in range(1, coefficients.nc):
                assert self.u[ci].femSpace.__class__.__name__ == self.u[
                    0].femSpace.__class__.__name__, "to reuse_test_trial_quad all femSpaces must be the same!"
        # Simplicial Mesh
        # assume the same mesh for  all components for now
        self.mesh = self.u[0].femSpace.mesh
        self.testSpace = testSpaceDict
        self.dirichletConditions = dofBoundaryConditionsDict
        # explicit Dirichlet  conditions for now, no Dirichlet BC constraints
        self.dirichletNodeSetList = None
        self.coefficients = coefficients
        self.coefficients.initializeMesh(self.mesh)
        self.nc = self.coefficients.nc
        self.stabilization = stabilization
        self.shockCapturing = shockCapturing
        # no velocity post-processing for now
        self.conservativeFlux = conservativeFluxDict
        self.fluxBoundaryConditions = fluxBoundaryConditionsDict
        self.diffusiveFluxBoundaryConditionsSetterDictDict = diffusiveFluxBoundaryConditionsSetterDictDict
        # determine whether  the stabilization term is nonlinear
        self.stabilizationIsNonlinear = False
        # cek come back
        if self.stabilization is not None:
            for ci in range(self.nc):
                if coefficients.mass.has_key(ci):
                    for flag in coefficients.mass[ci].values():
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if coefficients.advection.has_key(ci):
                    for flag in coefficients.advection[ci].values():
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if coefficients.diffusion.has_key(ci):
                    for diffusionDict in coefficients.diffusion[ci].values():
                        for flag in diffusionDict.values():
                            if flag != 'constant':
                                self.stabilizationIsNonlinear = True
                if coefficients.potential.has_key(ci):
                    for flag in coefficients.potential[ci].values():
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if coefficients.reaction.has_key(ci):
                    for flag in coefficients.reaction[ci].values():
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if coefficients.hamiltonian.has_key(ci):
                    for flag in coefficients.hamiltonian[ci].values():
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
        # determine if we need element boundary storage
        self.elementBoundaryIntegrals = {}
        for ci in range(self.nc):
            self.elementBoundaryIntegrals[ci] = (
                (self.conservativeFlux is not None) or (
                    numericalFluxType is not None) or (
                    self.fluxBoundaryConditions[ci] == 'outFlow') or (
                    self.fluxBoundaryConditions[ci] == 'mixedFlow') or (
                    self.fluxBoundaryConditions[ci] == 'setFlow'))
        #
        # calculate some dimensions
        #
        # assume same space dim for all variables
        self.nSpace_global = self.u[0].femSpace.nSpace_global
        self.nDOF_trial_element = [
            u_j.femSpace.max_nDOF_element for u_j in self.u.values()]
        self.nDOF_phi_trial_element = [
            phi_k.femSpace.max_nDOF_element for phi_k in self.phi.values()]
        self.n_phi_ip_element = [
            phi_k.femSpace.referenceFiniteElement.interpolationConditions.nQuadraturePoints for phi_k in self.phi.values()]
        self.nDOF_test_element = [
            femSpace.max_nDOF_element for femSpace in self.testSpace.values()]
        self.nFreeDOF_global = [
            dc.nFreeDOF_global for dc in self.dirichletConditions.values()]
        self.nVDOF_element = sum(self.nDOF_trial_element)
        self.nFreeVDOF_global = sum(self.nFreeDOF_global)
        #
        NonlinearEquation.__init__(self, self.nFreeVDOF_global)
        #
        # build the quadrature point dictionaries from the input (this
        # is just for convenience so that the input doesn't have to be
        # complete)
        #
        elementQuadratureDict = {}
        elemQuadIsDict = isinstance(elementQuadrature, dict)
        if elemQuadIsDict:  # set terms manually
            for I in self.coefficients.elementIntegralKeys:
                if elementQuadrature.has_key(I):
                    elementQuadratureDict[I] = elementQuadrature[I]
                else:
                    elementQuadratureDict[I] = elementQuadrature['default']
        else:
            for I in self.coefficients.elementIntegralKeys:
                elementQuadratureDict[I] = elementQuadrature
        if self.stabilization is not None:
            for I in self.coefficients.elementIntegralKeys:
                if elemQuadIsDict:
                    if elementQuadrature.has_key(I):
                        elementQuadratureDict[
                            ('stab',) + I[1:]] = elementQuadrature[I]
                    else:
                        elementQuadratureDict[
                            ('stab',) + I[1:]] = elementQuadrature['default']
                else:
                    elementQuadratureDict[
                        ('stab',) + I[1:]] = elementQuadrature
        if self.shockCapturing is not None:
            for ci in self.shockCapturing.components:
                if elemQuadIsDict:
                    if elementQuadrature.has_key(('numDiff', ci, ci)):
                        elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature[
                            ('numDiff', ci, ci)]
                    else:
                        elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature[
                            'default']
                else:
                    elementQuadratureDict[
                        ('numDiff', ci, ci)] = elementQuadrature
        if massLumping:
            for ci in self.coefficients.mass.keys():
                elementQuadratureDict[('m', ci)] = Quadrature.SimplexLobattoQuadrature(
                    self.nSpace_global, 1)
            for I in self.coefficients.elementIntegralKeys:
                elementQuadratureDict[
                    ('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
        if reactionLumping:
            for ci in self.coefficients.mass.keys():
                elementQuadratureDict[('r', ci)] = Quadrature.SimplexLobattoQuadrature(
                    self.nSpace_global, 1)
            for I in self.coefficients.elementIntegralKeys:
                elementQuadratureDict[
                    ('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
        elementBoundaryQuadratureDict = {}
        if isinstance(elementBoundaryQuadrature, dict):  # set terms manually
            for I in self.coefficients.elementBoundaryIntegralKeys:
                if elementBoundaryQuadrature.has_key(I):
                    elementBoundaryQuadratureDict[
                        I] = elementBoundaryQuadrature[I]
                else:
                    elementBoundaryQuadratureDict[
                        I] = elementBoundaryQuadrature['default']
        else:
            for I in self.coefficients.elementBoundaryIntegralKeys:
                elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature
        #
        # find the union of all element quadrature points and
        # build a quadrature rule for each integral that has a
        # weight at each point in the union
        # mwf include tag telling me which indices are which quadrature rule?
        (self.elementQuadraturePoints, self.elementQuadratureWeights,
         self.elementQuadratureRuleIndeces) = Quadrature.buildUnion(elementQuadratureDict)
        self.nQuadraturePoints_element = self.elementQuadraturePoints.shape[0]
        self.nQuadraturePoints_global = self.nQuadraturePoints_element * \
            self.mesh.nElements_global
        #
        # Repeat the same thing for the element boundary quadrature
        #
        (self.elementBoundaryQuadraturePoints, self.elementBoundaryQuadratureWeights,
         self.elementBoundaryQuadratureRuleIndeces) = Quadrature.buildUnion(elementBoundaryQuadratureDict)
        self.nElementBoundaryQuadraturePoints_elementBoundary = self.elementBoundaryQuadraturePoints.shape[
            0]
        self.nElementBoundaryQuadraturePoints_global = (
            self.mesh.nElements_global *
            self.mesh.nElementBoundaries_element *
            self.nElementBoundaryQuadraturePoints_elementBoundary)
        if type(self.u[0].femSpace) == C0_AffineLinearOnSimplexWithNodalBasis:
            # print self.nQuadraturePoints_element
            if self.nSpace_global == 3:
                assert(self.nQuadraturePoints_element == 5)
            elif self.nSpace_global == 2:
                assert(self.nQuadraturePoints_element == 6)
            elif self.nSpace_global == 1:
                assert(self.nQuadraturePoints_element == 3)

            # print self.nElementBoundaryQuadraturePoints_elementBoundary
            if self.nSpace_global == 3:
                assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 4)
            elif self.nSpace_global == 2:
                assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 4)
            elif self.nSpace_global == 1:
                assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 1)

        #
        # simplified allocations for test==trial and also check if space is mixed or not
        #
        self.added_mass_i = 0;
        self.Aij = np.zeros((self.coefficients.flags_rigidbody.shape[0], 6, 6), 'd')
        self.q = {}
        self.ebq = {}
        self.ebq_global = {}
        self.ebqe = {}
        self.phi_ip = {}
        # mesh
        #self.q['x'] = numpy.zeros((self.mesh.nElements_global,self.nQuadraturePoints_element,3),'d')
        self.ebqe['x'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             3),
            'd')
        self.q[('u', 0)] = numpy.zeros(
            (self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
        self.q[
            ('grad(u)',
             0)] = numpy.zeros(
            (self.mesh.nElements_global,
             self.nQuadraturePoints_element,
             self.nSpace_global),
            'd')
        self.ebqe[
            ('u',
             0)] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary),
            'd')
        self.ebqe[
            ('grad(u)',
             0)] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global),
            'd')

        self.q[('v', 0)] = numpy.zeros(
            (self.mesh.nElements_global,
             self.nQuadraturePoints_element,
             self.nDOF_trial_element[0]),
            'd')
        self.q['J'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.nQuadraturePoints_element,
             self.nSpace_global,
             self.nSpace_global),
            'd')
        self.q['det(J)'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.nQuadraturePoints_element),
            'd')
        self.q['inverse(J)'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.nQuadraturePoints_element,
             self.nSpace_global,
             self.nSpace_global),
            'd')
        self.ebq[('v', 0)] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nDOF_trial_element[0]),
            'd')
        self.ebq[('w', 0)] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nDOF_trial_element[0]),
            'd')
        self.ebq['x'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             3),
            'd')
        self.ebq['hat(x)'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             3),
            'd')
        self.ebq['inverse(J)'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global,
             self.nSpace_global),
            'd')
        self.ebq['g'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global - 1,
             self.nSpace_global - 1),
            'd')
        self.ebq['sqrt(det(g))'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary),
            'd')
        self.ebq['n'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global),
            'd')
        self.ebq[('dS_u', 0)] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary),
            'd')
        self.ebqe['dS'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary),
            'd')
        self.ebqe[('dS_u', 0)] = self.ebqe['dS']
        self.ebqe['n'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global),
            'd')
        self.ebqe['inverse(J)'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global,
             self.nSpace_global),
            'd')
        self.ebqe['g'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global - 1,
             self.nSpace_global - 1),
            'd')
        self.ebqe['sqrt(det(g))'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary),
            'd')
        self.ebq_global['n'] = numpy.zeros(
            (self.mesh.nElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global),
            'd')
        self.ebq_global['x'] = numpy.zeros(
            (self.mesh.nElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             3),
            'd')
        self.ebqe[('diffusiveFlux_bc_flag', 0, 0)] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'i')
        self.ebqe[('diffusiveFlux_bc', 0, 0)] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
        self.ebqe[('diffusiveFlux', 0, 0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
        self.points_elementBoundaryQuadrature = set()
        self.scalars_elementBoundaryQuadrature = set(
            [('u', ci) for ci in range(self.nc)])
        self.vectors_elementBoundaryQuadrature = set()
        self.tensors_elementBoundaryQuadrature = set()
        logEvent(memory("element and element boundary Jacobians",
                   "OneLevelTransport"), level=4)
        self.inflowBoundaryBC = {}
        self.inflowBoundaryBC_values = {}
        self.inflowFlux = {}
        for cj in range(self.nc):
            self.inflowBoundaryBC[cj] = numpy.zeros(
                (self.mesh.nExteriorElementBoundaries_global,), 'i')
            self.inflowBoundaryBC_values[cj] = numpy.zeros(
                (self.mesh.nExteriorElementBoundaries_global, self.nDOF_trial_element[cj]), 'd')
            self.inflowFlux[cj] = numpy.zeros(
                (self.mesh.nExteriorElementBoundaries_global,
                 self.nElementBoundaryQuadraturePoints_elementBoundary),
                'd')
        self.internalNodes = set(range(self.mesh.nNodes_global))
        # identify the internal nodes this is ought to be in mesh
        # \todo move this to mesh
        for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
            ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
            eN_global = self.mesh.elementBoundaryElementsArray[ebN, 0]
            ebN_element = self.mesh.elementBoundaryLocalElementBoundariesArray[
                ebN, 0]
            for i in range(self.mesh.nNodes_element):
                if i != ebN_element:
                    I = self.mesh.elementNodesArray[eN_global, i]
                    self.internalNodes -= set([I])
        self.nNodes_internal = len(self.internalNodes)
        self.internalNodesArray = numpy.zeros((self.nNodes_internal,), 'i')
        for nI, n in enumerate(self.internalNodes):
            self.internalNodesArray[nI] = n
        #
        del self.internalNodes
        self.internalNodes = None
        logEvent("Updating local to global mappings", 2)
        self.updateLocal2Global()
        logEvent("Building time integration object", 2)
        logEvent(memory("inflowBC, internalNodes,updateLocal2Global",
                   "OneLevelTransport"), level=4)
        # mwf for interpolating subgrid error for gradients etc
        if self.stabilization and self.stabilization.usesGradientStabilization:
            self.timeIntegration = TimeIntegrationClass(
                self, integrateInterpolationPoints=True)
        else:
            self.timeIntegration = TimeIntegrationClass(self)

        if options is not None:
            self.timeIntegration.setFromOptions(options)
        logEvent(memory("TimeIntegration", "OneLevelTransport"), level=4)
        logEvent("Calculating numerical quadrature formulas", 2)
        self.calculateQuadrature()
        self.setupFieldStrides()

        comm = Comm.get()
        self.comm = comm
        if comm.size() > 1:
            assert numericalFluxType is not None and numericalFluxType.useWeakDirichletConditions, "You must use a numerical flux to apply weak boundary conditions for parallel runs"

        logEvent(memory("stride+offset", "OneLevelTransport"), level=4)
        if numericalFluxType is not None:
            if options is None or options.periodicDirichletConditions is None:
                self.numericalFlux = numericalFluxType(
                    self,
                    dofBoundaryConditionsSetterDict,
                    advectiveFluxBoundaryConditionsSetterDict,
                    diffusiveFluxBoundaryConditionsSetterDictDict)
            else:
                self.numericalFlux = numericalFluxType(
                    self,
                    dofBoundaryConditionsSetterDict,
                    advectiveFluxBoundaryConditionsSetterDict,
                    diffusiveFluxBoundaryConditionsSetterDictDict,
                    options.periodicDirichletConditions)
        else:
            self.numericalFlux = None
        # strong Dirichlet
        self.dirichletConditionsForceDOF = {0: DOFBoundaryConditions(self.u[cj].femSpace, dofBoundaryConditionsSetterDict[cj], weakDirichletConditions=False)}
        # set penalty terms
        # cek todo move into numerical flux initialization
        if self.ebq_global.has_key('penalty'):
            for ebN in range(self.mesh.nElementBoundaries_global):
                for k in range(
                        self.nElementBoundaryQuadraturePoints_elementBoundary):
                    self.ebq_global['penalty'][ebN, k] = self.numericalFlux.penalty_constant / (
                        self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power)
        # penalty term
        # cek move  to Numerical flux initialization
        if self.ebqe.has_key('penalty'):
            for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
                ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
                for k in range(
                        self.nElementBoundaryQuadraturePoints_elementBoundary):
                    self.ebqe['penalty'][ebNE, k] = self.numericalFlux.penalty_constant / \
                        self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power
        logEvent(memory("numericalFlux", "OneLevelTransport"), level=4)
        self.elementEffectiveDiametersArray = self.mesh.elementInnerDiametersArray
        # use post processing tools to get conservative fluxes, None by default
        from proteus import PostProcessingTools
        self.velocityPostProcessor = PostProcessingTools.VelocityPostProcessingChooser(
            self)
        logEvent(memory("velocity postprocessor", "OneLevelTransport"), level=4)
        # helper for writing out data storage
        from proteus import Archiver
        self.elementQuadratureDictionaryWriter = Archiver.XdmfWriter()
        self.elementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
        self.exteriorElementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
        self.globalResidualDummy = None
        compKernelFlag = 0
        self.addedMass = cAddedMass.AddedMass(
            self.nSpace_global,
            self.nQuadraturePoints_element,
            self.u[0].femSpace.elementMaps.localFunctionSpace.dim,
            self .u[0].femSpace.referenceFiniteElement.localFunctionSpace.dim,
            self.testSpace[0].referenceFiniteElement.localFunctionSpace.dim,
            self.nElementBoundaryQuadraturePoints_elementBoundary,
            compKernelFlag)
        self.barycenters = self.coefficients.barycenters
        self.flags_rigidbody = self.coefficients.flags_rigidbody
Пример #20
0
def test_2DgmshLoadAndAdapt(verbose=0):
    """Test for loading gmsh mesh through PUMI, estimating error and adapting for 
    a 2D Couette flow case"""
    testDir=os.path.dirname(os.path.abspath(__file__))
    Model=testDir + '/Couette2D.null'
    Mesh=testDir + '/Couette2D.msh'
    domain = Domain.PUMIDomain(dim=2) #initialize the domain
    domain.PUMIMesh=MeshAdaptPUMI.MeshAdaptPUMI(hmax=0.01, hmin=0.008, numIter=1,sfConfig='ERM',maType='isotropic',targetError=1)
    domain.PUMIMesh.loadModelAndMesh(Model, Mesh)
    domain.faceList=[[14],[12],[11],[13]]

    mesh = MeshTools.TriangularMesh()
    mesh.cmesh = cmeshTools.CMesh()
    comm = Comm.init()

    nElements_initial = mesh.nElements_global
    mesh.convertFromPUMI(domain.PUMIMesh, domain.faceList,domain.regList, parallel = comm.size() > 1, dim = domain.nd)

    domain.PUMIMesh.transferFieldToPUMI("coordinates",mesh.nodeArray)

    rho = numpy.array([998.2,998.2])
    nu = numpy.array([1.004e-6, 1.004e-6])
    g = numpy.asarray([0.0,0.0])
    deltaT = 1.0 #dummy number
    domain.PUMIMesh.transferPropertiesToPUMI(rho,nu,g,deltaT)

    #Couette Flow
    Lz = 0.05
    Uinf = 2e-3
    #hard code solution
    vector=numpy.zeros((mesh.nNodes_global,3),'d')
    dummy = numpy.zeros(mesh.nNodes_global); 
    vector[:,0] = Uinf*mesh.nodeArray[:,1]/Lz #v-velocity
    vector[:,1] = dummy
    vector[:,2] = dummy
    domain.PUMIMesh.transferFieldToPUMI("velocity", vector)
    del vector
    del dummy

    scalar=numpy.zeros((mesh.nNodes_global,1),'d')
    domain.PUMIMesh.transferFieldToPUMI("p", scalar)

    scalar[:,0] = mesh.nodeArray[:,1]
    domain.PUMIMesh.transferFieldToPUMI("phi", scalar)
    del scalar

    scalar = numpy.zeros((mesh.nNodes_global,1),'d')+1.0
    domain.PUMIMesh.transferFieldToPUMI("vof", scalar)

    errorTotal=domain.PUMIMesh.get_local_error()
    ok(errorTotal<1e-14)

    ok(domain.PUMIMesh.willAdapt(),1)

    domain.PUMIMesh.adaptPUMIMesh()
    
    mesh = MeshTools.TriangularMesh()
    mesh.convertFromPUMI(domain.PUMIMesh,
                     domain.faceList,
                     domain.regList,
                     parallel = comm.size() > 1,
                     dim = domain.nd)
    nElements_final = mesh.nElements_global
    ok(nElements_final>nElements_initial)
Пример #21
0
    def __init__(self,
                 uDict,
                 phiDict,
                 testSpaceDict,
                 matType,
                 dofBoundaryConditionsDict,
                 dofBoundaryConditionsSetterDict,
                 coefficients,
                 elementQuadrature,
                 elementBoundaryQuadrature,
                 fluxBoundaryConditionsDict=None,
                 advectiveFluxBoundaryConditionsSetterDict=None,
                 diffusiveFluxBoundaryConditionsSetterDictDict=None,
                 stressTraceBoundaryConditionsSetterDict=None,
                 stabilization=None,
                 shockCapturing=None,
                 conservativeFluxDict=None,
                 numericalFluxType=None,
                 TimeIntegrationClass=None,
                 massLumping=False,
                 reactionLumping=False,
                 options=None,
                 name='defaultName',
                 reuse_trial_and_test_quadrature=True,
                 sd=True,
                 movingDomain=False):
        from proteus import Comm
        #
        # set the objects describing the method and boundary conditions
        #
        self.movingDomain = movingDomain
        self.tLast_mesh = None
        #
        self.name = name
        self.sd = sd
        self.Hess = False
        self.lowmem = True
        self.timeTerm = True  # allow turning off  the  time derivative
        # self.lowmem=False
        self.testIsTrial = True
        self.phiTrialIsTrial = True
        self.u = uDict
        self.ua = {}  # analytical solutions
        self.phi = phiDict
        self.dphi = {}
        self.matType = matType
        # mwf try to reuse test and trial information across components if
        # spaces are the same
        self.reuse_test_trial_quadrature = reuse_trial_and_test_quadrature  # True#False
        if self.reuse_test_trial_quadrature:
            for ci in range(1, coefficients.nc):
                assert self.u[ci].femSpace.__class__.__name__ == self.u[
                    0].femSpace.__class__.__name__, "to reuse_test_trial_quad all femSpaces must be the same!"
        # Simplicial Mesh
        # assume the same mesh for  all components for now
        self.mesh = self.u[0].femSpace.mesh
        self.testSpace = testSpaceDict
        self.dirichletConditions = dofBoundaryConditionsDict
        # explicit Dirichlet  conditions for now, no Dirichlet BC constraints
        self.dirichletNodeSetList = None
        self.coefficients = coefficients
        self.coefficients.initializeMesh(self.mesh)
        self.nc = self.coefficients.nc
        self.stabilization = stabilization
        self.shockCapturing = shockCapturing
        # no velocity post-processing for now
        self.conservativeFlux = conservativeFluxDict
        self.fluxBoundaryConditions = fluxBoundaryConditionsDict
        self.advectiveFluxBoundaryConditionsSetterDict = advectiveFluxBoundaryConditionsSetterDict
        self.diffusiveFluxBoundaryConditionsSetterDictDict = diffusiveFluxBoundaryConditionsSetterDictDict
        # determine whether  the stabilization term is nonlinear
        self.stabilizationIsNonlinear = False
        # cek come back
        if self.stabilization is not None:
            for ci in range(self.nc):
                if coefficients.mass.has_key(ci):
                    for flag in coefficients.mass[ci].values():
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if coefficients.advection.has_key(ci):
                    for flag in coefficients.advection[ci].values():
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if coefficients.diffusion.has_key(ci):
                    for diffusionDict in coefficients.diffusion[ci].values():
                        for flag in diffusionDict.values():
                            if flag != 'constant':
                                self.stabilizationIsNonlinear = True
                if coefficients.potential.has_key(ci):
                    for flag in coefficients.potential[ci].values():
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if coefficients.reaction.has_key(ci):
                    for flag in coefficients.reaction[ci].values():
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
                if coefficients.hamiltonian.has_key(ci):
                    for flag in coefficients.hamiltonian[ci].values():
                        if flag == 'nonlinear':
                            self.stabilizationIsNonlinear = True
        # determine if we need element boundary storage
        self.elementBoundaryIntegrals = {}
        for ci in range(self.nc):
            self.elementBoundaryIntegrals[ci] = (
                (self.conservativeFlux is not None) or (
                    numericalFluxType is not None) or (
                    self.fluxBoundaryConditions[ci] == 'outFlow') or (
                    self.fluxBoundaryConditions[ci] == 'mixedFlow') or (
                    self.fluxBoundaryConditions[ci] == 'setFlow'))
        #
        # calculate some dimensions
        #
        # assume same space dim for all variables
        self.nSpace_global = self.u[0].femSpace.nSpace_global
        self.nDOF_trial_element = [
            u_j.femSpace.max_nDOF_element for u_j in self.u.values()]
        self.nDOF_phi_trial_element = [
            phi_k.femSpace.max_nDOF_element for phi_k in self.phi.values()]
        self.n_phi_ip_element = [
            phi_k.femSpace.referenceFiniteElement.interpolationConditions.nQuadraturePoints for phi_k in self.phi.values()]
        self.nDOF_test_element = [
            femSpace.max_nDOF_element for femSpace in self.testSpace.values()]
        self.nFreeDOF_global = [
            dc.nFreeDOF_global for dc in self.dirichletConditions.values()]
        self.nVDOF_element = sum(self.nDOF_trial_element)
        self.nFreeVDOF_global = sum(self.nFreeDOF_global)
        #
        NonlinearEquation.__init__(self, self.nFreeVDOF_global)
        #
        # build the quadrature point dictionaries from the input (this
        # is just for convenience so that the input doesn't have to be
        # complete)
        #
        elementQuadratureDict = {}
        elemQuadIsDict = isinstance(elementQuadrature, dict)
        if elemQuadIsDict:  # set terms manually
            for I in self.coefficients.elementIntegralKeys:
                if elementQuadrature.has_key(I):
                    elementQuadratureDict[I] = elementQuadrature[I]
                else:
                    elementQuadratureDict[I] = elementQuadrature['default']
        else:
            for I in self.coefficients.elementIntegralKeys:
                elementQuadratureDict[I] = elementQuadrature
        if self.stabilization is not None:
            for I in self.coefficients.elementIntegralKeys:
                if elemQuadIsDict:
                    if elementQuadrature.has_key(I):
                        elementQuadratureDict[
                            ('stab',) + I[1:]] = elementQuadrature[I]
                    else:
                        elementQuadratureDict[
                            ('stab',) + I[1:]] = elementQuadrature['default']
                else:
                    elementQuadratureDict[
                        ('stab',) + I[1:]] = elementQuadrature
        if self.shockCapturing is not None:
            for ci in self.shockCapturing.components:
                if elemQuadIsDict:
                    if elementQuadrature.has_key(('numDiff', ci, ci)):
                        elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature[
                            ('numDiff', ci, ci)]
                    else:
                        elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature[
                            'default']
                else:
                    elementQuadratureDict[
                        ('numDiff', ci, ci)] = elementQuadrature
        if massLumping:
            for ci in self.coefficients.mass.keys():
                elementQuadratureDict[('m', ci)] = Quadrature.SimplexLobattoQuadrature(
                    self.nSpace_global, 1)
            for I in self.coefficients.elementIntegralKeys:
                elementQuadratureDict[
                    ('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
        if reactionLumping:
            for ci in self.coefficients.mass.keys():
                elementQuadratureDict[('r', ci)] = Quadrature.SimplexLobattoQuadrature(
                    self.nSpace_global, 1)
            for I in self.coefficients.elementIntegralKeys:
                elementQuadratureDict[
                    ('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
        elementBoundaryQuadratureDict = {}
        if isinstance(elementBoundaryQuadrature, dict):  # set terms manually
            for I in self.coefficients.elementBoundaryIntegralKeys:
                if elementBoundaryQuadrature.has_key(I):
                    elementBoundaryQuadratureDict[
                        I] = elementBoundaryQuadrature[I]
                else:
                    elementBoundaryQuadratureDict[
                        I] = elementBoundaryQuadrature['default']
        else:
            for I in self.coefficients.elementBoundaryIntegralKeys:
                elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature
        #
        # find the union of all element quadrature points and
        # build a quadrature rule for each integral that has a
        # weight at each point in the union
        # mwf include tag telling me which indices are which quadrature rule?
        (self.elementQuadraturePoints, self.elementQuadratureWeights,
         self.elementQuadratureRuleIndeces) = Quadrature.buildUnion(elementQuadratureDict)
        self.nQuadraturePoints_element = self.elementQuadraturePoints.shape[0]
        self.nQuadraturePoints_global = self.nQuadraturePoints_element * \
            self.mesh.nElements_global
        #
        # Repeat the same thing for the element boundary quadrature
        #
        (self.elementBoundaryQuadraturePoints, self.elementBoundaryQuadratureWeights,
         self.elementBoundaryQuadratureRuleIndeces) = Quadrature.buildUnion(elementBoundaryQuadratureDict)
        self.nElementBoundaryQuadraturePoints_elementBoundary = self.elementBoundaryQuadraturePoints.shape[
            0]
        self.nElementBoundaryQuadraturePoints_global = (
            self.mesh.nElements_global *
            self.mesh.nElementBoundaries_element *
            self.nElementBoundaryQuadraturePoints_elementBoundary)
        if type(self.u[0].femSpace) == C0_AffineLinearOnSimplexWithNodalBasis:
            # print self.nQuadraturePoints_element
            if self.nSpace_global == 3:
                assert(self.nQuadraturePoints_element == 5)
            elif self.nSpace_global == 2:
                assert(self.nQuadraturePoints_element == 6)
            elif self.nSpace_global == 1:
                assert(self.nQuadraturePoints_element == 3)

            # print self.nElementBoundaryQuadraturePoints_elementBoundary
            if self.nSpace_global == 3:
                assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 4)
            elif self.nSpace_global == 2:
                assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 4)
            elif self.nSpace_global == 1:
                assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 1)

        # pdb.set_trace()
        #
        # simplified allocations for test==trial and also check if space is mixed or not
        #
        self.q = {}
        self.ebq = {}
        self.ebq_global = {}
        self.ebqe = {}
        self.phi_ip = {}
        # mesh
        #self.q['x'] = numpy.zeros((self.mesh.nElements_global,self.nQuadraturePoints_element,3),'d')
        self.ebqe['x'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             3),
            'd')
        self.q[('u', 0)] = numpy.zeros(
            (self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
        self.q[
            ('grad(u)',
             0)] = numpy.zeros(
            (self.mesh.nElements_global,
             self.nQuadraturePoints_element,
             self.nSpace_global),
            'd')
        self.ebqe[
            ('u',
             0)] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary),
            'd')
        self.ebqe[
            ('grad(u)',
             0)] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global),
            'd')

        self.q[('v',0)] = numpy.zeros(
            (self.mesh.nElements_global,
             self.nQuadraturePoints_element,
             self.nDOF_trial_element[0]),
            'd')
        self.q['J'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.nQuadraturePoints_element,
             self.nSpace_global,
             self.nSpace_global),
            'd')
        self.q['det(J)'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.nQuadraturePoints_element),
            'd')
        self.q['inverse(J)'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.nQuadraturePoints_element,
             self.nSpace_global,
             self.nSpace_global),
            'd')
        self.ebq[('v',0)] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nDOF_trial_element[0]),
            'd')
        self.ebq[('w',0)] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nDOF_trial_element[0]),
            'd')
        self.ebq['x'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             3),
            'd')
        self.ebq['hat(x)'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             3),
            'd')
        self.ebq['inverse(J)'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global,
             self.nSpace_global),
            'd')
        self.ebq['g'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global-1,
             self.nSpace_global-1),
            'd')
        self.ebq['sqrt(det(g))'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary),
            'd')
        self.ebq['n'] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global),
            'd')
        self.ebq[('dS_u',0)] = numpy.zeros(
            (self.mesh.nElements_global,
             self.mesh.nElementBoundaries_element,
             self.nElementBoundaryQuadraturePoints_elementBoundary),
            'd')
        self.ebqe['dS'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary),
            'd')
        self.ebqe[('dS_u',0)] = self.ebqe['dS']
        self.ebqe['n'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global),
            'd')
        self.ebqe['inverse(J)'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global,
             self.nSpace_global),
            'd')
        self.ebqe['g'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global-1,
             self.nSpace_global-1),
            'd')
        self.ebqe['sqrt(det(g))'] = numpy.zeros(
            (self.mesh.nExteriorElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary),
            'd')
        self.ebq_global['n'] = numpy.zeros(
            (self.mesh.nElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             self.nSpace_global),
            'd')
        self.ebq_global['x'] = numpy.zeros(
            (self.mesh.nElementBoundaries_global,
             self.nElementBoundaryQuadraturePoints_elementBoundary,
             3),
            'd')
        self.ebqe[('advectiveFlux_bc_flag',0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global,self.nElementBoundaryQuadraturePoints_elementBoundary),'i')
        self.ebqe[('diffusiveFlux_bc_flag',0,0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global,self.nElementBoundaryQuadraturePoints_elementBoundary),'i')
        self.ebqe[('advectiveFlux_bc',0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global,self.nElementBoundaryQuadraturePoints_elementBoundary),'d')
        self.ebqe[('diffusiveFlux_bc',0,0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global,self.nElementBoundaryQuadraturePoints_elementBoundary),'d')
        self.ebqe[('advectiveFlux',0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global,self.nElementBoundaryQuadraturePoints_elementBoundary),'d')
        self.ebqe[('diffusiveFlux',0,0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global,self.nElementBoundaryQuadraturePoints_elementBoundary),'d')
        self.points_elementBoundaryQuadrature = set()
        self.scalars_elementBoundaryQuadrature = set(
            [('u', ci) for ci in range(self.nc)])
        self.vectors_elementBoundaryQuadrature = set()
        self.tensors_elementBoundaryQuadrature = set()
        log(memory("element and element boundary Jacobians",
                   "OneLevelTransport"), level=4)
        self.inflowBoundaryBC = {}
        self.inflowBoundaryBC_values = {}
        self.inflowFlux = {}
        for cj in range(self.nc):
            self.inflowBoundaryBC[cj] = numpy.zeros(
                (self.mesh.nExteriorElementBoundaries_global,), 'i')
            self.inflowBoundaryBC_values[cj] = numpy.zeros(
                (self.mesh.nExteriorElementBoundaries_global, self.nDOF_trial_element[cj]), 'd')
            self.inflowFlux[cj] = numpy.zeros(
                (self.mesh.nExteriorElementBoundaries_global,
                 self.nElementBoundaryQuadraturePoints_elementBoundary),
                'd')
        self.internalNodes = set(range(self.mesh.nNodes_global))
        # identify the internal nodes this is ought to be in mesh
        # \todo move this to mesh
        for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
            ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
            eN_global = self.mesh.elementBoundaryElementsArray[ebN, 0]
            ebN_element = self.mesh.elementBoundaryLocalElementBoundariesArray[
                ebN, 0]
            for i in range(self.mesh.nNodes_element):
                if i != ebN_element:
                    I = self.mesh.elementNodesArray[eN_global, i]
                    self.internalNodes -= set([I])
        self.nNodes_internal = len(self.internalNodes)
        self.internalNodesArray = numpy.zeros((self.nNodes_internal,), 'i')
        for nI, n in enumerate(self.internalNodes):
            self.internalNodesArray[nI] = n
        #
        del self.internalNodes
        self.internalNodes = None
        log("Updating local to global mappings", 2)
        self.updateLocal2Global()
        log("Building time integration object", 2)
        log(memory("inflowBC, internalNodes,updateLocal2Global",
                   "OneLevelTransport"), level=4)
        # mwf for interpolating subgrid error for gradients etc
        if self.stabilization and self.stabilization.usesGradientStabilization:
            self.timeIntegration = TimeIntegrationClass(
                self, integrateInterpolationPoints=True)
        else:
            self.timeIntegration = TimeIntegrationClass(self)

        if options is not None:
            self.timeIntegration.setFromOptions(options)
        log(memory("TimeIntegration", "OneLevelTransport"), level=4)
        log("Calculating numerical quadrature formulas", 2)
        self.calculateQuadrature()
        self.setupFieldStrides()

        comm = Comm.get()
        self.comm = comm
        if comm.size() > 1:
            assert numericalFluxType is not None and numericalFluxType.useWeakDirichletConditions, "You must use a numerical flux to apply weak boundary conditions for parallel runs"

        log(memory("stride+offset", "OneLevelTransport"), level=4)
        if numericalFluxType is not None:
            if options is None or options.periodicDirichletConditions is None:
                self.numericalFlux = numericalFluxType(
                    self,
                    dofBoundaryConditionsSetterDict,
                    advectiveFluxBoundaryConditionsSetterDict,
                    diffusiveFluxBoundaryConditionsSetterDictDict)
            else:
                self.numericalFlux = numericalFluxType(
                    self,
                    dofBoundaryConditionsSetterDict,
                    advectiveFluxBoundaryConditionsSetterDict,
                    diffusiveFluxBoundaryConditionsSetterDictDict,
                    options.periodicDirichletConditions)
        else:
            self.numericalFlux = None
        # set penalty terms
        # cek todo move into numerical flux initialization
        if self.ebq_global.has_key('penalty'):
            for ebN in range(self.mesh.nElementBoundaries_global):
                for k in range(
                        self.nElementBoundaryQuadraturePoints_elementBoundary):
                    self.ebq_global['penalty'][ebN, k] = self.numericalFlux.penalty_constant / (
                        self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power)
        # penalty term
        # cek move  to Numerical flux initialization
        if self.ebqe.has_key('penalty'):
            for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
                ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
                for k in range(
                        self.nElementBoundaryQuadraturePoints_elementBoundary):
                    self.ebqe['penalty'][ebNE, k] = self.numericalFlux.penalty_constant / \
                        self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power
        log(memory("numericalFlux", "OneLevelTransport"), level=4)
        self.elementEffectiveDiametersArray = self.mesh.elementInnerDiametersArray
        # use post processing tools to get conservative fluxes, None by default
        from proteus import PostProcessingTools
        self.velocityPostProcessor = PostProcessingTools.VelocityPostProcessingChooser(
            self)
        log(memory("velocity postprocessor", "OneLevelTransport"), level=4)
        # helper for writing out data storage
        from proteus import Archiver
        self.elementQuadratureDictionaryWriter = Archiver.XdmfWriter()
        self.elementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
        self.exteriorElementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
        self.globalResidualDummy = None
        log("flux bc objects")
        for ci,fbcObject  in self.fluxBoundaryConditionsObjectsDict.iteritems():
            self.ebqe[('advectiveFlux_bc_flag',ci)] = numpy.zeros(self.ebqe[('advectiveFlux_bc',ci)].shape,'i')
            for t,g in fbcObject.advectiveFluxBoundaryConditionsDict.iteritems():
                if self.coefficients.advection.has_key(ci):
                    self.ebqe[('advectiveFlux_bc',ci)][t[0],t[1]] = g(self.ebqe[('x')][t[0],t[1]],self.timeIntegration.t)
                    self.ebqe[('advectiveFlux_bc_flag',ci)][t[0],t[1]] = 1
            for ck,diffusiveFluxBoundaryConditionsDict in fbcObject.diffusiveFluxBoundaryConditionsDictDict.iteritems():
                self.ebqe[('diffusiveFlux_bc_flag',ck,ci)] = numpy.zeros(self.ebqe[('diffusiveFlux_bc',ck,ci)].shape,'i')
                for t,g in diffusiveFluxBoundaryConditionsDict.iteritems():
                    self.ebqe[('diffusiveFlux_bc',ck,ci)][t[0],t[1]] = g(self.ebqe[('x')][t[0],t[1]],self.timeIntegration.t)
                    self.ebqe[('diffusiveFlux_bc_flag',ck,ci)][t[0],t[1]] = 1
        self.numericalFlux.setDirichletValues(self.ebqe)
        compKernelFlag = 0
        self.presinc = cPresInc(
            self.nSpace_global,
            self.nQuadraturePoints_element,
            self.u[0].femSpace.elementMaps.localFunctionSpace.dim,
            self .u[0].femSpace.referenceFiniteElement.localFunctionSpace.dim,
            self.testSpace[0].referenceFiniteElement.localFunctionSpace.dim,
            self.nElementBoundaryQuadraturePoints_elementBoundary,
            compKernelFlag)
Пример #22
0
def test_poiseuilleError(verbose=0):
    """Test for loading gmsh mesh through PUMI, estimating error for 
    a Poiseuille flow case. The estimated error should be larger than the
    exact error in the seminorm"""
    testDir = os.path.dirname(os.path.abspath(__file__))
    Model = testDir + '/Couette.null'
    Mesh = testDir + '/Couette.msh'

    domain = Domain.PUMIDomain()  #initialize the domain
    domain.PUMIMesh = MeshAdaptPUMI.MeshAdaptPUMI(hmax=0.01,
                                                  hmin=0.008,
                                                  numIter=1,
                                                  sfConfig=b'ERM',
                                                  maType=b'isotropic',
                                                  logType=b'off')
    domain.PUMIMesh.loadModelAndMesh(bytes(Model, 'utf-8'),
                                     bytes(Mesh, 'utf-8'))
    domain.faceList = [[80], [76], [42], [24], [82], [78]]
    domain.boundaryLabels = [1, 2, 3, 4, 5, 6]

    mesh = MeshTools.TetrahedralMesh()
    mesh.cmesh = cmeshTools.CMesh()
    comm = Comm.init()

    nElements_initial = mesh.nElements_global
    mesh.convertFromPUMI(domain,
                         domain.PUMIMesh,
                         domain.faceList,
                         domain.regList,
                         parallel=comm.size() > 1,
                         dim=domain.nd)

    domain.PUMIMesh.transferFieldToPUMI(b"coordinates", mesh.nodeArray)

    rho = numpy.array([998.2, 998.2])
    nu = numpy.array([1.004e-6, 1.004e-6])
    g = numpy.asarray([0.0, 0.0, 0.0])
    deltaT = 1.0  #dummy number
    epsFact = 1.0  #dummy number
    domain.PUMIMesh.transferPropertiesToPUMI(rho, nu, g, deltaT, deltaT,
                                             deltaT, epsFact)

    #Poiseuille Flow
    Ly = 0.2
    Lz = 0.05
    Re = 100
    Umax = Re * nu[0] / Lz

    def vOfX(x):
        return 4 * Umax / (Lz**2) * (x[2]) * (Lz - x[2])

    def dvOfXdz(x):
        return 4 * Umax / (Lz**2) * (Lz - 2 * x[2])

    #hard code solution
    vector = numpy.zeros((mesh.nNodes_global, 3), 'd')
    dummy = numpy.zeros(mesh.nNodes_global)

    vector[:, 0] = dummy
    vector[:, 1] = 4 * Umax / (Lz**2) * (mesh.nodeArray[:, 2]) * (
        Lz - mesh.nodeArray[:, 2])  #v-velocity
    vector[:, 2] = dummy
    domain.PUMIMesh.transferFieldToPUMI(b"velocity", vector)

    scalar = numpy.zeros((mesh.nNodes_global, 1), 'd')
    domain.PUMIMesh.transferFieldToPUMI(b"p", scalar)

    scalar[:, 0] = mesh.nodeArray[:, 2]
    domain.PUMIMesh.transferFieldToPUMI(b"phi", scalar)
    del scalar

    scalar = numpy.zeros((mesh.nNodes_global, 1), 'd') + 1.0
    domain.PUMIMesh.transferFieldToPUMI(b"vof", scalar)

    errorTotal = domain.PUMIMesh.get_local_error()

    # load the femspace with linear basis and get the quadrature points on a reference element
    elementQuadrature = Quadrature.SimplexGaussQuadrature(domain.nd, 3)

    ok(mesh.nNodes_element == 4)  #confirm all of the elements have 4 nodes

    #hard code computation for H1 seminorm; ideally will be reformatted using the classes within proteus
    derivativeArrayRef = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, -1, -1]]
    error = 0
    for eID in range(mesh.nElements_global):
        nodes = mesh.elementNodesArray[eID]
        coords = []
        for i in range(mesh.nNodes_element):
            coords.append(mesh.nodeArray[nodes[i]])
        J = numpy.matrix([[
            coords[0][0] - coords[3][0], coords[1][0] - coords[3][0],
            coords[2][0] - coords[3][0]
        ],
                          [
                              coords[0][1] - coords[3][1],
                              coords[1][1] - coords[3][1],
                              coords[2][1] - coords[3][1]
                          ],
                          [
                              coords[0][2] - coords[3][2],
                              coords[1][2] - coords[3][2],
                              coords[2][2] - coords[3][2]
                          ]])
        invJ = J.I
        detJ = numpy.linalg.det(J)
        gradPhi_h = 0
        for k in range(len(elementQuadrature.points)):
            tempQpt = 0
            zCoord = elementQuadrature.points[k][0]*coords[0][2] \
                +elementQuadrature.points[k][1]*coords[1][2] \
                +elementQuadrature.points[k][2]*coords[2][2] \
                +(1-elementQuadrature.points[k][0]-elementQuadrature.points[k][1]-elementQuadrature.points[k][2])*coords[3][2]
            for i in range(mesh.nNodes_element):
                temp = 0
                for j in range(domain.nd):
                    temp = temp + derivativeArrayRef[i][j] * invJ[j, 2]
                tempQpt = tempQpt + vector[nodes[i]][1] * temp
            exactgradPhi = dvOfXdz([0, 0, zCoord])
            gradPhi_h = gradPhi_h + tempQpt
            error = error + (exactgradPhi - gradPhi_h
                             )**2 * elementQuadrature.weights[k] * abs(detJ)

    error = sqrt(error)
    ok(error < errorTotal)
Пример #23
0
#!/usr/bin/env python
"""
Test module for the conservative LS with EV
"""
from __future__ import absolute_import

from builtins import range
from builtins import object
from proteus.iproteus import *
from proteus import Comm
comm = Comm.get()
Profiling.logLevel = 2
Profiling.verbose = True
import numpy as np
import tables
import pytest
from . import thelper_cons_ls
from . import thelper_cons_ls_so
from . import thelper_vof_p
from . import thelper_vof_n
from . import thelper_ncls_p
from . import thelper_ncls_n
from . import thelper_redist_p
from . import thelper_redist_n
from . import thelper_MCorr_p
from . import thelper_MCorr_n


class TestMCorr(object):
    @classmethod
    def setup_class(cls):
Пример #24
0
    TetrahedralMesh,
    MeshParallelPartitioningTypes,
    triangleVerticesToNormals,
    tetrahedronVerticesToNormals,
    intersectPoints,
    intersectEdges,
    intersectPolyhedron,
    getMeshIntersections,
    MultilevelEdgeMesh,
    MultilevelTriangularMesh,
    MultilevelTetrahedralMesh,
    MultilevelHexahedralMesh,
    InterpolatedBathymetryMesh,
)

comm = Comm.init()
Profiling.procID = comm.rank()

GNUPLOT = False


class TestMeshTools():
    @classmethod
    def setup_class(cls):
        pass

    @classmethod
    def teardown_class(cls):
        pass

    def setup_method(self, method):
Пример #25
0
log = Profiling.logEvent

log("Initializing MPI")#this won't show up unless logAllProcesses=True because we don't know our procID yet
if opts.petscOptions != None:
    petsc_argv = sys.argv[:1]+opts.petscOptions.split()
    log("PETSc options from commandline")
    log(str(petsc_argv))
else:
    petsc_argv=sys.argv[:1]
if opts.petscOptionsFile != None:
    petsc_argv=[sys.argv[0]]
    petsc_argv += open(opts.petscOptionsFile).read().split()
    log("PETSc options from commandline")
    log(str(petsc_argv))

comm = Comm.init(argv=petsc_argv)
#blanket import statements can go below here now that petsc4py should be initialized
Profiling.procID=comm.rank()
log("Initialized MPI")
if opts.viewer is not False:
    from proteusGraphical import *
from proteus import *

log("Adding "+str(opts.probDir)+" to path for loading modules")
probDir = str(opts.probDir)
if probDir not in sys.path:
    sys.path.insert(0,probDir)

pList = []
nList = []
sList = []
Пример #26
0
def setup_profiling():
    comm = Comm.get()
    Profiling.procID = comm.rank()
    Profiling.logLevel = 10
    Profiling.logFile = sys.stdout
    Profiling.logAllProcesses = True
Пример #27
0
from proteus import Context
from proteus import Comm
comm = Comm.get()
ctx = Context.get()


# simulation flags for error analysis
#
# simFlagsList is initialized in proteus.iproteus
#

simFlagsList[0]['errorQuantities']=['u']
simFlagsList[0]['errorTypes']= ['numericalSolution'] #compute error in soln and glob. mass bal
simFlagsList[0]['errorNorms']= ['L1','LI'] #compute L2 norm in space or H0 or ...
simFlagsList[0]['errorTimes']= ['Last'] #'All', 'Last'
simFlagsList[0]['echo']=True
simFlagsList[0]['echoRelativeErrors']=True
#
start
quit
Пример #28
0
    def computeWaterline(self, t):
        self.waterline_calls += 1
        if (
            self.coefficients.waterline_interval > 0
            and self.waterline_calls % self.coefficients.waterline_interval == 0
        ):
            self.waterline_npoints = numpy.zeros((1,), "i")
            self.waterline_data = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nSpace_global), "d")
            self.ncls.calculateWaterline(  # element
                self.waterline_npoints,
                self.waterline_data,
                self.u[0].femSpace.elementMaps.psi,
                self.u[0].femSpace.elementMaps.grad_psi,
                self.mesh.nodeArray,
                self.mesh.nodeVelocityArray,
                self.MOVING_DOMAIN,
                self.mesh.elementNodesArray,
                self.elementQuadratureWeights[("u", 0)],
                self.u[0].femSpace.psi,
                self.u[0].femSpace.grad_psi,
                self.u[0].femSpace.psi,
                self.u[0].femSpace.grad_psi,
                # element boundary
                self.u[0].femSpace.elementMaps.psi_trace,
                self.u[0].femSpace.elementMaps.grad_psi_trace,
                self.elementBoundaryQuadratureWeights[("u", 0)],
                self.u[0].femSpace.psi_trace,
                self.u[0].femSpace.grad_psi_trace,
                self.u[0].femSpace.psi_trace,
                self.u[0].femSpace.grad_psi_trace,
                self.u[0].femSpace.elementMaps.boundaryNormals,
                self.u[0].femSpace.elementMaps.boundaryJacobians,
                # physics
                self.mesh.nElements_global,
                self.coefficients.useMetrics,
                self.timeIntegration.alpha_bdf,  # mwf was self.timeIntegration.dt,
                self.shockCapturing.lag,
                self.shockCapturing.shockCapturingFactor,
                self.coefficients.sc_uref,
                self.coefficients.sc_beta,
                self.u[0].femSpace.dofMap.l2g,
                self.mesh.elementDiametersArray,
                self.u[0].dof,
                self.coefficients.u_old_dof,
                self.coefficients.q_v,
                self.timeIntegration.m_tmp[0],
                self.q[("u", 0)],
                self.q[("grad(u)", 0)],
                self.q[("dH_sge", 0, 0)],
                self.timeIntegration.beta_bdf[0],  # mwf was self.timeIntegration.m_last[0],
                self.q[("cfl", 0)],
                self.shockCapturing.numDiff[0],
                self.shockCapturing.numDiff_last[0],
                self.offset[0],
                self.stride[0],
                self.mesh.nExteriorElementBoundaries_global,
                self.mesh.exteriorElementBoundariesArray,
                self.mesh.elementBoundaryElementsArray,
                self.mesh.elementBoundaryLocalElementBoundariesArray,
                self.mesh.elementBoundaryMaterialTypes,
                self.coefficients.ebqe_v,
                self.numericalFlux.isDOFBoundary[0],
                self.numericalFlux.ebqe[("u", 0)],
                self.ebqe[("u", 0)],
            )
            from proteus import Comm

            comm = Comm.get()
            filename = os.path.join(
                self.coefficients.opts.dataDir, "waterline." + str(comm.rank()) + "." + str(self.waterline_prints)
            )
            numpy.save(filename, self.waterline_data[0 : self.waterline_npoints[0]])
            self.waterline_prints += 1
#!/usr/bin/env python
"""
Test module for linear boundary value problems (serial)

This module solves equations of the form

.. math::

  \nabla \cdot \left( a(x) \nabla u \right) = f(x)

"""
from proteus.iproteus import *
from proteus import Comm
comm = Comm.get()
Profiling.logLevel=7
Profiling.verbose=True
import numpy.testing as npt
from nose.tools import ok_ as ok
from nose.tools import eq_ as eq

def test_c0p1():
    import poisson_het_2d_p
    import poisson_het_2d_c0pk_n
    pList = [poisson_het_2d_p]
    nList = [poisson_het_2d_c0pk_n]    
    so = default_so
    so.name = pList[0].name = "poisson_2d_c0p1"+"pe"+`comm.size()`
    so.sList=[default_s]
    opts.logLevel=7
    opts.verbose=True
    opts.profile=True
Пример #30
0
def test_2DgmshLoadAndAdapt(verbose=0):
    """Test for loading gmsh mesh through PUMI, estimating error and adapting for 
    a 2D Couette flow case"""
    testDir = os.path.dirname(os.path.abspath(__file__))
    Model = testDir + '/Couette2D.null'
    Mesh = testDir + '/Couette2D.msh'
    domain = Domain.PUMIDomain(dim=2)  #initialize the domain
    domain.PUMIMesh = MeshAdaptPUMI.MeshAdaptPUMI(hmax=0.01,
                                                  hmin=0.008,
                                                  numIter=1,
                                                  sfConfig='ERM',
                                                  maType='isotropic',
                                                  targetError=1)
    domain.PUMIMesh.loadModelAndMesh(Model, Mesh)
    domain.faceList = [[14], [12], [11], [13]]

    mesh = MeshTools.TriangularMesh()
    mesh.cmesh = cmeshTools.CMesh()
    comm = Comm.init()

    nElements_initial = mesh.nElements_global
    mesh.convertFromPUMI(domain.PUMIMesh,
                         domain.faceList,
                         domain.regList,
                         parallel=comm.size() > 1,
                         dim=domain.nd)

    domain.PUMIMesh.transferFieldToPUMI("coordinates", mesh.nodeArray)

    rho = numpy.array([998.2, 998.2])
    nu = numpy.array([1.004e-6, 1.004e-6])
    g = numpy.asarray([0.0, 0.0])
    deltaT = 1.0  #dummy number
    domain.PUMIMesh.transferPropertiesToPUMI(rho, nu, g, deltaT)

    #Couette Flow
    Lz = 0.05
    Uinf = 2e-3
    #hard code solution
    vector = numpy.zeros((mesh.nNodes_global, 3), 'd')
    dummy = numpy.zeros(mesh.nNodes_global)
    vector[:, 0] = Uinf * mesh.nodeArray[:, 1] / Lz  #v-velocity
    vector[:, 1] = dummy
    vector[:, 2] = dummy
    domain.PUMIMesh.transferFieldToPUMI("velocity", vector)
    del vector
    del dummy

    scalar = numpy.zeros((mesh.nNodes_global, 1), 'd')
    domain.PUMIMesh.transferFieldToPUMI("p", scalar)

    scalar[:, 0] = mesh.nodeArray[:, 1]
    domain.PUMIMesh.transferFieldToPUMI("phi", scalar)
    del scalar

    scalar = numpy.zeros((mesh.nNodes_global, 1), 'd') + 1.0
    domain.PUMIMesh.transferFieldToPUMI("vof", scalar)

    errorTotal = domain.PUMIMesh.get_local_error()
    ok(errorTotal < 1e-14)

    ok(domain.PUMIMesh.willAdapt(), 1)

    domain.PUMIMesh.adaptPUMIMesh()

    mesh = MeshTools.TriangularMesh()
    mesh.convertFromPUMI(domain.PUMIMesh,
                         domain.faceList,
                         domain.regList,
                         parallel=comm.size() > 1,
                         dim=domain.nd)
    nElements_final = mesh.nElements_global
    ok(nElements_final > nElements_initial)