Exemple #1
0
def main():
    mesh = df.Mesh()
    h5f = df.HDF5File(mesh.mpi_comm(), "simple_duct.h5", "r")
    h5f.read(mesh, "mesh", False)
    V = df.VectorFunctionSpace(mesh, "CG", 1)
    P = df.FunctionSpace(mesh, "CG", 1)
    u_expr = df.Expression(("0.", "0.", expr_str(100)), degree=1)
    u = ft.interpolate_nonmatching_mesh(u_expr, V)
    u_avg = df.assemble(u.sub(2) * df.dx) / 40.

    u.vector()[:] /= u_avg

    xdmff = df.XDMFFile(mesh.mpi_comm(), "simple_duct_u0.xdmf")
    xdmff.parameters["rewrite_function_mesh"] = False
    xdmff.parameters["flush_output"] = True
    xdmff.write(u, float(0.))

    p_expr = df.Expression("0.", degree=1)
    p = ft.interpolate_nonmatching_mesh(p_expr, P)

    xdmfp = df.XDMFFile(mesh.mpi_comm(), "simple_duct_p0.xdmf")
    xdmfp.parameters["rewrite_function_mesh"] = False
    xdmfp.parameters["flush_output"] = True
    xdmfp.write(p, float(0.))

    df.plot(u.sub(2), interactive=True)
Exemple #2
0
 def import_mesh(self, filename=None):
     r"""Load mesh from generated xdmf files."""
     name = MESH
     if filename is None:
         directory = APP_DIR
     else:
         # check if path exist
         if not os.path.exists(filename):
             raise ValueError(error(E_PATH, filename))
         directory, name = os.path.split(filename)
         name = name.split(".")[0]  # remove extension if exists
     try:
         mesh = self
         with dolfin.XDMFFile(directory.child(name + XDMF)) as infile:
             infile.read(mesh)
         mvc_bnd = dolfin.MeshValueCollection("size_t", self, 1)
         with dolfin.XDMFFile(directory.child(name + BND_XDMF)) as infile:
             infile.read(mvc_bnd, "bnd")
         mvc_dom = dolfin.MeshValueCollection("size_t", self, 2)
         with dolfin.XDMFFile(directory.child(name + DOM_XDMF)) as infile:
             infile.read(mvc_dom, "dom")
         self._mvc_bnd = mvc_bnd
         self._mvc_dom = mvc_dom
     except RuntimeError as e:
         logging.error("RunTimeError\n{}\n\n".format(e))
Exemple #3
0
    def store_mesh(self,
                   mesh: dolfin.Mesh,
                   cell_domains: dolfin.MeshFunction = None,
                   facet_domains: dolfin.MeshFunction = None) -> None:
        """Save the mesh, and cellfunction and facet function if provided."""
        with dolfin.XDMFFile(mesh.mpi_comm(),
                             str(self._casedir / "mesh.xdmf")) as meshfile:
            meshfile.write(mesh)

            # if cell_domains is not None:
            #     meshfile.write(cell_domains, "cell_domains")
            # if facet_domains is not None:
            #     meshfile.write(facet_domains, "facet_domains")

        if cell_domains is not None:
            with df.XDMFFile(mesh.mpi_comm(),
                             str(self._casedir /
                                 "cell_function.xdmf")) as cf_file:
                cf_file.write(mesh)
                cf_file.write(cell_domains)

        if facet_domains is not None:
            with df.XDMFFile(mesh.mpi_comm(),
                             str(self._casedir /
                                 "facet_function.xdmf")) as ff_file:
                ff_file.write(mesh)
                ff_file.write(facet_domains)
