Esempio n. 1
0
    def write_data(self, file_name):

        print file_name


        ### Create a 1d mesh

        editor = fc.MeshEditor()
        mesh = fc.Mesh()
        editor.open(mesh, 1, 1)

        editor.init_vertices(len(self.center_xs))
        editor.init_cells(len(self.center_xs) - 1)

        # Add vertices
        i = 0
        for d in self.distances:
            editor.add_vertex(i, d)
            i += 1

        # Add cells
        for i in range(len(self.distances) - 1):
            editor.add_cell(i, np.array([i, i+1], dtype = np.uintp))

        editor.close()


        ### Create output hdf5 file

        out_file = fc.HDF5File(mesh.mpi_comm(), file_name, "w")


        ### Create and set data functions

        V = fc.FunctionSpace(mesh, "CG", 1)
        smb = fc.Function(V)
        surface = fc.Function(V)
        bed = fc.Function(V)
        width = fc.Function(V)
        thickness = fc.Function(V)

        smb.vector().set_local(self.flowline_data['smb'])
        smb.vector().apply("insert")
        surface.vector().set_local(self.flowline_data['surface'])
        surface.vector().apply("insert")
        bed.vector().set_local(self.flowline_data['bed'])
        bed.vector().apply("insert")
        width.vector().set_local(self.flowline_data['width'])
        width.vector().apply("insert")
        thickness.vector().set_local(self.flowline_data['surface'] - self.flowline_data['bed'])
        thickness.vector().apply("insert")


        out_file.write(mesh, "/mesh")
        out_file.write(smb.vector(), "/smb")
        out_file.write(surface.vector(), "/surface")
        out_file.write(bed.vector(), "/bed")
        out_file.write(width.vector(), "/width")
        out_file.write(thickness.vector(), "/thickness")
        out_file.close()
Esempio n. 2
0
    def create_cocontinuous_mesh(self):

        if self.use_previously_stored_mesh:

            self.mesh = fe.Mesh(self.mesh_fname)
            print('Mesh has been loaded from file')
            return

        p = self.L * np.ones(3)
        geo     = mesher.Box(fe.Point(0,0,0), fe.Point(p))
        net     = self.extrude_base_net()
        columns = self.create_cylindrical_columns()
        net    += columns

        if self.keep_only_network: 
            geo  = net
        else:
            geo -= net

        print('Finished creating the geometry')
        self.mesh = mesher.generate_mesh(geo, self.mesh_density);

        print('Writing mesh to file')
        mesh_file = fe.File(self.mesh_fname)
        mesh_file << self.mesh
        print('Finished writing mesh to file')
Esempio n. 3
0
    def deepcopy(self):
        """ Return an entire deep copy of `self`. 
        For example, this is useful for checkpointing small problems in memory,
        or for running a batch of simulations with parameter changes.
        """
        sim = type(self)(time_order=self.time_order,
                         integration_measure=self.integration_measure(),
                         setup_solver=False)

        sim._mesh = fenics.Mesh(self.mesh)

        sim._function_space = fenics.FunctionSpace(sim.mesh, sim._element)

        for i in range(len(self._solutions)):

            sim._solutions[i] = fenics.Function(sim.function_space)

            sim._solutions[i].leaf_node().vector(
            )[:] = self._solutions[i].leaf_node().vector()

            sim._times[i] = 0. + self._times[i]

        for i in range(len(self._timestep_sizes)):

            sim._timestep_sizes[i] = self._timestep_sizes[i]

        sim.setup_solver()

        sim.solver.parameters = self.solver.parameters.copy()

        return sim
Esempio n. 4
0
    def read_checkpoint(self, filepath):
        """Read solutions and times from a checkpoint file."""
        self._mesh = fenics.Mesh()

        print("Reading checkpoint from " + filepath)

        with fenics.HDF5File(self.mesh.mpi_comm(), filepath, "r") as h5:

            h5.read(self._mesh, "mesh", True)

            self._function_space = fenics.FunctionSpace(
                self.mesh, self._element)

            for i in range(self.time_order + 1):

                self._solutions[i] = fenics.Function(self.function_space)

                h5.read(self._solutions[i], "solution" + str(i))
                """ fenics.HDF5File doesn't implement read methods for every write method.
                Our only option here seems to be to use a fenics.Vector to store values,
                because a reader is implemented for GenericVector, which Vector inherits from.
                Furthermore, for the correct read method to be called, we must pass a boolean
                as a third argument related to distributed memory.
                """
                time = fenics.Vector(fenics.mpi_comm_world(), 1)

                h5.read(time, "time" + str(i), False)

                self._times[i] = time.get_local()[0]

        self.newton_solution = fenics.Function(self.function_space)

        self.setup_solver()
Esempio n. 5
0
    def load_mesh(self):
        """
        Method to load the mesh file given the mesh folder path.
        Returns:

        """
        return fn.Mesh(self.mesh_folder_path)
Esempio n. 6
0
 def _build_mesh(self):
     args = self.args
     # mesh = fa.Mesh(args.root_path + '/' + args.solutions_path + '/saved_mesh/mesh_square.xml')
     mesh = fa.Mesh(args.root_path + '/' + args.solutions_path +
                    '/saved_mesh/mesh_disk.xml')
     # mesh = fa.RectangleMesh(fa.Point(0, 0), fa.Point(1, 1), 3, 3)
     self.mesh = mesh
