コード例 #1
0
def mesh_randomizer_2d(mesh, percentage, preserve_boundary=True):
    """
    Randomly perturb a given mesh.

    Args:
        mesh: Input mesh.
        percentage: Maximum perturbation in percentage of mesh.hmin().
        preserve_boundary: Whether to move the vertices on the boundary.
    Returns:
        rmesh: The perturbed mesh.
    """
    # Generate a deep copy of the mesh
    rmesh = Mesh(mesh)
    meshsize = rmesh.hmin()
    # Randomly perturbed the mesh
    radius = np.random.rand(rmesh.num_vertices()) * percentage * meshsize
    theta = np.random.rand(rmesh.num_vertices()) * 2.0 * np.pi
    deltax = np.zeros([rmesh.num_vertices(), 2])
    deltax[:, 0] = (radius * np.sin(theta)).transpose()
    deltax[:, 1] = (radius * np.cos(theta)).transpose()
    # What to do with the boundary vertices
    if preserve_boundary:
        # Exterior means global boundary
        boundary_mesh = BoundaryMesh(rmesh, "exterior")
        # entity_map contains the indices of vertices on the boundary
        boundary_vertices = boundary_mesh.entity_map(0).array()
        deltax[boundary_vertices] = 0.0
    rmesh.coordinates()[:] = rmesh.coordinates() + deltax
    return rmesh
コード例 #2
0
def verification_distributed_L2(list_dt, mesh_file, g0):
    def speed_function(t_n):
        return 1.

    meshy = Mesh(mesh_file)

    tips_evolution = []
    for dt in list_dt:
        print('dt = %e' % dt)

        Nt = int(Tf / dt)
        rlx = 0.8

        results = initialise_results()

        run_dynamic(results, meshy, u0, 'distributed', g0, dt, Nt, Ur, Gamma,
                    speed_function, rlx)

        wx_tip = results[3][:, -1, 0]
        tips_evolution.append(wx_tip)

    l2s = np.empty(0)
    for i, tip in enumerate(tips_evolution[:-1]):
        diff = tip[i] - tip[i + 1][::2]
        l2 = np.sqrt(np.sum(diff**2) / len(tips_evolution[i]))

        l2s = np.append(l2s, l2)

    return l2s
コード例 #3
0
ファイル: meshing.py プロジェクト: JacobDowns/cslvr
    def extrude_mesh(self, l, z_offset):
        # accepts the number of layers and the length of extrusion

        mesh = self.mesh

        # Extrude vertices
        all_coords = []
        for i in linspace(0, z_offset, l):
            all_coords.append(
                hstack((mesh.coordinates(), i * ones((self.n_v2, 1)))))
        self.global_vertices = vstack(all_coords)

        # Extrude cells (tris to tetrahedra)
        for i in range(l - 1):
            for c in self.mesh.cells():
                # Make a prism out of 2 stacked triangles
                vertices = hstack((c + i * self.n_v2, c + (i + 1) * self.n_v2))

                # Determine prism orientation
                smallest_vertex_index = argmin(vertices)

                # Map to I-ordering of Dompierre et al.
                mapping = self.indirection_table[smallest_vertex_index]

                # Determine which subdivision scheme to use.
                if min(vertices[mapping][[1, 5]]) < min(
                        vertices[mapping][[2, 4]]):
                    local_tets = vstack((vertices[mapping][[0,1,2,5]],\
                                         vertices[mapping][[0,1,5,4]],\
                                         vertices[mapping][[0,4,5,3]]))
                else:
                    local_tets = vstack((vertices[mapping][[0,1,2,4]],\
                                         vertices[mapping][[0,4,2,5]],\
                                         vertices[mapping][[0,4,5,3]]))
                # Concatenate local tet to cell array
                self.global_tets = vstack((self.global_tets, local_tets))

        # Eliminate phantom initialization tet
        self.global_tets = self.global_tets[1:, :]

        # Query number of vertices and tets in new mesh
        self.n_verts = self.global_vertices.shape[0]
        self.n_tets = self.global_tets.shape[0]

        # Initialize new dolfin mesh of dimension 3
        self.new_mesh = Mesh()
        m = MeshEditor()
        m.open(self.new_mesh, 3, 3)
        m.init_vertices(self.n_verts, self.n_verts)
        m.init_cells(self.n_tets, self.n_tets)

        # Copy vertex data into new mesh
        for i, v in enumerate(self.global_vertices):
            m.add_vertex(i, Point(*v))

        # Copy cell data into new mesh
        for j, c in enumerate(self.global_tets):
            m.add_cell(j, *c)

        m.close()