def main():
    args = get_settings()

    interp = itp.Interpolation(args.mesh_file_in,
                               args.u_file_in,
                               p_filename_in=args.p_file_in)
    interp.update(args.step)

    u_1 = interp.u
    p_1 = interp.p

    mesh_2 = import_mesh(args.other_mesh_in)
    S_2 = df.FunctionSpace(mesh_2, "CG", 1)

    u_ = dict()
    for key, val in u_1.iteritems():
        u_[key] = ft.interpolate_nonmatching_mesh(val, S_2)
    u__ = df.as_vector([u_[key] for key in u_.keys()])
    u = AssignedVectorFunction(u__)
    u()
    p = ft.interpolate_nonmatching_mesh(p_1, S_2)

    xdmff_u = df.XDMFFile(mesh_2.mpi_comm(), args.initfile_out + "_u.xdmf")
    xdmff_u.parameters["rewrite_function_mesh"] = False
    xdmff_u.parameters["flush_output"] = True
    xdmff_u.write(u, 0.)
    xdmff_p = df.XDMFFile(mesh_2.mpi_comm(), args.initfile_out + "_p.xdmf")
    xdmff_p.parameters["rewrite_function_mesh"] = False
    xdmff_p.parameters["flush_output"] = True
    xdmff_p.write(p, 0.)
    def __init__(self,
                 parameters,
                 mesh_name,
                 facet_name,
                 bc_dict={
                     "obstacle": 2,
                     "channel_walls": 1,
                     "inlet": 3,
                     "outlet": 4
                 }):
        """
        Create the required function spaces, functions and boundary conditions
        for a channel flow problem
        """
        self.bc_dict = bc_dict
        self.mesh = df.Mesh()
        with df.XDMFFile(mesh_name) as infile:
            infile.read(self.mesh)

        mvc = df.MeshValueCollection("size_t", self.mesh,
                                     self.mesh.topology().dim() - 1)
        with df.XDMFFile(facet_name) as infile:
            infile.read(mvc, "name_to_read")
        self.mf = mf = df.cpp.mesh.MeshFunctionSizet(self.mesh, mvc)

        self.V = V = df.VectorFunctionSpace(self.mesh, 'P',
                                            parameters["degree velocity"])
        self.Q = Q = df.FunctionSpace(self.mesh, 'P',
                                      parameters["degree pressure"])
        self.rho = df.Constant(parameters["density [kg/m3]"])
        self.mu = df.Constant(parameters["viscosity [Pa*s]"])
        self.dt = df.Constant(parameters["dt [s]"])
        self.g = df.Constant((0, 0))
        self.vu, self.vp = df.TestFunction(V), df.TestFunction(Q)
        self.u_, self.p_ = df.Function(V), df.Function(Q)
        self.u_1, self.p_1 = df.Function(V), df.Function(Q)
        self.u_k, self.p_k = df.Function(V), df.Function(Q)
        self.u, self.p = df.TrialFunction(V), df.TrialFunction(Q)  # unknown!

        self.U_m = U_m = parameters["velocity [m/s]"]
        x = [0, .41 / 2]  # center of the channel
        Ucenter = 4. * U_m * x[1] * (.41 - x[1]) / (.41 * .41)
        U0_str = "4.*U_m*x[1]*(.41-x[1])/(.41*.41)"
        self.U_mean = np.mean(2 / 3 * Ucenter)

        U0 = df.Expression((U0_str, "0"), U_m=U_m, degree=2)
        bc0 = df.DirichletBC(V, df.Constant((0, 0)), mf, bc_dict["obstacle"])
        bc1 = df.DirichletBC(V, df.Constant((0, 0)), mf,
                             bc_dict["channel_walls"])
        bc2 = df.DirichletBC(V, U0, mf, bc_dict["inlet"])
        bc3 = df.DirichletBC(Q, df.Constant(0), mf, bc_dict["outlet"])
        self.bcu = [bc0, bc1, bc2]
        self.bcp = [bc3]
        self.ds_ = df.Measure("ds", domain=self.mesh, subdomain_data=mf)
        return
Exemple #6
0
    def save(self, save_number=1, it=0):
        # save samples for visualization
        if save_number > self.number_particles_all:
            save_number = self.number_particles_all

        if self.rank == 0:
            mean = self.model.generate_vector(PARAMETER)
            for p in range(self.nproc):
                for m in range(self.number_particles_all):
                    mean.axpy(1.0/(self.nproc*self.number_particles_all), self.particles_gather[p][m])

            particle_fun = dl.Function(self.model.problem.Vh[PARAMETER], name='particle')
            particle_fun.vector().axpy(1.0, mean)
            filename = 'data/mean' + '_iteration_' + str(it) + '_isProjection_' + str(self.options["is_projection"]) + '_' + str(self.options["low_rank_Hessian"]) + '.xdmf'
            if dlversion() <= (1, 6, 0):
                dl.File(self.model.prior.R.mpi_comm(), filename) << particle_fun
            else:
                xf = dl.XDMFFile(self.model.prior.R.mpi_comm(), filename)
                xf.write(particle_fun)

            variance = self.model.generate_vector(PARAMETER)
            if self.nproc*self.number_particles_all > 1:
                for p in range(self.nproc):
                    for m in range(self.number_particles_all):
                        vhelp = self.model.generate_vector(PARAMETER)
                        vhelp.axpy(1.0, self.particles_gather[p][m])
                        vhelp.axpy(-1.0, mean)
                        vsqured = vhelp.get_local()**2
                        vhelp.set_local(vsqured)
                        variance.axpy(1.0 / (self.nproc*self.number_particles_all-1), vhelp)

            particle_fun = dl.Function(self.model.problem.Vh[PARAMETER], name='particle')
            particle_fun.vector().axpy(1.0, variance)
            filename = 'data/variance' + '_iteration_' + str(it) + '_isProjection_' + str(self.options["is_projection"]) + '_'  + str(self.options["low_rank_Hessian"]) + '.xdmf'
            if dlversion() <= (1, 6, 0):
                dl.File(self.model.prior.R.mpi_comm(), filename) << particle_fun
            else:
                xf = dl.XDMFFile(self.model.prior.R.mpi_comm(), filename)
                xf.write(particle_fun)

            for n in range(save_number):
                if self.type_parameter is 'field':
                    particle_fun = dl.Function(self.model.problem.Vh[PARAMETER], name='particle')
                    particle_fun.vector().axpy(1.0, self.particles[n])
                    filename = 'data/rank_' + str(self.rank) + '_particle_' + str(n) + '_iteration_' + str(it) + str(self.options["is_projection"]) + '_' + str(self.options["low_rank_Hessian"]) + '.xdmf'
                    if dlversion() <= (1, 6, 0):
                        dl.File(self.model.prior.R.mpi_comm(), filename) << particle_fun
                    else:
                        xf = dl.XDMFFile(self.model.prior.R.mpi_comm(), filename)
                        xf.write(particle_fun)
                elif self.type_parameter is 'vector':
                    filename = 'data/rank_' + str(self.rank) + '_particle_' + str(n) + '_iteration_' + str(it)
                    np.savez(filename, particle=self.particles[n].get_local())