Esempio n. 7
0
    def build_mesh(self):
        self.length = 1.
        self.height = 1.

        self.mesh = fe.Mesh()
        editor = fe.MeshEditor()
        editor.open(self.mesh, 'triangle', 2, 2)
        editor.init_vertices(10)
        editor.init_cells(8)
        editor.add_vertex(0, fe.Point(0.5, 0.5))
        editor.add_vertex(1, fe.Point(1., 0.5))
        editor.add_vertex(2, fe.Point(1., 1.))
        editor.add_vertex(3, fe.Point(0.5, 1.))
        editor.add_vertex(4, fe.Point(0., 1.))
        editor.add_vertex(5, fe.Point(0., 0.5))
        editor.add_vertex(6, fe.Point(0., 0.))
        editor.add_vertex(7, fe.Point(0.5, 0.))
        editor.add_vertex(8, fe.Point(1., 0.))
        editor.add_vertex(9, fe.Point(0., 0.5))
        editor.add_cell(0, [0, 1, 3])
        editor.add_cell(1, [1, 2, 3])
        editor.add_cell(2, [0, 3, 4])
        editor.add_cell(3, [0, 4, 5])
        editor.add_cell(4, [0, 9, 7])
        editor.add_cell(5, [6, 7, 9])
        editor.add_cell(6, [0, 7, 8])
        editor.add_cell(7, [0, 8, 1])
        editor.close()

        base_refinement = 4
        self.total_refinement = base_refinement + self.local_refinement_iteration

        for i in range(self.total_refinement):
            self.mesh = fe.refine(self.mesh)
Esempio n. 8
0
    def load(self):
        # Convert mesh from MSH to Dolfin-XML
        shutil.copyfile("input/%s.msh" % input_mesh, "%s.msh" % input_mesh)
        destination_xml = "%s.xml" % input_mesh
        subprocess.call(
            ["dolfin-convert",
             "%s.msh" % input_mesh, destination_xml])

        # Load mesh and boundaries
        mesh = d.Mesh(destination_xml)

        self.patches = d.MeshFunction("size_t", mesh,
                                      "%s_facet_region.xml" % input_mesh)
        self.subdomains = d.MeshFunction("size_t", mesh,
                                         "%s_physical_region.xml" % input_mesh)

        # Define differential over subdomains
        self.dxs = d.dx[self.subdomains]

        # Turn subdomains into a Numpy array
        self.subdomains_array = N.asarray(self.subdomains.array(),
                                          dtype=N.int32)

        # Create a map from subdomain indices to tissues
        self.tissues_by_subdomain = {}
        for i, t in v.tissues.items():
            print(i, t)
            for j in t["indices"]:
                self.tissues_by_subdomain[j] = t

        self.mesh = mesh

        self.setup_fe()
        self.prepare_increase_conductivity()
Esempio n. 9
0
def adapt_coarse_solution_to_fine_solution(scalar,
                                           coarse_solution,
                                           fine_solution,
                                           element,
                                           absolute_tolerance=1.e-2,
                                           maximum_refinement_cycles=6,
                                           circumradius_threshold=0.01):
    """ Refine the mesh of the coarse solution until the interpolation error tolerance is met. """
    adapted_coarse_mesh = fenics.Mesh(coarse_solution.function_space().mesh())

    adapted_coarse_function_space = fenics.FunctionSpace(
        adapted_coarse_mesh, element)

    adapted_coarse_solution = fenics.Function(adapted_coarse_function_space)

    adapted_coarse_solution.leaf_node().vector(
    )[:] = coarse_solution.leaf_node().vector()

    for refinement_cycle in range(maximum_refinement_cycles):

        cell_markers = fenics.MeshFunction(
            "bool", adapted_coarse_mesh.leaf_node(),
            adapted_coarse_mesh.topology().dim(), False)

        for coarse_cell in fenics.cells(adapted_coarse_mesh.leaf_node()):

            coarse_value = scalar(adapted_coarse_solution.leaf_node(),
                                  coarse_cell.midpoint())

            fine_value = scalar(fine_solution.leaf_node(),
                                coarse_cell.midpoint())

            if (abs(coarse_value - fine_value) > absolute_tolerance):

                cell_markers[coarse_cell] = True

        cell_markers = unmark_cells_below_circumradius(
            adapted_coarse_mesh.leaf_node(), cell_markers,
            circumradius_threshold)

        if any(cell_markers):

            adapted_coarse_mesh = fenics.refine(adapted_coarse_mesh,
                                                cell_markers)

            adapted_coarse_function_space = fenics.FunctionSpace(
                adapted_coarse_mesh, element)

            adapted_coarse_solution = fenics.project(
                fine_solution.leaf_node(),
                adapted_coarse_function_space.leaf_node())

        else:

            break

    return adapted_coarse_solution, adapted_coarse_function_space, adapted_coarse_mesh