コード例 #4
0
def run_succession(list_Cy):
    list_results = []
    
    meshy = Mesh(mesh_file)
    for Cy in list_Cy:
        print('Cy = %s' % Cy)
        results = run_static(meshy, u0, 'drag', Cd*Cy, rlx)
        list_results.append(results)
        print('')
    
    return list_results
コード例 #5
0
def evenodd_functions_old(
    omesh,
    degree,
    func,
    width=None,
    evenodd=None
):
    """Break a function into even and odd components

    Required parameters:
    omesh: the mesh on which the function is defined
    degree: the degree of the FunctionSpace 
    func: the Function. This has to be something that fe.interpolate
        can interpolate onto a FunctionSpace or that fe.project can
        project onto a FunctionSpace.
    width: the width of the domain on which func is defined. (If not
        provided, this will be determined from omesh.
    evenodd: the symmetries of the functions to be constructed
        evenodd_symmetries(dim) is used if this is not provided
    """
    SS = FunctionSpace(omesh, 'CG', degree)
    dim = omesh.geometry().dim()
    if width is None:
        stats = mesh_stats(omesh)
        width = stats['xmax']
    if evenodd is None:
        evenodd = evenodd_symmetries(dim)
    try:
        f0 = fe.interpolate(func, SS)
    except TypeError:
        f0 = fe.project(func, SS)
    ffuncs = []
    flips = evenodd_symmetries(dim)
    for flip in (flips):
        fmesh = Mesh(omesh)
        SSf = FunctionSpace(fmesh, 'CG', degree)
        ffunc = fe.interpolate(f0, SSf)
        fmesh.coordinates()[:, :] = (width*flip
                                     + (1 - 2*flip)*fmesh.coordinates())
        fmesh.bounding_box_tree().build(fmesh)
        ffuncs.append(ffunc)
    E = evenodd_matrix(evenodd)
    components = matmul(2**(-dim)*E, ffuncs)
    cs = []
    for c in components:
        try:
            cs.append(fe.interpolate(c, SS))
        except TypeError:
            cs.append(fe.project(c, SS, solver_type='lu'))
    return(cs)
コード例 #6
0
def gaussian_mesh_randomizer(mesh, percentage, preserve_boundary=True):
    """
    Randomly perturb a given mesh.

    Args:
        mesh: Input mesh.
        percentage: Maximum perturbation in percentage of mesh.hmin().
        preserve_boundary: Whether to move the vertices on the boundary.
    Returns:
        rmesh: The perturbed mesh.
    """
    rmesh = Mesh(mesh)
    deltax = (np.random.randn(rmesh.num_vertices(),
                              rmesh.geometry().dim()) * percentage *
              rmesh.hmin())
    if preserve_boundary:
        boundary_mesh = BoundaryMesh(rmesh, "exterior")
        boundary_vertices = boundary_mesh.entity_map(0).array()
        deltax[boundary_vertices] = 0.0
    rmesh.coordinates()[:] = rmesh.coordinates() + deltax
    return rmesh