Exemple #7
0
def XDMFFile(arg1, arg2=None):
    if arg2 is None:
        assert isinstance(arg1, str)
        filename = arg1
        if filename.endswith(".rtc.xdmf"):
            return MeshRestrictionXDMFFile(filename)
        else:
            return dolfin.XDMFFile(filename)
    else:
        assert isinstance(arg2, str)
        mpi_comm = arg1
        filename = arg2
        assert not filename.endswith(".rtc.xdmf")
        return dolfin.XDMFFile(mpi_comm, filename)
Exemple #8
0
    def _open_xdmf_output_solution(self, add=''):
        if self.array_tag is False:
            filestring = self.result_dir + "solution_real" + self.study + add + ".xdmf"
        else:
            filestring = self.result_dir + "solution_real" + self.study + "_" + str(self.array_iter) + add + ".xdmf"
        self.logger.debug('opening xdmffile ' + filestring)
        self.datafileXDMFreal = d.XDMFFile(self.mesh.mesh.mpi_comm(), filestring)
        if self.array_tag is False:
            filestring = self.result_dir + "solution_imag" + self.study + add + ".xdmf"
        else:
            filestring = self.result_dir + "solution_imag" + self.study + "_" + str(self.array_iter) + add + ".xdmf"

        self.logger.debug('opening xdmffile ' + filestring)
        self.datafileXDMFimag = d.XDMFFile(self.mesh.mesh.mpi_comm(), filestring)
Exemple #9
0
def test_bndModel():

    Lx, Ly, Nx, Ny, NxyMicro = 2.0, 0.5, 12, 4, 50
    singleScaleFile = resultFolder + "bar_single_scale.xdmf"
    multiScaleFile = resultFolder + "bar_multiscale_standalone_%s.xdmf"
    start = timer()
    print("simulating single scale")
    os.system("python bar_single_scale.py %d %d" % (Nx, Ny))
    end = timer()
    print('finished in ', end - start)

    for bndModel in ['per', 'lin', 'MR', 'lag']:
        suffix = "{0} {1} {2} {3} > log_{3}.txt".format(
            Nx, Ny, NxyMicro, bndModel)

        start = timer()
        print("simulating using " + bndModel)
        os.system("python bar_multiscale_standalone.py " + suffix)
        end = timer()
        print('finished in ', end - start)

    mesh = df.RectangleMesh(df.Point(0.0, 0.0), df.Point(Lx, Ly), Nx, Ny,
                            "right/left")

    Uh = df.VectorFunctionSpace(mesh, "Lagrange", 1)

    uh0 = df.Function(Uh)

    with df.XDMFFile(resultFolder + "bar_single_scale.xdmf") as f:
        f.read_checkpoint(uh0, 'u')

    error = {}
    ehtemp = df.Function(Uh)

    for bndModel in ['per', 'lin', 'MR', 'lag']:

        with df.XDMFFile(multiScaleFile % bndModel) as f:
            f.read_checkpoint(ehtemp, 'u')

        ehtemp.vector().set_local(ehtemp.vector().get_local()[:] -
                                  uh0.vector().get_local()[:])

        error[bndModel] = df.norm(ehtemp)
        print(error[bndModel])

    assert np.abs(error['lin'] - error['lag']) < 1e-12
    assert np.abs(error['per'] - 0.006319071443377064) < 1e-12
    assert np.abs(error['lin'] - 0.007901978018038507) < 1e-12
    assert np.abs(error['MR'] - 0.0011744201374588351) < 1e-12
