示例#1
0
def convert_meshfunctions_to_submesh(mesh, submesh, meshfunctions_on_mesh):
    assert meshfunctions_on_mesh is None or (isinstance(
        meshfunctions_on_mesh, list) and len(meshfunctions_on_mesh) > 0)
    if meshfunctions_on_mesh is None:
        return None
    meshfunctions_on_submesh = list()
    # Create submesh subdomains
    for mesh_subdomain in meshfunctions_on_mesh:
        submesh_subdomain = MeshFunction("size_t", submesh,
                                         mesh_subdomain.dim())
        submesh_subdomain.set_all(0)
        assert submesh_subdomain.dim() in (submesh.topology().dim(),
                                           submesh.topology().dim() - 1)
        if submesh_subdomain.dim() == submesh.topology().dim():
            for submesh_cell in cells(submesh):
                submesh_subdomain.array()[
                    submesh_cell.index()] = mesh_subdomain.array()[
                        submesh.submesh_to_mesh_cell_local_indices[
                            submesh_cell.index()]]
        elif submesh_subdomain.dim() == submesh.topology().dim() - 1:
            for submesh_facet in facets(submesh):
                submesh_subdomain.array()[
                    submesh_facet.index()] = mesh_subdomain.array()[
                        submesh.submesh_to_mesh_facet_local_indices[
                            submesh_facet.index()]]
        else:  # impossible to arrive here anyway, thanks to the assert
            raise TypeError(
                "Invalid arguments in convert_meshfunctions_to_submesh.")
        meshfunctions_on_submesh.append(submesh_subdomain)
    return meshfunctions_on_submesh
示例#2
0
def load_data(mesh, mesh_f, dim, data):
    '''
    Represent mesh_f over dim entities of mesh as collection of vertices.
    Can have mesh as mesh function or (h5_file, data_set)
    '''
    try:
        h5_file, data_set = mesh_f
        mf = MeshFunction('size_t', mesh, dim, 0)
        h5_file.read(mf, data_set)
    except ValueError:
        mf = mesh_f
        data_set = '%d dim entites' % mf.dim()
            
    # Mapf for encoding entities as vertices
    mesh.init(dim, 0)
    e2v = mesh.topology()(dim, 0)

    tags = set(mf.array())
    # Don't encode zero - we initialize to it
    if 0 in tags: tags.remove(0)
    info('%s evolves tags %r' % (data_set, tags))

    for tag in tags:
        data[(dim, tag)] = np.array([e2v(e.index()) for e in SubsetIterator(mf, tag)],
                                    dtype='uintp')
    return data
示例#3
0
def convert(msh_file, h5_file, save_mvc=False):
    '''Temporary version of convertin from msh to h5'''
    root, _ = os.path.splitext(msh_file)
    assert os.path.splitext(msh_file)[1] == '.msh'
    assert os.path.splitext(h5_file)[1] == '.h5'

    # Get the xml mesh
    xml_file = '.'.join([root, 'xml'])
    subprocess.call(['dolfin-convert %s %s' % (msh_file, xml_file)], shell=True)
    # Success?
    assert os.path.exists(xml_file)

    mesh = Mesh(xml_file)
    out = HDF5File(mesh.mpi_comm(), h5_file, 'w')
    out.write(mesh, 'mesh')

    print('Mesh has %d cells' % mesh.num_cells())
    print('Mesh size %g %g' % (mesh.hmin(), mesh.hmax()))
    
    # Save ALL data as facet_functions
    names = ('surfaces', 'volumes')
    if not save_mvc:
        for name, region in zip(names, ('facet_region.xml', 'physical_region.xml')):
            r_xml_file = '_'.join([root, region])

            f = MeshFunction('size_t', mesh, r_xml_file)
            print('%d %s with 1' % (sum(1 for _ in SubsetIterator(f, 1)), name))
            out.write(f, name)

        return True

    for name, region in zip(names, ('facet_region.xml', 'physical_region.xml')):
        r_xml_file = '_'.join([root, region])

        f = MeshFunction('size_t', mesh, r_xml_file)
        # With mesh value collection we only store nonzero tags
        mvc = MeshValueCollection('size_t', mesh, f.dim())
        # Fill
        fill_mvc_from_mf(f, mvc)
        # And save
        out.write(mvc, name)
                    
    return True