コード例 #7
0
def unit_mesh(ht, hx):
    editor = MeshEditor()
    mesh = Mesh()
    editor.open(mesh, "triangle", 2, 2)
    editor.init_vertices(7)
    editor.add_vertex(0, np.array([0.0, 0.0]))
    editor.add_vertex(1, np.array([ht / 2.0, 0.0]))
    editor.add_vertex(2, np.array([0.0, hx / 2.0]))
    editor.add_vertex(3, np.array([ht / 2.0, hx / 2.0]))
    editor.add_vertex(4, np.array([ht, hx / 2.0]))
    editor.add_vertex(5, np.array([ht / 2.0, hx]))
    editor.add_vertex(6, np.array([ht, hx]))
    editor.init_cells(6)
    editor.add_cell(0, np.array([0, 1, 3], dtype=np.uintp))
    editor.add_cell(1, np.array([0, 2, 3], dtype=np.uintp))
    editor.add_cell(2, np.array([1, 3, 4], dtype=np.uintp))
    editor.add_cell(3, np.array([2, 3, 5], dtype=np.uintp))
    editor.add_cell(4, np.array([3, 4, 6], dtype=np.uintp))
    editor.add_cell(5, np.array([3, 5, 6], dtype=np.uintp))
    editor.close()
    mesh.order()
    return mesh
コード例 #8
0
def verification_distributed_L2(list_Nelem, g0):
    profiles = []

    for n_elems in list_Nelem:
        print('number of elements = %d' % n_elems)
        
        mesh_file = '../xml_files/straight_%s.xml' % n_elems
        
        meshy   = Mesh(mesh_file)
        results = run_static(meshy, u0, 'distributed', g0, relaxation=0.5)
        
        # x-displacement for all nodes
        displ_x = results[3,:,0]
        profiles.append(displ_x)
        
    l2s = np.empty(0)
    for i, prof in enumerate(profiles[:-1]):
        diff = profiles[i] - profiles[i+1][::2]
        l2 = np.sqrt(np.sum(diff**2)/len(profiles[i]))
        
        l2s = np.append(l2s, l2)
      
    return l2s
コード例 #9
0
ファイル: validation_static.py プロジェクト: lm2-poly/RodiCS
def validation_distributed(mesh_file):
    alphas = np.linspace(0.015, 1.25, 60)
    g0s    = g0(alphas)
    
    delta_ROHDE  = th_y_dist(1, alphas)
    delta_FEniCS = np.empty(0)
    
    relaxation = 0.8
    for G0 in g0s:
        print('g0 = %f' % G0)
        
        if G0 > 10:
            relaxation = 0.5
        
        meshy   = Mesh(mesh_file)
        results = run_static(meshy, u0, 'distributed', G0, relaxation=relaxation)
        
        delta = extract_deflection(meshy, u0, results)
        delta_FEniCS = np.append(delta_FEniCS, delta)
        
        print('')
        
    return g0s, delta_ROHDE, delta_FEniCS
コード例 #10
0
u0_ph = (0.00)*np.pi

# u0 is unitary by definition.
u0 = np.array([np.sin(u0_th)*np.cos(u0_ph),
               np.sin(u0_th)*np.sin(u0_ph),
               np.cos(u0_th)])

# Drag coefficient and Cauchy number
Cd = 1.2
Cy = 50

# Relaxation parameter
rlx = 0.8

# Import mesh
meshy   = Mesh(mesh_file)

# Successive simulations
def run_succession(list_Cy):
    list_results = []
    
    meshy = Mesh(mesh_file)
    for Cy in list_Cy:
        print('Cy = %s' % Cy)
        results = run_static(meshy, u0, 'drag', Cd*Cy, rlx)
        list_results.append(results)
        print('')
    
    return list_results

def draw_succession(ax, list_Cy, list_results, colors):
コード例 #11
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_ronne_3D_10H():
   global home
   return Mesh(home + '/antarctica/antarctica_ronne_shelf.xml')
コード例 #12
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_antarctica_3D_gradS_crude():
   global home
   return Mesh(home + '/antarctica/antarctica_3D_gradS_mesh_crude.xml')
コード例 #13
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_antarctica_3D_10k():
   global home
   return Mesh(home + '/antarctica/antarctica_3D_10k.xml')
コード例 #14
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_antarctica_3D_gradS_detailed():
   global home
   return Mesh(home + '/antarctica/antarctica_3D_gradS_mesh_detailed.xml')