Exemple #10
0
def function_from_xdmf(function_space, function_name="", xdmf_path=""):
    """Read a finite element function from a xdmf file with checkpoint format.
        Multiple functions can also be read at once.

    Parameters
    ----------
    function_space : dolfin.FunctionSpace
        Function space appropriate for the previously saved function.
        The mesh must be identical to the one used for the saved function.
    function_name : str or list of str
        The name(s) of the saved function.
    xdmf_path : pathlib.Path or str
        Path of the xdmf file. It can be a Path object or a string.
        Extension must be '.xmdf'

    If multiple functions are requested: #TODO : test
    the first argument must be a list of tuples (FunctionSpace, function name)
    the second argument must be empty.

    Returns
    -------
    dolfin.Function, list of dolfin.Function
        New function(s) that is(are) identical to the previously saved function(s).

    Example
    --------
    >>> import dolfin as fe
    >>> mesh = xdmf_mesh("mesh.xdmf")
    >>> V = fe.VectorFunctionSpace(mesh, "CG", 2)
    >>> W = fe.VectorFunctionSpace(mesh, "DG", 1)
    >>> function_from_xdmf([(V,"u"),(W,"eps")], xdmf_path="checkpoint.xdmf")
    """

    if isinstance(function_space, list):
        all_f = list()
        with fe.XDMFFile(str(xdmf_path)) as f_in:
            for fspace, fname in function_space:
                f = fe.Function(fspace)
                f_in.read_checkpoint(f, fname)
                f.rename(fname, "")
                all_f.append(f)
        return all_f
    else:
        f = fe.Function(function_space)
        f_in = fe.XDMFFile(str(xdmf_path))
        f_in.read_checkpoint(f, function_name)
        f_in.close()
        f.rename(function_name, "")
        return f
Exemple #11
0
def mesh3d(width, depth, height, nx, ny, nz):
    mesh = dolfin.BoxMesh(Point(0., 0., 0.), Point(width, depth, height), nx,
                          ny, nz)
    boundary = (dolfin.MeshFunction("size_t", mesh,
                                    mesh.topology().dim() - 1, 0), {})
    for f in dolfin.facets(mesh):
        if dolfin.near(f.midpoint()[2], 0.):
            boundary[0][f] = 1  # bottom
            boundary[1]['bottom'] = 1
        elif dolfin.near(f.midpoint()[2], height):
            boundary[0][f] = 2  # top
            boundary[1]['top'] = 2
        elif dolfin.near(f.midpoint()[0], 0.):
            boundary[0][f] = 3  # left
            boundary[1]['left'] = 3
        elif dolfin.near(f.midpoint()[0], width):
            boundary[0][f] = 4  # right
            boundary[1]['right'] = 4
        elif dolfin.near(f.midpoint()[1], 0):
            boundary[0][f] = 5  # front
            boundary[1]['front'] = 5
        elif dolfin.near(f.midpoint()[1], depth):
            boundary[0][f] = 6  # back
            boundary[1]['back'] = 6
    # Definition of measures and normal vector:
    n = dolfin.FacetNormal(mesh)
    dx = dolfin.Measure("dx", mesh)
    ds = dolfin.Measure("ds", subdomain_data=boundary[0])
    mesh_xdmf = dolfin.XDMFFile(mpi_comm_world(), "data/mesh_3D.xdmf")
    mesh_xdmf.write(boundaries[0])
    return (mesh, boundary, n, dx, ds)
Exemple #12
0
    def load_mesh_function(self, name: str, directory: Path = None) -> dolfin.MeshFunction:
        """Lead and return a mesh function.

        There are two options, 'cell_function' or 'facet_function'.

        Arguments:
            name: Either 'cell_function' or 'facet_function'.
        """
        # TODO: I could use Enum rather than hard-coding names
        msg = "Meshfunctions are stored as 'cell_function' or 'facet_function'."
        # if not name in ("cell_function", "facet_function"):
        #     raise ValueError(msg)

        self.load_mesh()        # Method tests if mesh is already loaded

        dimension = self.mesh.geometry().dim()      # if cell function
        if name == "facet_function" or name[-3:] == "_ff":
            dimension -= 1      # dimension is one less

        # mvc = df.MeshValueCollection("size_t", self.mesh, dimension)
        cell_function = df.MeshFunction("size_t", self.mesh, dimension)

        _directory = self._casedir
        if directory is not None:
            _directory = Path(directory)
        infile_name = _directory / f"{name}.xdmf"
        if not infile_name.exists():
            raise RuntimeError(f"Mesh function {infile_name} does not exist")
        with df.XDMFFile(str(infile_name)) as infile:
            infile.read(cell_function)
            # infile.read(mvc)
        # cell_function = df.MeshFunction("size_t", self.mesh, mvc)
        return cell_function