示例#4
0
    def __init__(self,
                 mesh: df.Mesh,
                 time: df.Constant,
                 M_i: tp.Union[df.Expression, tp.Dict[int, df.Expression]],
                 M_e: tp.Union[df.Expression, tp.Dict[int, df.Expression]],
                 I_s: tp.Union[df.Expression, tp.Dict[int,
                                                      df.Expression]] = None,
                 I_a: tp.Union[df.Expression, tp.Dict[int,
                                                      df.Expression]] = None,
                 ect_current: tp.Dict[int, df.Expression] = None,
                 v_: df.Function = None,
                 cell_domains: df.MeshFunction = None,
                 facet_domains: df.MeshFunction = None,
                 dirichlet_bc: tp.List[tp.Tuple[df.Expression, int]] = None,
                 dirichlet_bc_v: tp.List[tp.Tuple[df.Expression, int]] = None,
                 periodic_domain: df.SubDomain = None,
                 parameters: df.Parameters = None) -> None:
        """Initialise solverand check all parametersare correct.

        NB! The periodic domain has to be set in the cellsolver too.
        """
        self._timestep = None

        comm = df.MPI.comm_world
        rank = df.MPI.rank(comm)

        msg = "Expecting mesh to be a Mesh instance, not {}".format(mesh)
        assert isinstance(mesh, df.Mesh), msg

        msg = "Expecting time to be a Constant instance (or None)."
        assert isinstance(time, df.Constant) or time is None, msg

        msg = "Expecting parameters to be a Parameters instance (or None)"
        assert isinstance(parameters, df.Parameters) or parameters is None, msg

        self._nullspace_basis = None

        # Store input
        self._mesh = mesh
        self._time = time

        # Initialize and update parameters if given
        self._parameters = self.default_parameters()
        if parameters is not None:
            self._parameters.update(parameters)

        if self._parameters["Chi"] == -1 or self._parameters["Cm"] == -1:
            raise ValueError(
                "Need Chi and Cm to be specified explicitly throug the parameters."
            )

        # Set-up function spaces
        k = self._parameters["polynomial_degree"]
        Ve = df.FiniteElement("CG", self._mesh.ufl_cell(), k)
        V = df.FunctionSpace(self._mesh,
                             "CG",
                             k,
                             constrained_domain=periodic_domain)
        Ue = df.FiniteElement("CG", self._mesh.ufl_cell(), k)

        if self._parameters["linear_solver_type"] == "direct":
            Re = df.FiniteElement("R", self._mesh.ufl_cell(), 0)
            _element = df.MixedElement((Ve, Ue, Re))
            self.VUR = df.FunctionSpace(mesh,
                                        _element,
                                        constrained_domain=periodic_domain)
        else:
            _element = df.MixedElement((Ve, Ue))
            self.VUR = df.FunctionSpace(mesh,
                                        _element,
                                        constrained_domain=periodic_domain)

        self.V = V

        if cell_domains is None:
            cell_domains = df.MeshFunction("size_t", mesh,
                                           self._mesh.geometry().dim())
            cell_domains.set_all(0)

        # Chech that it is indeed a cell function.
        cell_dim = cell_domains.dim()
        mesh_dim = self._mesh.geometry().dim()
        msg = "Got {cell_dim}, expected {mesh_dim}.".format(cell_dim=cell_dim,
                                                            mesh_dim=mesh_dim)
        assert cell_dim == mesh_dim, msg
        self._cell_domains = cell_domains

        if facet_domains is None:
            facet_domains = df.MeshFunction("size_t", mesh,
                                            self._mesh.geometry().dim() - 1)
            facet_domains.set_all(0)

        # Check that it is indeed a facet function.
        facet_dim = facet_domains.dim()
        msg = "Got {facet_dim}, expected {mesh_dim}.".format(
            facet_dim=facet_dim, mesh_dim=mesh_dim - 1)
        assert facet_dim == mesh_dim - 1, msg
        self._facet_domains = facet_domains

        # Gather all cell keys on all processes. Greatly simplifies things
        cell_keys = set(self._cell_domains.array())
        all_cell_keys = comm.allgather(cell_keys)
        all_cell_keys = reduce(or_, all_cell_keys)

        # If Mi is not dict, make dict
        if not isinstance(M_i, dict):
            M_i = {int(i): M_i for i in all_cell_keys}
        else:  # Check that the keys match the cell function
            M_i_keys = set(M_i.keys())
            msg = "Got {M_i_keys}, expected {cell_keys}.".format(
                M_i_keys=M_i_keys, cell_keys=all_cell_keys)
            assert M_i_keys == all_cell_keys, msg

        # If Me is not dict, make dict
        if not isinstance(M_e, dict):
            M_e = {int(i): M_e for i in all_cell_keys}
        else:  # Check that the keys match the cell function
            M_e_keys = set(M_e.keys())
            msg = "Got {M_e_keys}, expected {cell_keys}.".format(
                M_e_keys=M_e_keys, cell_keys=all_cell_keys)
            assert M_e_keys == all_cell_keys, msg
        self._M_i = M_i
        self._M_e = M_e

        # Store source terms
        if I_s is not None and not isinstance(I_s, dict):
            I_s = {key: I_s for key in all_cell_keys}
        self._I_s = I_s

        if I_a is not None and not isinstance(I_a, dict):
            I_a = {key: I_a for key in all_cell_keys}
        self._I_a = I_a

        # Set the ECT current, Note, it myst depend on `time` to be updated
        if ect_current is not None:
            ect_tags = set(ect_current.keys())
            facet_tags = set(self._facet_domains.array())
            msg = "{} not in facet domains ({}).".format(ect_tags, facet_tags)
            assert ect_tags <= facet_tags, msg
        self._ect_current = ect_current

        # Set-up solution fields:
        if v_ is None:
            self.merger = df.FunctionAssigner(V, self.VUR.sub(0))
            self.v_ = df.Function(V, name="v_")
        else:
            # df.debug("Experimental: v_ shipped from elsewhere.")
            self.merger = None
            self.v_ = v_
        self.vur = df.Function(self.VUR, name="vur")

        # Set Dirichlet bcs for the transmembrane potential
        self._bcs = []
        if dirichlet_bc_v is not None:
            for function, marker in dirichlet_bc_v:
                self._bcs.append(
                    df.DirichletBC(self.VUR.sub(0), function,
                                   self._facet_domains, marker))

        # Set Dirichlet bcs for the extra cellular potential
        if dirichlet_bc is not None:
            for function, marker in dirichlet_bc:
                self._bcs.append(
                    df.DirichletBC(self.VUR.sub(1), function,
                                   self._facet_domains, marker))