コード例 #15
0
ファイル: ksdgsoln.py プロジェクト: leonavery/KSDG
    def __init__(self, prefix, noperiodic=False):
        """Access a KSDG solution.

        Required argument:
        prefix: This is the prefix for the names of the files in which
        the solution is stored. (Typically, it would be the value of
        the --save option to ksdgsolver<d>.py.

        optional argument:
        noperiodic=False: Treat solution as periodic, even if it wasn't.
        """
        self.prefix = os.path.expanduser(prefix)
        self.prefix = os.path.expandvars(self.prefix)
        self.noperiodic = noperiodic
        self.meshfile = self.prefix + '_omesh.xml.gz'
        if os.path.isfile(self.meshfile):
            self.mesh = self.omesh = Mesh(self.meshfile)
        else:
            self.meshfile = prefix + '_mesh.xml.gz'
            self.mesh = Mesh(self.meshfile)
        self.optionsfile = self.prefix + '_options.txt'
        with open(self.optionsfile, 'r') as optsf:
            self.options = optsf.readlines()
        self.fsinfofile = fsinfo_filename(self.prefix, 0)
        with h5py.File(self.fsinfofile, 'r') as fsf:
            self.dim, self.degree = (
                int(fsf['dim'][()]),
                int(fsf['degree'][()]),
            )
            try:
                # self.periodic = fsf['periodic'].value #deprecated
                self.periodic = fsf['periodic'][()]
            except KeyError:
                self.periodic = False
            try:
                self.ligands = pickle.loads(fsf['ligands'][()])
            except KeyError:
                self.ligands = False
            try:
                self.param_names = pickle.loads(fsf['param_names'][()])
                self.variable = True
            except KeyError:
                self.param_names = []
                self.variable = False
            try:
                self.params0 = pickle.loads(fsf['params0'][()])
            except KeyError:
                self.params0 = {}
            try:
                pfuncs = fsf['param_funcs'][()]
                self.param_funcs = dill.loads(pfuncs.tobytes())
            except (KeyError, ValueError):
                self.param_funcs = {}

        def identity(t, params={}):
            return t

        self.param_funcs['t'] = identity
        if self.params0 and self.ligands:
            capp = [s for s in self.options if '--cappotential' in s]
            if 'tophat' in capp[0]:
                self.cappotential = 'tophat'
            elif 'witch' in capp[0]:
                self.cappotential = 'witch'
            self.Vgroups = copy.deepcopy(self.ligands)
            self.Vparams = ParameterList(default_parameters)
            self.Vparams.add(self.Vgroups.params())

            def Vfunc(Us, params={}):
                self.Vparams.update(params)  # copy params into ligands
                return self.Vgroups.V(Us)  # compute V

            def Vtophat(rho, params={}):
                tanh = ufl.tanh((rho - params['rhomax']) / params['cushion'])
                return params['maxscale'] * params['sigma']**2 / 2 * (tanh + 1)

            def Vwitch(rho, params={}):
                tanh = ufl.tanh((rho - params['rhomax']) / params['cushion'])
                return (params['maxscale'] * params['sigma']**2 / 2 *
                        (tanh + 1) * (rho / params['rhomax']))

            Vcap = Vwitch if self.cappotential == 'witch' else Vtophat

            def V2(Us, rho, params={}):
                return Vfunc(Us, params=params) + Vcap(rho, params=params)

            self.V = V2
        self.tsfile = prefix + '_ts.h5'
        self.ts = self.timeSeries = KSDGTimeSeries(self.tsfile, 'r')
        self.tstimes = self.ts.sorted_times()
        self.tmin, self.tmax = self.tstimes[0], self.tstimes[-1]
        kwargs = dict(mesh=self.mesh,
                      dim=self.dim,
                      degree=self.degree,
                      t0=self.tmin,
                      ligands=self.ligands,
                      parameters=self.params0,
                      V=V2,
                      periodic=self.periodic)
        if self.variable:
            kwargs['param_funcs'] = self.param_funcs
        self.ksdg = makeKSDGSolver(**kwargs)
        # self.V = self.ksdg.V
        if self.periodic and self.noperiodic:
            self.mesh = self.ksdg.mesh
            self.meshstats = mesh_stats(self.ksdg.mesh)
        else:
            try:
                self.meshstats = mesh_stats(self.ksdg.omesh)
            except AttributeError:
                self.meshstats = mesh_stats(self.ksdg.mesh)
        if self.periodic and not self.noperiodic:
            self.ex_mesh = ExpandedMesh(self.ksdg.sol)
            self.function = self.ex_mesh.expanded_function
        else:
            self.ex_mesh = None
            self.function = self.ksdg.sol
        self.fs = self.function.function_space()
        self.transform = integerify_transform(
            np.reshape(self.fs.tabulate_dof_coordinates(), (-1, self.dim)))