Esempio n. 10
0
def distribute_mesh(mesh):
    """Distribute a local copy of a mesh

    Required argument:
    mesh: a sequential copy of the mesh to be distributed. Only the
    copy on the rank 0 process is used. This mesh will be distribuetd
    among all processes connected to MPI.COMM_WORLD so that it can be
    used for FEniCS computations.

    Return value: the distributed mesh
    """
    scomm = MPI.COMM_SELF
    wcomm = MPI.COMM_WORLD
    gmesh = gather_mesh(mesh)
    if wcomm.rank == 0:
        assert (gmesh.mpi_comm().size == 1)  # check it's sequential
        with tempfile.TemporaryDirectory() as td:
            meshfile = os.path.join(td, 'mesh.xml')
            logGATHER('writing ' + meshfile)
            File(MPI.COMM_SELF, meshfile) << gmesh
            logGATHER('broadcasting meshfile')
            meshfile = wcomm.bcast(meshfile, root=0)
            try:
                with open(meshfile, 'r') as mf:  # rank 0
                    dmesh = fe.Mesh(wcomm, meshfile)
                    logGATHER('dmesh', dmesh)
            except FileNotFoundError:
                logGATHER('meshfile', meshfile, 'not found')
            wcomm.Barrier()  # wait for everyone to read it
            logGATHER('destroying temp directory')
        # context manager destroyed, temp dir gets deleted
    else:
        meshfile = None
        logGATHER('receiving broadcast meshfile')
        meshfile = wcomm.bcast(meshfile, root=0)
        logGATHER('meshfile', meshfile)
        try:
            with open(meshfile, 'r') as mf:  # rank != 0
                dmesh = fe.Mesh(wcomm, meshfile)
                logGATHER('dmesh', dmesh)
        except FileNotFoundError:
            logGATHER('meshfile', meshfile, 'not found')
        wcomm.Barrier()
    return (dmesh)
Esempio n. 11
0
def meshReader(dictMesh):
    ''' converts json mesh to fenics mesh and apply the boundary conditions.
    dict:: dictMesh,  the mesh from database in the form of a python dictionary

    output:
    dolfin.ccp.mesh:: feMesh, mesh defined in fenics object
    '''

    # conver dict to object
    mesh = namedtuple("mesh", dictMesh.keys())(*dictMesh.values())

    nodes = np.array(mesh.nodes)
    cells = np.array(mesh.connectivity, dtype=np.uintp)

    feMesh = fn.Mesh()

    editor = fn.MeshEditor()
    # cell type, topological, and geometrical dimensions. i.e. 2, 3 for 3d surface mesh
    editor.open(feMesh, "triangle", 2, 3)
    # cell types available:  point, interval, triangle, quadrilateral, tetrahedron, hexahedron
    editor.init_vertices(len(mesh.nodes))
    editor.init_cells(len(mesh.connectivity))

    [editor.add_vertex(i, n) for i, n in enumerate(nodes)]
    [editor.add_cell(i, n - 1) for i, n in enumerate(cells)]
    editor.close()

    # construct faces
    faceSets = fn.MeshFunction('size_t', feMesh, 2)
    for face, faceCells in mesh.faces.items():
        for index in faceCells:
            faceSets.set_value(index, int(face), feMesh)

    # construct edges
    edgeSets = fn.MeshFunction('size_t', feMesh, 1)
    meshEdges = {}
    for edge in fn.edges(feMesh):
        meshEdges[edge.index()] = []
        for vert in fn.vertices(edge):
            meshEdges[edge.index()].append(vert.index())

    for edge, nodes in meshEdges.items():
        for edgeName, edgeList in mesh.edges.items():
            if nodes in edgeList:
                edgeSets.set_value(edge, int(edgeName), feMesh)

    # construct points
    pointSets = fn.MeshFunction('size_t', feMesh, 0)
    for pointName, point in mesh.points.items():
        pointSets.set_value(point, int(pointName), feMesh)

    return dict(feMesh=feMesh,
                faceSets=faceSets,
                edgeSets=edgeSets,
                pointSets=pointSets)
Esempio n. 12
0
 def readMesh(self):
     """
     If mesh instance is None, read mesh instance from file denoted
     by filename property.
     """
     # TODO: implement mesh read in for open file
     if self.mesh is None:
         xdmffile = fenics.XDMFFile(self.xdmffilename)
         self.mesh = fenics.Mesh()
         xdmffile.read(self.mesh)
         xdmffile.close()