示例#5
0
    def __init__(self,
                 mesh: df.Mesh,
                 time: df.Constant,
                 M_i: tp.Union[df.Expression, tp.Dict[int, df.Expression]],
                 I_s: tp.Union[df.Expression, tp.Dict[int,
                                                      df.Expression]] = None,
                 v_: df.Function = None,
                 cell_domains: df.MeshFunction = None,
                 facet_domains: df.MeshFunction = None,
                 parameters: df.Parameters = None):
        # Store input
        self._mesh = mesh
        self._I_s = I_s
        self._time = time

        # Set-up function spaces
        V = df.FunctionSpace(self._mesh, "CG", 1)

        self.V = V

        # Set-up solution fields:
        if v_ is None:
            self.v_ = df.Function(V, name="v_")
        else:
            self.v_ = v_

        self.v = df.Function(self.V, name="v")

        if cell_domains is None:
            cell_domains = df.MeshFunction("size_t", mesh,
                                           self._mesh.geometry().dim())
            cell_domains.set_all(0)

        # Chech that it is indeed a cell function.
        cell_dim = cell_domains.dim()
        mesh_dim = self._mesh.geometry().dim()
        msg = "Got {}, expected {}.".format(cell_dim, mesh_dim)
        assert cell_dim == mesh_dim, msg
        self._cell_domains = cell_domains

        if facet_domains is None:
            facet_domains = df.MeshFunction("size_t", mesh,
                                            self._mesh.geometry().dim() - 1)
            facet_domains.set_all(0)

        # Check that it is indeed a facet function.
        facet_dim = facet_domains.dim()
        msg = "Got {}, expected {}.".format(facet_dim, mesh_dim)
        assert facet_dim == mesh_dim - 1, msg
        self._facet_domains = facet_domains

        if not isinstance(M_i, dict):
            M_i = {int(i): M_i for i in set(self._cell_domains.array())}
        else:
            M_i_keys = set(M_i.keys())
            cell_keys = set(self._cell_domains.array())
            msg = "Got {}, expected {}.".format(M_i_keys, cell_keys)
            assert M_i_keys == cell_keys, msg
        self._M_i = M_i

        # Initialize and update parameters if given
        self.parameters = self.default_parameters()
        if parameters is not None:
            self.parameters.update(parameters)