コード例 #16
0
ファイル: ksdggather.py プロジェクト: leonavery/KSDG
def remap_from_files(prefix, ksdg=None):
    """remap dofs from multiprocess FunctionSpace to single process

    Required parameter:
    prefix -- the filename prefix for the fsinfo files

    Optional parameter:
    ksdg -- the KSDGSolver that defines the single process
            FunctionsSpace

    Returns a vector of integers that can be used to remap degrees of
    freedom on a distributed mesh to those on the local mesh, using
    numpy indirection, i.e.

    remap = remap_from_files(ksdg, local_mesh=lmesh)
    local_function.vector()[:] = global_function.vector()[:][remap]
    
    This function does the same thing as dofremap, but at a different
    time and a different way. Unlike dofremap, remap_from_files is
    called after a solution is finished, not while it is in
    progress. The information about the degrees of freedom is
    retrieved from h5 files created at the time of solution. If the
    solution was run as an MPI group on S processes, there
    remap_from_files consults S+1 files:

    prefix_mesh.xml.gz
    prefixrank0_fsinfo.h5
    prefixrank1_fsinfo.h5
    ...
    prefixrank<S-1>_fsinfo.h5

    The mesh file contains the total mesh for the problem, as
    assembled by gather_mesh. Of the fsinfo files (which contain
    information about the function space local to each MPI process),
    at least the rank0 file must exist. Its 'size' entry is read to
    determine the number of fsinfo files, and its degree and dim
    entries are used to create a FunctionSpace on this mesh (by
    creating a KSDGSolver with those arguments). It then goes through
    the fsinfo files sequentially, determining the mapping from each
    one's DOFs to the DOFs pof the global FunctionSpace. 

    Note: this works only for solutions with a single rho and a single
    U.
    """
    if (ksdg):
        mesh = ksdg.mesh
    else:
        meshfile = prefix + '_mesh.xml.gz'
        mesh = Mesh(meshfile)
    dim = mesh.geometry().dim()
    r0name = fsinfo_filename(prefix, 0)
    with h5py.File(r0name, 'r') as fsf:
        size = fsf['/mpi/size'].value
        if (dim != fsf['dim'].value):
            raise KSDGException("mesh dimension = " + dim +
                                ", FunctionSpace dim = " + fsf['dim'])
        try:
            degree = fsf['degree'].value
        except KeyError:
            degree = 3
            try:
                periodic = fsf['periodic'].value
            except KeyError:
                periodic = False
    if not ksdg:
        from .ksdgmakesolver import makeKSDGSolver  # circular import
        ksdg = makeKSDGSolver(mesh=mesh,
                              degree=degree,
                              project_initial_condition=False,
                              periodic=periodic)
    owneddofs = []
    ltg = []
    dofcoords = []
    dofs = []
    rho_dofs = []
    U_dofs = []
    cell_dofs = []
    cell_indices = []
    #
    # collect info about each processes dofs from files
    #
    for rank in range(size):
        rname = fsinfo_filename(prefix, rank)
        with h5py.File(rname, 'r') as fsf:
            owneddofs.append(fsf['ownership_range'].value.copy())
            ltg.append(fsf['tabulate_local_to_global_dofs'].value.copy())
            dofcoords.append(fsf['dofcoords'].value[0].copy())
            dofs.append(fsf['dofs'].value.copy())
            U_dofs.append(fsf['U_dofs'].value.copy())
            rho_dofs.append(fsf['rho_dofs'].value.copy())
            cell_dofs.append(fsf['cell_dofs'].value.copy())
            cell_indices.append(fsf['/mesh/cell_indices'].value.copy())
    transform = integerify_transform(dofcoords)
    spacing = transform[0]
    base = transform[1]
    #
    # check against global info
    #
    owneddofs = np.array(owneddofs)
    gdofmap = ksdg.VS.dofmap()
    gdofrange = gdofmap.ownership_range()
    if gdofrange[0] != 0:
        raise KSDGException("First dof %d, expected 0", gdofrange[0])
    fdofmin = owneddofs[:, 0].min()
    fdofmax = owneddofs[:, 1].max()
    if (fdofmin != gdofrange[0] or fdofmax != gdofrange[1]):
        raise KSDGException("dof mismatch: global %d - %d, files %d - %d" %
                            (gdofrange[0], gdofrange[1], fdofmin, fdofmax))
    fdofs = np.zeros((gdofrange[1], dim + 2))
    #
    # combine file info into one list of file dofs
    #
    for rank in range(size):
        fdofs[rho_dofs[rank], 1] = 0.0
        fdofs[U_dofs[rank], 1] = 1.0
        ncells = cell_indices[rank].shape[0]
        dofspercell = cell_dofs[rank].shape[1]
        for cell in range(ncells):
            fdofs[ltg[rank][cell_dofs[rank][cell]],
                  0] = cell_indices[rank][cell]
        nlocal = owneddofs[rank, 1] - owneddofs[rank, 0]
        fdofs[ltg[rank][:nlocal], 2:] = dofcoords[rank]
    #
    # assemble global dof list
    #
    ifdofs = np.empty_like(fdofs, dtype=int)
    np.rint(fdofs[:, :2], out=ifdofs[:, :2], casting='unsafe')
    np.rint(fdofs[:, 2:] / spacing - base, out=ifdofs[:, 2:], casting='unsafe')
    gdofs = local_dofs(ksdg)
    gdofs = gdofs[:, :-1]
    igdofs = np.empty_like(gdofs, dtype=int)
    np.rint(gdofs[:, :2], out=igdofs[:, :2], casting='unsafe')
    np.rint(gdofs[:, 2:] / spacing - base, out=igdofs[:, 2:], casting='unsafe')
    #
    # DOFs belonging to R subspaces don't have cells or coordinates
    #
    Rdofs = np.array([], dtype=int)
    for ss in subspaces(fs):
        if isRsubspace(ss):
            Rdofs = np.append(Rdofs, ss.dofmap().dofs())
    logGATHER('Rdofs', Rdofs)
    try:
        doflist[Rdofs - owneddofs[0], 1] = -2.0
        doflist[Rdofs - owneddofs[0], 2:-1] = -float('inf')
    except IndexError:
        logGATHER('IndexError: Rdofs-owneddofs[0]', Rdofs - owneddofs[0])
    return (remap_list(ifdofs, igdofs, fdofs, gdofs))