Esempio n. 13
0
    def build_mesh(self):
        path_to_msh = 'data/gmsh/{}/{}/mesh'.format(self.case_name,
                                                    self.mesh_refinement_level)
        save_with_meshio(path_to_msh, 2)

        path_to_xdmf = 'data/gmsh/{}/{}/mesh.xdmf'.format(
            self.case_name, self.mesh_refinement_level)
        xdmf_mesh = fe.XDMFFile(path_to_xdmf)
        self.mesh = fe.Mesh()
        xdmf_mesh.read(self.mesh)

        self.length = 500
        self.height = 500
        self.segment = 30

        # domain = mshr.Polygon([fe.Point(0., 0.),
        #                        fe.Point(0., self.height)])
        # resolution = 100 if self.local_refinement_iteration == 0 else 200
        # self.mesh = mshr.generate_mesh(domain, resolution)

        # Reference
        # https://scicomp.stackexchange.com/questions/32647/how-to-use-meshfunction-in-fenics-dolfin
        # https://fenicsproject.org/qa/596/setting-condition-for-mesh-refinement/
        # for i in range(self.local_refinement_iteration):
        #     cell_markers = fe.MeshFunction('bool', self.mesh, self.mesh.topology().dim())
        #     cell_markers.set_all(False)
        #     for cell in fe.cells(self.mesh):
        #         p = cell.midpoint()
        #         if  p[0] > 1./20.*self.length and p[0] < 10.5/20.*self.length and p[1] > 9.5/20.*self.height and p[1] < 13/20*self.height:
        #         # if np.sqrt((p[0] - self.length/2.)**2 + (p[1] - self.height/2.)**2) < self.length/5.:
        #             cell_markers[cell] = True
        #     self.mesh = fe.refine(self.mesh, cell_markers)

        length = self.length
        height = self.height
        segment = self.segment

        class Lower(fe.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and fe.near(x[1], 0)

        class Upper(fe.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and fe.near(x[1], height)

        class Segment(fe.SubDomain):
            def inside(self, x, on_boundary):
                return fe.near(x[1], height / 2.) and fe.near(
                    x[0], length - segment)
                # return  fe.near(x[1], height/2.) and x[0] >= length - segment

        self.lower = Lower()
        self.upper = Upper()
        self.segment = Segment()
Esempio n. 14
0
def wrapper2D(par, meshName, N_PN, boundaryFilePrefix, solutionFolder):
    #-------- load mesh --------
    mesh = fe.Mesh(meshName + '.xml')
    boundaryMarkers = fe.MeshFunction('size_t', mesh, meshName + '_facet_region.xml')
    ds = fe.Measure('ds', domain=mesh, subdomain_data=boundaryMarkers)
    
    u = solvePN2nd(par, N_PN, mesh, boundaryFilePrefix, ds)
    #fe.plot(u[0])

    # first moment:     u0 = int_{4pi} I * b0 dOmega, b0 = sqrt(1 / 4 / pi)
    # radiative energy: phi = int_{4pi} I dOmega 
    radiativeEnergy = np.sqrt(4 * np.pi) * u[0].compute_vertex_values()
    createFolder(solutionFolder)
    sio.savemat('%sradiativeEnergy_P%d2nd_%s.mat'%(solutionFolder, N_PN, meshName.split('/')[-1]),
                    {'radiativeEnergy': radiativeEnergy, 'points': mesh.coordinates(),
                     'connectivityList': mesh.cells()})
    
    return u
Esempio n. 15
0
 def readXDMFFile(self, xdmffilename, group_value_dict):
     xdmffile = fenics.XDMFFile(xdmffilename)
     self.group_value_dict = group_value_dict
     self.mesh = fenics.Mesh()
     xdmffile.read(self.mesh)
     self.markers = {}
     self.marked = {}
     self.ds = {}
     self.bcs = {}
     for (key, value) in self.group_value_dict.iteritems():
         # Fenics interface here: create facet function of type size_t (positive int) for every group
         # TODO: examine whether size_t is appropriate or this class could be generalized
         self.markers[key] = fenics.FacetFunction("size_t", self.mesh)
         xdmffile.read(self.markers[key], key)
         self.marked[key] = value.get("marked", 1)
         self.ds[key] = fenics.Measure("ds", domain=self.mesh, subdomain_data=self.markers[key])
         self.bcs[key] = value
     xdmffile.close()
Esempio n. 16
0
def preprocess(fname):
    """Loads mesh, defines system of equations and prepares system matrix."""
    mesh = fe.Mesh(fname + ".xml")
    if INPUTS['saving']['mesh']:
        fe.File(fname + "_mesh.pvd") << mesh
    boundaries = fe.MeshFunction('size_t', mesh, fname + '_facet_region.xml')
    if INPUTS['saving']['boundaries']:
        fe.File(fname + "_subdomains.pvd") << boundaries
    subdomains = fe.MeshFunction('size_t', mesh,
                                 fname + '_physical_region.xml')
    if INPUTS['saving']['subdomains']:
        fe.File(fname + "_subdomains.pvd") << subdomains
    if INPUTS['plotting']['mesh']:
        fe.plot(mesh, title='Mesh')
    if INPUTS['plotting']['boundaries']:
        fe.plot(boundaries, title='Boundaries')
    if INPUTS['plotting']['subdomains']:
        fe.plot(subdomains, title='Subdomains')
    fun_space = fe.FunctionSpace(mesh,
                                 INPUTS['element_type'],
                                 INPUTS['element_degree'],
                                 constrained_domain=PeriodicDomain())
    if ARGS['--verbose']:
        dofmap = fun_space.dofmap()
        print('Number of DOFs:', len(dofmap.dofs()))
    field = fe.TrialFunction(fun_space)
    test_func = fe.TestFunction(fun_space)
    cond = Conductivity(subdomains,
                        fe.Constant(INPUTS['conductivity']['gas']),
                        fe.Constant(INPUTS['conductivity']['solid']),
                        degree=0)
    system_matrix = -cond * fe.inner(fe.grad(field),
                                     fe.grad(test_func)) * fe.dx
    bctop = fe.Constant(INPUTS['boundary_conditions']['top'])
    bcbot = fe.Constant(INPUTS['boundary_conditions']['bottom'])
    bcs = [
        fe.DirichletBC(fun_space, bctop, boundaries, 1),
        fe.DirichletBC(fun_space, bcbot, boundaries, 2)
    ]
    field = fe.Function(fun_space)
    return system_matrix, field, bcs, cond
Esempio n. 17
0
    def read_checkpoint(self, checkpoint_filepath):
        """Read the checkpoint solution and time, perhaps to restart."""
        phaseflow.helpers.print_once("Reading checkpoint file from " +
                                     checkpoint_filepath)

        self.mesh = fenics.Mesh()

        with fenics.HDF5File(self.mesh.mpi_comm(), checkpoint_filepath,
                             "r") as h5:

            h5.read(self.mesh, "mesh", True)

        self.setup_element()

        self.setup_function_space()

        self.setup_states()

        with fenics.HDF5File(self.mesh.mpi_comm(), checkpoint_filepath,
                             "r") as h5:

            h5.read(self.old_state.solution, "solution")

            if self.second_order_time_discretization:

                h5.read(self.old_old_state.solution, "old_solution")

        with h5py.File(checkpoint_filepath, "r") as h5:

            self.old_state.time = h5["time"].value

            self.set_timestep_size(h5["timestep_size"].value)

            if self.second_order_time_discretization:

                self.old_old_state.time = h5["old_time"].value

        self.restarted = True

        self.output_dir += "restarted_t" + str(self.old_state.time) + "/"
Esempio n. 18
0
    def build_mesh(self):
        # Read mesh from matlab file .mat and convert it to FEniCS mesh
        mesh_matlab = loadmat('data/mat/mesh/PF-1.mat')
        points = mesh_matlab['p']
        cells = mesh_matlab['t']
        points = points.T
        cells = [("triangle", (cells[:-1, :] - 1).T)]
        meshio.write_points_cells(
            'data/xdmf/{}/mesh.xdmf'.format(self.case_name), points, cells)
        xdmf_mesh = fe.XDMFFile('data/xdmf/{}/mesh.xdmf'.format(
            self.case_name))
        self.mesh = fe.Mesh()
        xdmf_mesh.read(self.mesh)

        self.length = 1
        self.height = 1
        length = self.length
        height = self.height

        class Lower(fe.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and fe.near(x[1], 0)

        class Upper(fe.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and fe.near(x[1], height)

        class Corner(fe.SubDomain):
            def inside(self, x, on_boundary):
                return fe.near(x[0], 0) and fe.near(x[1], 0)

        class Middle(fe.SubDomain):
            def inside(self, x, on_boundary):
                return np.absolute(
                    x[1] - 0.5) < 1e-2 and (x[0] - 0.3) * (x[0] - 0.7) < 1e-7

        self.lower = Lower()
        self.upper = Upper()
        self.corner = Corner()
        self.middle = Middle()
Esempio n. 19
0
        def readXDMFfile(self, xdmffilename, group_value_dict):
            """
            Initialization of CellExpressionXDMF by reading an XDMF file.

            @param: xdmffilename: path to xdmf file
            @param: group_value_dict: {"groupname":function(x)}

            function(x) is a function which is evaluated at the marked positions of the cells
            """
            xdmffile = fenics.XDMFFile(xdmffilename)
            self.group_value_dict = group_value_dict
            self.mesh = fenics.Mesh()
            xdmffile.read(self.mesh)
            self.markers = {}
            self.dx = {}
            for (key, value) in self.group_value_dict.iteritems():
                # Fenics interface here: create cell function of type int for every group
                # TODO: examine whether int is appropriate or this class could be generalized
                self.markers[key] = fenics.CellFunction("size_t", self.mesh)
                xdmffile.read(self.markers[key], key)
                self.dx[key] = fenics.Measure("dx", domain=self.mesh, subdomain_data=self.markers[key])
            xdmffile.close()
Esempio n. 20
0
def _inp_to_XML(args):

    input_name = args['names'][0]
    output_name = args['names'][1]

    if not input_name:
        return 'no input name'
    if not output_name:
        return 'no output name'

    try:
        file = open(input_name, 'r')
        csv_file = csv.reader(file, delimiter=',', skipinitialspace=True)
    except FileNotFoundError:
        return FileNotFoundError

    exists = os.path.isfile(output_name)
    if exists:
        return 'Not removing an existed file:' + output_name
    else:
        ofile = open(output_name, "w+")

    try:
        nodes, elems, node_sets, cell_sets = _read_input(csv_file, ofile)
        # Close CSV object
        file.close()
        del csv_file
    except:
        raise
    result = _write_XMP(ofile, nodes, elems, node_sets, cell_sets)
    ofile.close()

    if result:
        try:
            mesh = fe.Mesh(output_name)
            result = 'The XML file is created and tested.'
        except:
            raise
    return result
Esempio n. 21
0
def load_2d_muscle_geo(filename='../geo/muscle_2d.xml', L0=1e-2):

    mesh = fe.Mesh(filename)
    coords = mesh.coordinates()
    coords *= L0
    mesh.bounding_box_tree().build(mesh)

    # Define Boundaries
    bottom = fe.CompiledSubDomain("near(x[1], side, 0.01) && on_boundary", side=-20.0 * L0)
    top = fe.CompiledSubDomain("near(x[1], side, 0.01) && on_boundary", side=20.0 * L0)

    # Initialize mesh function for boundary domains
    boundaries = fe.MeshFunction('size_t', mesh, 2)
    boundaries.set_all(0)
    bottom.mark(boundaries, 1)
    top.mark(boundaries, 2)

    # Define new measures associated with the interior domains and
    # exterior boundaries

    dx = fe.Measure('dx', domain=mesh)
    ds = fe.Measure('ds', domain=mesh, subdomain_data=boundaries)

    return mesh, dx, ds, {"top": top, "bottom": bottom}
Esempio n. 22
0
# Get the libraries
import fenics as fn
import numpy as np
import sympy as sym
import scipy as sc
from scipy import constants
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm  #Colormap
import meshio as mio
#import mshr as msr

# %%

# %%
mesh = fn.Mesh()
with fn.XDMFFile("meshing/Dmesh.xdmf") as infile:
    infile.read(mesh)
mvc = fn.MeshValueCollection("size_t", mesh, 2)
with fn.XDMFFile("meshing/Dmf.xdmf") as infile:
    infile.read(mvc, "name_to_read")
mf = fn.cpp.mesh.MeshFunctionSizet(mesh, mvc)

# %%
M = 2  #species

Poly = fn.FiniteElement('Lagrange', mesh.ufl_cell(), 2)
Multi = fn.FiniteElement('Real', mesh.ufl_cell(), 0)
ElemP = [Poly] * (M + 1)
ElemR = [Multi] * (M)
Elem = [ElemP + ElemR][0]
Esempio n. 23
0
 def _load_fct(path):
     return fn.Mesh(path)
Esempio n. 24
0
import fenics as fe
import dolfin
import numpy as np
from dolfin.fem.norms import errornorm
from dolfin.common.plotting import plot
import matplotlib.pyplot as plt
import sys

EPSILON = 1.0e-14
DEG = 2

mesh = fe.Mesh('step.xml')

# Control pannel
MODEL = False  # flag to use SA model
b = fe.Expression(('0', '0'), degree=DEG)  # forcing
nu = fe.Constant(2e-6)
rho = fe.Constant(1)
RE = 0.01
lmx = 1  # mixing length
dt = 0.1
# Re = 10 / 1e-4 = 1e5

V = fe.VectorElement("Lagrange", mesh.ufl_cell(), 2)
P = fe.FiniteElement("Lagrange", mesh.ufl_cell(), 1)
NU = fe.FiniteElement("Lagrange", mesh.ufl_cell(), 1)
if MODEL: M = fe.MixedElement([V, P, NU])
else: M = fe.MixedElement([V, P])
W = fe.FunctionSpace(mesh, M)

W0 = fe.Function(W)
 def load_mesh(self, fn: str = None):
     if fn is not None:
         self.mesh = fe.Mesh(fn)
     else:
         self.mesh = fe.UnitCubeMesh(10, 12, 14)
Esempio n. 26
0
                            _Faces[key] = grp
                            break
        for key in _Faces.keys():
            del _groups[key]
        for key, value in _Faces.items():
            _Faces[key] = list(map(int, value))
        for key, value in _groups.items():
            _groups[key] = list(map(int, value))
        return _groups, _Faces


ImportedMesh = MeshImport("./UserFiles/myMesh.unv")
ImportedMesh.UNVtoXMLConverter()
Edges, Faces = ImportedMesh.MeshGroups()

mesh = fn.Mesh("./UserFiles/mesh.xml")

V = fn.FunctionSpace(mesh, 'CG', 1)
# Create subdomains
BoundaryEdges = fn.BoundaryMesh(mesh, 'exterior').entity_map(1).array()
BoundaryNodes = fn.BoundaryMesh(mesh, 'exterior').entity_map(0).array()
boundaries = fn.MeshFunction('size_t', mesh, dim=1)
boundaries.set_all(0)
interior = {}
idx = 1
for key, nodes in Edges.items():
    if all(item in BoundaryNodes for item in nodes):
        for node in nodes:
            ver = fn.Vertex(mesh, node)
            for edge in fn.edges(ver):
                if edge.index() in BoundaryEdges:
Esempio n. 27
0
########################### COMPILER OPTIONS #################################
fe.parameters.linear_algebra_backend = 'PETSc'
fe.parameters.form_compiler.cpp_optimize_flags = '-O3'
fe.parameters.form_compiler.quadrature_degree = 3

############################### IMPORT MESH ##################################
#cprint("\nMESH PRE-PROCESSING", 'blue', attrs=['bold'])
# Import mesh and groups
#cprint("Creating gmsh mesh...", 'green')
subprocess.check_output("gmsh ./gmsh/beam.geo -3", shell=True)
#cprint("Converting mesh to DOLFIN format...", 'green')
subprocess.check_output('dolfin-convert ./gmsh/beam.msh mesh/beam.xml',
                        shell=True)
#cprint("Importing mesh in FEniCS...", 'green')
mesh = fe.Mesh('mesh/beam.xml')
#cprint("Generating boundaries and subdomains...", 'green')
subdomains = fe.MeshFunction("size_t", mesh, "mesh/beam_physical_region.xml")
boundaries = fe.MeshFunction("size_t", mesh, "mesh/beam_facet_region.xml")

# Redefine the integration measures
dxp = fe.Measure('dx', domain=mesh, subdomain_data=subdomains)
dsp = fe.Measure('ds', domain=mesh, subdomain_data=boundaries)

##################### FINITE ELEMENT SPACES ##################################
# Finite element spaces
W = fe.FunctionSpace(mesh, 'P', 1)
V = fe.VectorFunctionSpace(mesh, 'P', 1)
Z = fe.TensorFunctionSpace(mesh, 'P', 1)

# Finite element functions
Esempio n. 28
0
def expand_mesh(mesh, transform=None):
    """expand_mesh -- expand a corner submesh to a full mesh.

    Required parameter:
    mesh -- the corner submesh to be expanded

    Optional parameter:
    transform -- the transform to integerfiy the vertex
        coordinates of the submesh.

    Returns:
    A list of four values: emsh, maps, cellmaps, and vertexmaps.
    emesh is the desired expanded mesh.
    maps is a list of 2**dim functions. Each, applied to a pair of
        coordinates in the submesh, maps them to a corresponding point
        in the appropriate sector of the expanded mesh.
    cellmaps is a 2**dim x nc integer ndarray (where nc is the number
        of cells in mesh). Each rowlists the cells in one of the
        2**dim sectors of emesh to which cells in the original submesh
        correspond. These lists are all disjoint.
    vertexmaps is a 2**dim x nv integer ndarray (where nv is the
        number of vertexes in mesh. Each row lists the vertexes of
        emesh to which vertexes of the original submesh map. These are
        not disjoint -- they overlap on the border of the submesh.
    """
    nvs = mesh.num_vertices()
    ncs = mesh.num_cells()
    cells = mesh.cells()
    dim = mesh.geometry().dim()
    cols = np.arange(dim)
    icols = ['i' + str(i) for i in range(dim)]
    if transform is None:
        mtrans = integerify_transform(mesh.coordinates())
    else:
        mtrans = transform
    imax = 2 * mtrans[-1]
    mtrans = list(mtrans[:-1]) + [imax]
    meshstats = mesh_stats(mesh)
    width = meshstats['xmax']
    symmetries = evenodd_symmetries(dim)
    maps = [
        lambda x, eo=eo, width=width: 2 * width * eo + (1 - 2 * eo) * x
        for eo in symmetries
    ]
    vertexes = vertex_list(mesh)
    vertexes['mesh'] = np.arange(nvs)
    ecoords = np.concatenate([map(mesh.coordinates()) for map in maps])
    evertexes = vertex_list(ecoords, transform=mtrans)
    evertexes.reset_index(inplace=True)
    evertexes = evertexes.drop_duplicates(subset=icols)
    evertexes.set_index(icols, inplace=True)
    evertexes.sort_index(inplace=True)
    envs = len(evertexes)
    encs = len(maps) * ncs
    emesh = fe.Mesh(MPI.COMM_SELF)
    editor = fe.MeshEditor()
    editor.open(emesh, str(cellShapes[dim - 1]), dim, dim)
    editor.init_vertices_global(envs, envs)
    editor.init_cells_global(encs, encs)
    for v in range(envs):
        coords = evertexes.iloc[v, cols].values
        editor.add_vertex_global(v, v, coords)
    emesh.order()
    evertexes = vertex_list(emesh)
    evertexes['global'] = np.arange(envs)
    base = 0
    cellmaps = []
    vertexmaps = []
    for map in maps:
        scoords = map(mesh.coordinates())
        svertexes = vertex_list(scoords)
        svertexes = svertexes.merge(evertexes, how='inner')
        vertexmap = svertexes['global'].values
        vertexmaps.append(vertexmap)
        for c, cell in enumerate(cells):
            editor.add_cell(base + c, vertexmap[cell])
        cellmap = base + np.arange(ncs)
        cellmaps.append(cellmap)
        base += ncs
    editor.close()
    cellmaps = np.array(cellmaps)
    vertexmaps = np.array(vertexmaps)
    return emesh, maps, cellmaps, vertexmaps
Esempio n. 29
0
def import_mesh(arg):
    """Imports a mesh file for use with CASHOCS / FEniCS.



	This function imports a mesh file that was generated by GMSH and converted to
	.xdmf with the command line function :ref:`cashocs-convert <cashocs_convert>`.
	If there are Physical quantities specified in the GMSH file, these are imported
	to the subdomains and boundaries output of this function and can also be directly
	accessed via the measures, e.g., with ``dx(1)``, ``ds(1)``, etc.

	Parameters
	----------
	arg : str or configparser.ConfigParser
		This is either a string, in which case it corresponds to the location
		of the mesh file in .xdmf file format, or a config file that
		has this path stored in its settings, under the section Mesh, as
		parameter ``mesh_file``.

	Returns
	-------
	mesh : dolfin.cpp.mesh.Mesh
		The imported (computational) mesh.
	subdomains : dolfin.cpp.mesh.MeshFunctionSizet
		A :py:class:`fenics.MeshFunction` object containing the subdomains,
		i.e., the Physical regions marked in the GMSH
		file.
	boundaries : dolfin.cpp.mesh.MeshFunctionSizet
		A MeshFunction object containing the boundaries,
		i.e., the Physical regions marked in the GMSH
		file. Can, e.g., be used to set up boundary
		conditions.
	dx : ufl.measure.Measure
		The volume measure of the mesh corresponding to
		the subdomains (i.e. GMSH Physical region indices).
	ds : ufl.measure.Measure
		The surface measure of the mesh corresponding to
		the boundaries (i.e. GMSH Physical region indices).
	dS : ufl.measure.Measure
		The interior facet measure of the mesh corresponding
		to boundaries (i.e. GMSH Physical region indices).
	"""

    start_time = time.time()
    print('Importing mesh to FEniCS')
    # Check for the file format

    if type(arg) == str:
        mesh_file = arg
        mesh_attribute = 'str'
    elif type(arg) == configparser.ConfigParser:
        mesh_attribute = 'config'
        ### overloading for remeshing
        if not arg.getboolean('Mesh', 'remesh', fallback=False):
            mesh_file = arg.get('Mesh', 'mesh_file')
        else:
            if not ('_cashocs_remesh_flag' in sys.argv):
                mesh_file = arg.get('Mesh', 'mesh_file')
            else:
                temp_dir = sys.argv[-1]
                with open(temp_dir + '/temp_dict.json', 'r') as file:
                    temp_dict = json.load(file)
                mesh_file = temp_dict['mesh_file']

    else:
        raise InputError(
            'cashocs.geometry.import_mesh', 'arg',
            'Not a valid argument for import_mesh. Has to be either a path to a mesh file (str) or a config.'
        )

    if mesh_file[-5:] == '.xdmf':
        file_string = mesh_file[:-5]
    else:
        raise InputError(
            'cashocs.geometry.import_mesh', 'arg',
            'Not a suitable mesh file format. Has to end in .xdmf.')

    mesh = fenics.Mesh()
    xdmf_file = fenics.XDMFFile(mesh.mpi_comm(), mesh_file)
    xdmf_file.read(mesh)
    xdmf_file.close()

    subdomains_mvc = fenics.MeshValueCollection('size_t', mesh,
                                                mesh.geometric_dimension())
    boundaries_mvc = fenics.MeshValueCollection('size_t', mesh,
                                                mesh.geometric_dimension() - 1)

    if os.path.isfile(file_string + '_subdomains.xdmf'):
        xdmf_subdomains = fenics.XDMFFile(mesh.mpi_comm(),
                                          file_string + '_subdomains.xdmf')
        xdmf_subdomains.read(subdomains_mvc, 'subdomains')
        xdmf_subdomains.close()
    if os.path.isfile(file_string + '_boundaries.xdmf'):
        xdmf_boundaries = fenics.XDMFFile(mesh.mpi_comm(),
                                          file_string + '_boundaries.xdmf')
        xdmf_boundaries.read(boundaries_mvc, 'boundaries')
        xdmf_boundaries.close()

    subdomains = fenics.MeshFunction('size_t', mesh, subdomains_mvc)
    boundaries = fenics.MeshFunction('size_t', mesh, boundaries_mvc)

    dx = fenics.Measure('dx', domain=mesh, subdomain_data=subdomains)
    ds = fenics.Measure('ds', domain=mesh, subdomain_data=boundaries)
    dS = fenics.Measure('dS', domain=mesh, subdomain_data=boundaries)

    end_time = time.time()
    print('Done Importing Mesh. Elapsed Time: ' +
          format(end_time - start_time, '.3e') + ' s')
    print('')

    # Add an attribute to the mesh to show with what procedure it was generated
    mesh._cashocs_generator = mesh_attribute

    return mesh, subdomains, boundaries, dx, ds, dS
Esempio n. 30
0
import matplotlib.pyplot as plt

config.update("jax_enable_x64", True)
fn.set_log_level(fn.LogLevel.ERROR)

# Create mesh, refined in the center
n = 64
mesh = fn.UnitSquareMesh(n, n)

cf = fn.MeshFunction("bool", mesh, mesh.geometry().dim())
subdomain = fn.CompiledSubDomain(
    "std::abs(x[0]-0.5) < 0.25 && std::abs(x[1]-0.5) < 0.25"
)
subdomain.mark(cf, True)
mesh = fn.Mesh(fn.refine(mesh, cf))

# Define discrete function spaces and functions
V = fn.FunctionSpace(mesh, "CG", 1)
W = fn.FunctionSpace(mesh, "DG", 0)

solve_templates = (fn.Function(W),)
assemble_templates = (fn.Function(V), fn.Function(W))

# Define and solve the Poisson equation
@build_jax_solve_eval(solve_templates)
def fenics_solve(f):
    u = fn.Function(V, name="State")
    v = fn.TestFunction(V)
    F = (ufl.inner(ufl.grad(u), ufl.grad(v)) - f * v) * ufl.dx
    bcs = [fn.DirichletBC(V, 0.0, "on_boundary")]