Exemple #13
0
def loadDolfin(filename, exterior=False):
    """Reads a `Fenics/Dolfin` file format (.xml or .xdmf).
    Return an ``Actor(vtkActor)`` object."""
    import sys
    if sys.version_info[0] < 3:
        return _loadDolfin_old(filename)

    import dolfin

    if filename.lower().endswith('.xdmf'):
        f = dolfin.XDMFFile(filename)
        m = dolfin.Mesh()
        f.read(m)
    else:
        m = dolfin.Mesh(filename)

    bm = dolfin.BoundaryMesh(m, "exterior")

    if exterior:
        poly = utils.buildPolyData(bm.coordinates(), bm.cells(), fast=True)
    else:
        polyb = utils.buildPolyData(bm.coordinates(), bm.cells(), fast=True)
        polym = utils.buildPolyData(m.coordinates(), m.cells(), fast=True)
        app = vtk.vtkAppendPolyData()
        app.AddInputData(polym)
        app.AddInputData(polyb)
        app.Update()
        poly = app.GetOutput()
    return Actor(poly).lw(0.1)
Exemple #14
0
def gmsh2dolfin(msh_file, unlink: bool = True):

    name = Path(msh_file).stem

    triangle_mesh_name = Path(f"triangle_mesh_{name}.xdmf")
    tetra_mesh_name = Path(f"mesh_{name}.xdmf")

    markers = {}
    if not (triangle_mesh_name.is_file() and tetra_mesh_name.is_file()):
        markers = convert_msh_to_xdmf(msh_file, triangle_mesh_name,
                                      tetra_mesh_name)

    mesh = df.Mesh()

    with df.XDMFFile(tetra_mesh_name.as_posix()) as infile:
        infile.read(mesh)

    cfun = df.MeshFunction("size_t", mesh, 3)
    read_meshfunction(tetra_mesh_name, cfun)

    ffun_val = df.MeshValueCollection("size_t", mesh, 2)
    read_meshfunction(triangle_mesh_name, ffun_val)
    ffun = df.MeshFunction("size_t", mesh, ffun_val)

    if unlink:
        triangle_mesh_name.unlink()
        triangle_mesh_name.with_suffix(".h5").unlink()
        tetra_mesh_name.unlink()
        tetra_mesh_name.with_suffix(".h5").unlink()

    return mesh, ffun, markers
 def __init__(self, data, logger):
     # use __init__ from Fenics class
     super().__init__(data, logger)
     self.logger.info("Starting Heat simulation.")
     ###
     # FEM part
     ###
     self._set_function_space()
     self._prepare_boundaries()
     self.logger.debug("Set DirichletBC")
     self.boundaries.set_DirichletBC(self.V, self.logger)
     self.datafileXDMFT = d.XDMFFile(self.mesh.mesh.mpi_comm(), self.result_dir + "Tsolution" + self.    study + '.xdmf')
     ###
     # Physics part
     ###
     stationary = 'timesteps' not in self.data
     if stationary:
         self._set_material_constants(stat=True)
         self._set_stationary_problem()
         self.logger.debug("Stationary problem set.")
         self.N = 1
         self.t = 0
     else:
         self._set_timestepping()
         self._set_material_constants()
         self._set_problem()
         self.logger.debug("Time-dependent problem set.")
     self._setup_solver()
     self._solve_problem()
     self.datafileXDMFT.close()
Exemple #16
0
 def _open_output_efield(self, add=''):
     """
     for the output we can add information, e.g. about the respective subdomain
     """
     if self.array_tag is False:
         filestring = self.result_dir + "efield_real" + self.study + add + ".xdmf"
     else:
         filestring = self.result_dir + "efield_real" + self.study + "_" + str(self.array_iter) + add + ".xdmf"
     self.logger.debug('opening xdmffile ' + filestring)
     self.dataXDMFEreal = d.XDMFFile(self.mesh.mesh.mpi_comm(), filestring)
     if self.array_tag is False:
         filestring = self.result_dir + "efield_imag" + self.study + add + ".xdmf"
     else:
         filestring = self.result_dir + "efield_imag" + self.study + "_" + str(self.array_iter) + add + ".xdmf"
     self.logger.debug('opening xdmffile ' + filestring)
     self.dataXDMFEimag = d.XDMFFile(self.mesh.mesh.mpi_comm(), filestring)
Exemple #17
0
    def __init__(self, model, filename="out.xdmf"):
        self.model = model
        self.plot = df.XDMFFile(filename)
        self.plot.parameters["functions_share_mesh"] = True

        self.model.d.rename("u", "u")
        self.model.k.rename("kappa", "kappa")