コード例 #17
0
from gmsh_interface import GmshInterface

g = GmshInterface("../geo/simple_muscle_3d.geo")
g.set_parameter("lc",0.1)
g.generate_xml("../geo/test.xml")




from fenics import Mesh, plot
import matplotlib.pyplot as plt

mesh = Mesh("../geo/test.xml")
plot(mesh)
plt.show()
コード例 #18
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_greenland_2D_5H_sealevel():
   global home
   return Mesh(home + '/greenland/greenland_2D_5H_sealevel.xml')
コード例 #19
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_greenland_coarse():
   global home
   return Mesh(home + '/greenland/greenland_coarse_mesh.xml')
コード例 #20
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_greenland_medium():
   global home
   return Mesh(home + '/greenland/greenland_medium_mesh.xml')
コード例 #21
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_greenland_detailed():
   global home
   return Mesh(home + '/greenland/greenland_detailed_mesh.xml')
コード例 #22
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_circle():
   global home
   return Mesh(home + '/test/circle_mesh.xml.gz')
コード例 #23
0
from fenics import MPI, Mesh, MeshValueCollection, XDMFFile, cpp, Measure, assemble, Constant

mesh = Mesh()
mvc = MeshValueCollection("size_t", mesh, mesh.topology().dim())
with XDMFFile(MPI.comm_world, "mesh/StraightPipe/mesh.xdmf") as infile:
    infile.read(mesh)
    infile.read(mvc, "name_to_read")

mvc = MeshValueCollection("size_t", mesh, mesh.topology().dim() - 1)
with XDMFFile(MPI.comm_world, "mesh/StraightPipe/mf.xdmf") as infile:
    infile.read(mvc, "name_to_read")

mf = cpp.mesh.MeshFunctionSizet(mesh, mvc)

# TODO: does not work well with mpi implementation, need to modify
# xmin = mesh.coordinates()[:, 0].min()
# xmax = mesh.coordinates()[:, 0].max()
# ymin = mesh.coordinates()[:, 1].min()
# ymax = mesh.coordinates()[:, 1].max()
# zmin = mesh.coordinates()[:, 2].min()
# zmax = mesh.coordinates()[:, 2].max()
# dx = Measure("dx", domain=mesh)
# volume = assemble(Constant(1) * dx)

# if MPI.rank(MPI.comm_world)==0:
#     print("Mesh informations:")
#     print("xmin, xmax: {}, {}".format(xmin, xmax))
#     print("ymin, ymax: {}, {}".format(ymin, ymax))
#     print("zmin, zmax: {}, {}".format(zmin, zmax))
#     print("Number of cells: {}".format(mesh.num_cells()))
#     print("Number of edges: {}".format(mesh.num_edges()))
コード例 #24
0
ファイル: ksdggather.py プロジェクト: leonavery/KSDG
def gather_mesh(mesh):
    """Gather a local copy of a distributed mesh"""
    # comm = MPI.COMM_WORLD
    if mesh in gather_mesh_cache:
        logGATHER('gather_mesh cache hit')
        return gather_mesh_cache[mesh]
    comm = mesh.mpi_comm()
    size = comm.size
    if size == 1:
        gather_mesh_cache[mesh] = mesh
        return (mesh)  # sequential: nothing to do
    dim = mesh.geometry().dim()
    topology = mesh.topology()
    logGATHER('topology.global_indices(0)', topology.global_indices(0))
    logGATHER('topology.size(0)', topology.size(0))
    #
    # To define a mesh, we need two things: a list of all the
    # vertices, each with an index and coordinates, and a list of all
    # cells, each specified by a list of vertices.
    #
    vcoord = mesh.coordinates()
    vcoords = gather_array(vcoord, comm)  # vertexes from all processes
    vindex = topology.global_indices(0)
    vindexes = gather_array(vindex, comm)  # global vertex indexes
    try:
        gnv = topology.size_global(0)
    except AttributeError:
        gnv = np.max(vindexes) + 1
    logGATHER('gnv', gnv)
    gvcs = np.zeros((gnv, dim), dtype=vcoords.dtype)
    for v, vc in enumerate(vcoords):  # coords indexed by global indices
        gvcs[vindexes[v], :] = vc
    logGATHER('gvcs', gvcs)
    #
    # We now have in gvcs a list of global vertex coordinates. (The
    # indices are just 0...len(gvcs)-1.) Now for the cells:
    #
    nc = mesh.num_cells()
    logGATHER('nc', nc)
    total = comm.allreduce(nc)
    logGATHER('total', total)
    cell = np.zeros(nc * (dim + 1), dtype=int)
    cell[:] = vindex[mesh.cells().flatten()]  # vindex to get global indices
    logGATHER('cell', cell)
    cells = gather_array(cell, comm)
    cells = cells.reshape(-1, dim + 1)
    logGATHER('cells', cells)
    cindex = topology.global_indices(dim)
    logGATHER('cindex', cindex)
    cindexes = gather_array(cindex, comm)
    logGATHER('cindexes', cindexes)
    try:
        gnc = topology.size_global(dim)
    except AttributeError:
        gnc = np.max(cindexes) + 1
    logGATHER('gnc', gnc)
    gcells = np.zeros((gnc, dim + 1), dtype=int)
    for v, cell in enumerate(cells):
        gcells[cindexes[v], :] = cell
    logGATHER('gcells', gcells)
    #
    # Now use this collected info to construct a mesh
    #
    try:
        scomm = fe.mpi_comm_self()
    except AttributeError:
        scomm = MPI.COMM_SELF
    mesh = Mesh(scomm)  # new mesh is sequential
    logGATHER('scomm', scomm)
    logGATHER('MPI.COMM_SELF', MPI.COMM_SELF)
    # if comm.rank == 0:
    if True:  # construct a mesh in all processes
        editor = MeshEditor()
        editor.open(mesh, str(cellShapes[dim - 1]), dim, dim)
        editor.init_vertices_global(len(gvcs), len(gvcs))
        editor.init_cells_global(len(gcells), len(gcells))
        for v, vc in enumerate(gvcs):
            editor.add_vertex_global(v, v, vc)
        for c, cell in enumerate(gcells):
            logGATHER('c, cell', c, cell)
            editor.add_cell(c, cell)
    mesh.order()
    logGATHER('mesh.mpi_comm()', mesh.mpi_comm())
    logGATHER('mesh.mpi_comm().size', mesh.mpi_comm().size)
    gather_mesh_cache[mesh] = mesh
    logGATHER('caching gathered mesh')
    return (mesh)