Exemple #18
0
 def read_mesh(self, numElementsFilm, reGen=True):
     if reGen:
         self.gen_mesh(numElementsFilm=2.0)
     fileName = "mesh/geometry_quad.xdmf"
     self.mesh = dl.Mesh()
     f = dl.XDMFFile(dl.mpi_comm_world(), fileName)
     f.read(self.mesh)
     f.close()
Exemple #19
0
def test_parallel():

    Lx, Ly, Ny, Nx, NxyMicro = 0.5, 2.0, 12, 5, 50
    bndModel = 'per'
    suffix = "%d %d %d %s > log_%s.txt" % (Nx, Ny, NxyMicro, bndModel,
                                           bndModel)

    start = timer()
    print("simulating single core")
    os.system("python bar_multiscale_standalone.py " + suffix)
    end = timer()
    print('finished in ', end - start)

    for nProc in [1, 2, 3, 4]:
        start = timer()
        print("simulating using nProc", nProc)
        os.system("mpirun -n %d python bar_multiscale_parallel.py " % nProc +
                  suffix)
        end = timer()
        print('finished in ', end - start)

    mesh = df.RectangleMesh(df.Point(0.0, 0.0), df.Point(Lx, Ly), Nx, Ny,
                            "right/left")

    Uh = df.VectorFunctionSpace(mesh, "Lagrange", 1)

    uh0 = df.Function(Uh)

    with df.XDMFFile("bar_multiscale_standalone_%s.xdmf" % bndModel) as f:
        f.read_checkpoint(uh0, 'u')

    error = {}
    ehtemp = df.Function(Uh)

    for nProc in [1, 2, 3, 4]:

        with df.XDMFFile("bar_multiscale_parallel_%s_np%d.xdmf" %
                         (bndModel, nProc)) as f:
            f.read_checkpoint(ehtemp, 'u')

        ehtemp.vector().set_local(ehtemp.vector().get_local()[:] -
                                  uh0.vector().get_local()[:])

        error[nProc] = df.norm(ehtemp)

    assert np.max(np.array(list(error.values()))) < 1e-13
Exemple #20
0
def get_mesh(
    directory: Path,
    name: str,
    facet_function_name: str = None,
    cell_function_name: str = None
) -> tp.Tuple[df.Mesh, df.MeshFunction, df.MeshFunction]:
    mesh = df.Mesh()
    mesh_name = str(directory / f"{name}.xdmf")
    with df.XDMFFile(mesh_name) as infile:
        infile.read(mesh)

    if cell_function_name is None:
        cell_function_name = f"{name}_cf.xdmf"
    _cell_function_name = directory / cell_function_name
    if not _cell_function_name.suffix == ".xdmf":
        _cell_function_name = Path(f"{_cell_function_name}.xdmf")
    if not _cell_function_name.exists():
        cell_function = None
        logging.info(
            f"Could not read cell function, file '{_cell_function_name} does not exist"
        )
    else:
        mvc = df.MeshValueCollection("size_t", mesh, mesh.geometry().dim())
        with df.XDMFFile(str(_cell_function_name)) as infile:
            infile.read(mvc)
            # infile.read(mvc, "tetra")
        cell_function = df.MeshFunction("size_t", mesh, mvc)

    if facet_function_name is None:
        facet_function_name = f"{name}_ff.xdmf"
    _facet_function_name = directory / facet_function_name
    if not _facet_function_name.suffix == ".xdmf":
        _facet_function_name = Path(f"{_facet_function_name}.xdmf")
    if not _facet_function_name.exists():
        facet_function = None
        logging.info(
            f"Could not read facet function, file '{_facet_function_name} does not exist"
        )
    else:
        mvc = df.MeshValueCollection("size_t", mesh, mesh.geometry().dim() - 1)
        with df.XDMFFile(str(_facet_function_name)) as infile:
            infile.read(mvc)
        facet_function = df.MeshFunction("size_t", mesh, mvc)
    return mesh, cell_function, facet_function