コード例 #25
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_greenland_3D_5H():
   global home
   return Mesh(home + '/greenland/greenland_3D_5H_mesh.xml')
コード例 #26
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_antarctica_3D_100H():
   global home
   return Mesh(home + '/antarctica/antarctica_3D_100H_mesh.xml')
コード例 #27
0
#from dolfin import Mesh
from fenics import Mesh
import os

if not os.path.isfile("mesh/Skewed2D.xml"):
    try:
        os.system("gmsh mesh/Skewed2D.geo -2 -o mesh/Skewed2D.msh")
        os.system("meshio-convert mesh/Skewed2D.msh mesh/Skewed2D.xml"
                  )  # seems like it does not work properly
        os.system("rm mesh/Skewed2D.msh")
    except RuntimeError:
        raise "Gmsh is required to run this demo"

# Create a mesh
mesh = Mesh("mesh/Skewed2D.xml")

# Specify boundary conditions
tol = 1e-8
L = 1.0


def inlet(x, on_bnd):
    return x[0] < tol and on_bnd


def outlet(x, on_bnd):
    return x[0] > L - tol and on_bnd


def walls(x, on_bnd):
コード例 #28
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_antarctica_coarse():
   global home
   return Mesh(home + '/antarctica/antarctica_50H_5l.xml')
コード例 #29
0
                    VectorFunctionSpace, MPI, mpi_comm_world
import sys
import numpy as np
import time as timer
from fenicstools import Probes

# Local import
from stress_tensor import *
from common import *
from weak_form import *

# Set output from FEniCS
set_log_active(False)

# Set ut problem
mesh = Mesh(
    path.join(rel_path, "mesh", "von_karman_street_FSI_structure_refine2.xml"))

# Function space
V = VectorFunctionSpace(mesh, "CG", 2)
VV = V * V

# Get the point [0.2,0.6] at the end of bar
for coord in mesh.coordinates():
    if coord[0] == 0.6 and (0.2 - DOLFIN_EPS <= coord[1] <= 0.2 + DOLFIN_EPS):
        #print coord
        break

BarLeftSide = AutoSubDomain(lambda x: "on_boundary" and \
                            (((x[0] - 0.2) * (x[0] - 0.2) +
                                (x[1] - 0.2) * (x[1] - 0.2) < 0.0505*0.0505 )
                                and x[1] >= 0.19 \
コード例 #30
0
ファイル: meshfactory.py プロジェクト: JacobDowns/cslvr
 def get_antarctica_2D_medium():
   global home
   return Mesh(home + '/antarctica/antarctica_2D_medium_mesh.xml')