Exemple #21
0
    def load_checkpoint(
        self,
        name: str,
        timestep_iterable: Iterable[int] = None,
    ) -> Iterator[Tuple[int, float, dolfin.Function]]:
        """yield tuple(float, function)."""
        metadata = self.load_metadata(name)

        _timestep_iterable = timestep_iterable
        timestep_iterable, time_iterable = self.load_time()

        # from IPython import embed; embed()
        # assert False
        if _timestep_iterable is None:
            _timestep_iterable = timestep_iterable

        if self.mesh is None:
            self.mesh = self.load_mesh()

        element_tuple = (
            dolfin.interval,
            dolfin.triangle,
            dolfin.tetrahedron
        )

        element = dolfin.FiniteElement(
            metadata["element_family"],
            element_tuple[self.mesh.geometry().dim() - 1],        # zero indexed
            metadata["element_degree"]
        )

        V_space = dolfin.FunctionSpace(self.mesh, element)
        v_func = dolfin.Function(V_space)

        _filename = self.casedir / Path("{name}/{name}_chk.xdmf".format(name=name))
        if _filename.exists():
            filename_list = [_filename]
        else:
            assert False, f"Could not open {_filename}"

        previous_timestep = -100
        for filename in filename_list:
            with dolfin.XDMFFile(dolfin.MPI.comm_world, str(filename)) as fieldfile:
                for savad_timestep_index, timestep in enumerate(_timestep_iterable):
                    if timestep == previous_timestep:
                        continue
                    previous_timestep = timestep
                    if timestep < int(metadata["start_timestep"]):
                        continue
                    if timestep % int(metadata["stride_timestep"]) != 0:
                        continue
                    try:
                        fieldfile.read_checkpoint(v_func, name, counter=timestep)
                    except RuntimeError as e:
                        LOGGER.info(f"Could not read timestep: {e}")
                    yield time_iterable[savad_timestep_index], v_func
def get_mesh(directory: str, name: str) -> Tuple[df.Mesh, df.MeshFunction, df.MeshFunction]:
    mesh = df.Mesh()
    with df.XDMFFile(f"{directory}/{name}.xdmf") as infile:
        infile.read(mesh)

    mvc = df.MeshValueCollection("size_t", mesh, 2)
    with df.XDMFFile(f"{directory}/{name}_cf.xdmf") as infile:
        infile.read(mvc, "cell_data")
    cell_function = df.MeshFunction("size_t", mesh, mvc)

    try:
        mvc = df.MeshValueCollection("size_t", mesh, 1)
        with df.XDMFFile(f"{directory}/{name}_ff.xdmf") as infile:
            infile.read(mvc, "facet_data")
        interface_function = df.MeshFunction("size_t", mesh, mvc)
    except:
        interface_function = df.MeshFunction("size_t", mesh, mesh.geometric_dimension() - 1)
        interface_function.set_all(0)
    return mesh, cell_function, interface_function
Exemple #23
0
 def exportState(self, x, filename, varname):
     out_file = dl.XDMFFile(self.Vh[STATE].mesh().mpi_comm(), filename)
     out_file.parameters["functions_share_mesh"] = True
     out_file.parameters["rewrite_function_mesh"] = False
     ufunc = dl.Function(self.Vh[STATE], name=varname)
     t = self.simulation_times[0]
     out_file.write(vector2Function(x[PARAMETER], self.Vh[STATE], name=varname),t)
     for t in self.simulation_times[1:]:
         x[STATE].retrieve(ufunc.vector(), t)
         out_file.write(ufunc, t)
Exemple #24
0
def get_indicator_function(function_path: Path,
                           mesh: df.Mesh,
                           name: str = "indicator") -> df.Function:
    # Has to be the same as in the bidomain solver
    function_space = df.FunctionSpace(mesh, "CG", 1)
    function = df.Function(function_space)
    with df.XDMFFile(str(function_path)) as infile:
        infile.read_checkpoint(function, name, 0)

    return function
Exemple #25
0
 def load_mesh(self, name: str = None) -> dolfin.mesh:
     """Load and return the mesh stored as xdmf."""
     if self.mesh is None:
         self.mesh = df.Mesh()
         if name is None:
             mesh_name = self._casedir / Path("mesh.xdmf")
         else:
             mesh_name = self._casedir / Path(f"{name}.xdmf")
         with df.XDMFFile(str(mesh_name)) as infile:
             infile.read(self.mesh)
     return self.mesh
Exemple #26
0
def _save_all_localization_fields(xdmf_path: Path, localization_dicts: list):
    """Sauvegarde de tous les champs de localisation dans un .xdmf
    localization_dicts : list de dictionnaires."""
    with fe.XDMFFile(str(xdmf_path)) as fo:
        fo.parameters["functions_share_mesh"] = True
        for d in localization_dicts:
            for k, fields in d.items():
                for f in fields:
                    logger.debug(f"Saving field {f.name()}")
                    fo.write(f, 0.0)
    return None
Exemple #27
0
    def _plot_mesh(self):
        if self.mesh.dimension < 3:
            self.logger.info("Plotting mesh")
            d.plot(self.mesh.mesh, title='mesh')
            plt.show()
            p = d.plot(self.mesh.cells, title="subdomains ")
            loc = plticker.MultipleLocator(base=1.0)
            # some hacks from the internet
            plt.colorbar(p, format='%d', ticks=loc, fraction=0.03, pad=0.04)
            plt.show()
            self.logger.debug(
                "Mesh was plotted, subdomains and facets also match the mesh")
        else:
            self.logger.info(
                "Plotting mesh does not make sense in 3D. Output is written to paraview readable files."
            )
            self.mesh_dir = "mesh/"
            if not os.path.exists(self.mesh_dir):
                try:
                    os.makedirs(self.mesh_dir)
                except OSError as exc:  # Guard against race condition
                    if exc.errno != errno.EEXIST:
                        raise

            tmp = d.XDMFFile(
                self.mesh.mesh.mpi_comm(),
                self.mesh_dir + self.mesh.meshname + str('_plot.xdmf'))
            tmp.write(self.mesh.mesh)
            tmp.close()
            tmp = d.XDMFFile(
                self.mesh.mesh.mpi_comm(), self.mesh_dir + self.mesh.meshname +
                str('_subdomains') + str('.xdmf'))
            tmp.write(self.mesh.cells)
            tmp.close()
            tmp = d.XDMFFile(
                self.mesh.mesh.mpi_comm(), self.mesh_dir + self.mesh.meshname +
                str('_facets') + str('.xdmf'))
            tmp.write(self.mesh.facets)
            tmp.close()

            self.logger.debug("Mesh was written out.")
Exemple #28
0
 def _plot_submesh(self, subdomain):
     try:
         if 'mesh' in self.plot:
             if self.plot['mesh'] is True:
                 tmp = d.XDMFFile(
                     self.mesh.mesh.mpi_comm(),
                     self.mesh_dir + self.mesh.meshname + '_plot_' +
                     str(subdomain) + '.xdmf')
                 tmp.write(self.sub_mesh)
                 tmp.close()
     except TypeError:
         pass
Exemple #29
0
def save_mesh(directory: Path,
              name: str,
              *,
              mesh: tp.Optional[df.Mesh] = None,
              cell_function: tp.Optional[df.MeshFunction] = None,
              facet_function: tp.Optional[df.MeshFunction] = None) -> None:
    if mesh is not None:
        mesh_path = directory / f"{name}.xdmf"
        logger.info(f"Saving mesh as {mesh_path}")
        with df.XDMFFile(str(mesh_path)) as mesh_file:
            mesh_file.write(mesh)
    if cell_function is not None:
        cell_path = directory / f"{name}_cf.xdmf"
        logger.info(f"Saving cell_function as {cell_path}")
        with df.XDMFFile(str(cell_path)) as cell_file:
            cell_file.write(cell_function)
    if facet_function is not None:
        facet_path = directory / f"{name}_ff.xdmf"
        logger.info(f"Saving facet_function as {facet_path}")
        with df.XDMFFile(str(facet_path)) as facet_file:
            facet_file.write(facet_function)
Exemple #30
0
def define_spatially_varying_penalty(simulation,
                                     P,
                                     k_min,
                                     k_max,
                                     boost_factor=3,
                                     exponent=1):
    """
    Define the penalty parameter used in the Poisson equations

    Spatially varying version, returns a DGT0 function

    Arguments:
        mesh: the mesh used in the simulation
        P: the polynomial degree of the unknown
        k_min: the minimum diffusion coefficient
        k_max: the maximum diffusion coefficient
        boost_factor: the penalty is multiplied by this factor
        exponent: set this to greater than 1 for superpenalisation
    """
    assert k_max >= k_min
    mesh = simulation.data['mesh']
    ndim = mesh.geometry().dim()

    # Compute the constant part of the penalty
    pconst = boost_factor * k_max**2 / k_min * (P + 1) * (P + ndim) / ndim

    # Compute the spatially varying penalty
    V = dolfin.FunctionSpace(mesh, 'DG', 0)
    dm = V.dofmap()
    penalty_func = dolfin.Function(V)
    arr = penalty_func.vector().get_local()
    for cell in dolfin.cells(mesh):
        vol = cell.volume()
        area = sum(cell.facet_area(i) for i in range(ndim + 1))
        geom_fac = area / vol
        dof, = dm.cell_dofs(cell.index())
        arr[dof] = pconst * geom_fac**exponent

    penalty_func.vector().set_local(arr)
    penalty_func.vector().apply('insert')

    # Optionally plot the penalty function to file
    if simulation.input.get_value('output/plot_elliptic_penalty', False,
                                  'bool'):
        prefix = simulation.input.get_value('output/prefix', '', 'string')
        pfile = prefix + '_elliptic_dg_penalty.xdmf'
        simulation.log.info(
            '    Plotting elliptic DG penalty to XDMF file %r' % pfile)
        penalty_func.rename('penalty', 'penalty')
        with dolfin.XDMFFile(mesh.mpi_comm(), pfile) as xdmf:
            xdmf.write(penalty_func)

    return penalty_func