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
    def __init__(self,
                 mesh: fe.Mesh,
                 density: fe.Expression,
                 constitutive_model: ConstitutiveModelBase,
                 bf: fe.Expression = fe.Expression('0', degree=0)):

        self._mesh = mesh
        self._density = density
        self._constitutive_model = constitutive_model
        self.bf = bf

        element_v = fe.VectorElement("P", mesh.ufl_cell(), 1)
        element_s = fe.FiniteElement("P", mesh.ufl_cell(), 1)
        mixed_element = fe.MixedElement([element_v, element_v, element_s])
        W = fe.FunctionSpace(mesh, mixed_element)

        # Unknowns, values at previous step and test functions
        w = fe.Function(W)
        self.u, self.v, self.p = fe.split(w)

        w0 = fe.Function(W)
        self.u0, self.v0, self.p0 = fe.split(w0)
        self.a0 = fe.Function(fe.FunctionSpace(mesh, element_v))

        self.ut, self.vt, self.pt = fe.TestFunctions(W)

        self.F = kin.def_grad(self.u)
        self.F0 = kin.def_grad(self.u0)
Пример #4
0
    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()
Пример #5
0
    def __init__(self,
                 mesh: fe.Mesh,
                 constitutive_model: ConstitutiveModelBase,
                 u_order=1,
                 p_order=0):

        # TODO a lot here...

        element_v = fe.VectorElement("P", mesh.ufl_cell(), u_order)
        element_s = fe.FiniteElement("DG", mesh.ufl_cell(), p_order)
        # mixed_element = fe.MixedElement([element_v, element_v, element_s])
        mixed_element = fe.MixedElement([element_v, element_s])

        self.W = fe.FunctionSpace(mesh, mixed_element)

        self.V, self.Q = self.W.split()

        self.w = fe.Function(self.W)
        self.u, self.p = fe.split(self.w)
        w0 = fe.Function(self.W)
        self.u0, self.p0 = fe.split(w0)
        self.ut, self.pt = fe.TestFunctions(self.W)

        self.F = kin.def_grad(self.u)
        self.F0 = kin.def_grad(self.u0)

        S_iso = constitutive_model.iso_stress(self.u)
        mod_p = constitutive_model.p(self.u)
        J = fe.det(self.F)
        F_inv = fe.inv(self.F)

        if mod_p is None:
            mod_p = J**2 - 1.
        else:
            mod_p -= self.p

        S = S_iso + J * self.p * F_inv * F_inv.T

        self.d_LHS = fe.inner(fe.grad(self.ut), self.F * S) * fe.dx \
                     + fe.inner(mod_p, self.pt) * fe.dx
        # + fe.inner(mod_p, fe.tr(fe.nabla_grad(self.ut)*fe.inv(self.F))) * fe.dx

        self.d_RHS = (fe.inner(fe.Constant((0., 0., 0.)), self.ut) * fe.dx)
Пример #6
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
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 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)
Пример #9
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
 def __init__(self, alpha_params: GeneralizedAlphaParameters,
              time_params: TimeSteppingParameters, fem_solver: FemSolver,
              boundary_excitation: ExternalExcitation,
              field_updates: FieldUpdates, fields: DDDbFields,
              mesh: fenics.Mesh, spaces: Spaces, dddb_file_name: str,
              initial_material_parameters: np.ndarray,
              in_checkpoint_file_name: str, out_checkpoint_file_name: str):
     super().__init__(alpha_params, time_params, fem_solver,
                      boundary_excitation, field_updates, fields)
     self.in_checkpoint_file = XDMFCheckpointHandler(
         file_name=in_checkpoint_file_name,
         append_to_existing=False,
         field=fields.imported_displacement_field,
         field_name=fields.u_new.name())
     self.out_checkpoint_file = XDMFCheckpointHandler(
         file_name=out_checkpoint_file_name,
         append_to_existing=False,
         field=fields.u_new,
         field_name=fields.u_new.name())
     self.v_out_checkpoint_file = XDMFCheckpointHandler(
         file_name='v_{}'.format(out_checkpoint_file_name),
         append_to_existing=False,
         field=fields.v_old,
         field_name=fields.v_old.name())
     self.a_out_checkpoint_file = XDMFCheckpointHandler(
         file_name='a_{}'.format(out_checkpoint_file_name),
         append_to_existing=False,
         field=fields.a_old,
         field_name=fields.a_old.name())
     self.np_files = NPYFile(file_name=dddb_file_name)
     self.tensor_space = spaces.tensor_space
     self.number_of_vertices = mesh.num_vertices()
     self.fields = fields
     initial_values_for_optimizer = np.random.random(
         self.fields.new_constitutive_relation_multiplicative_parameters.
         function_space().dim() - self.fields.function_space.dim())
     self.optimizer = ScipyOptimizer(
         fields=self.fields,
         initial_values=initial_values_for_optimizer,
         fem_solver=fem_solver,
         spaces=spaces)
Пример #11
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
Пример #12
0
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
Пример #13
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()))
Пример #14
0
 def get_circle():
   global home
   return Mesh(home + '/test/circle_mesh.xml.gz')
Пример #15
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):
Пример #16
0
 def get_ronne_3D_10H():
   global home
   return Mesh(home + '/antarctica/antarctica_ronne_shelf.xml')
Пример #17
0
 def get_antarctica_3D_gradS_crude():
   global home
   return Mesh(home + '/antarctica/antarctica_3D_gradS_mesh_crude.xml')
Пример #18
0
 def get_greenland_coarse():
   global home
   return Mesh(home + '/greenland/greenland_coarse_mesh.xml')
Пример #19
0
 def get_antarctica_3D_gradS_detailed():
   global home
   return Mesh(home + '/antarctica/antarctica_3D_gradS_mesh_detailed.xml')
Пример #20
0
 def get_greenland_detailed():
   global home
   return Mesh(home + '/greenland/greenland_detailed_mesh.xml')
Пример #21
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()
Пример #22
0
 def get_greenland_3D_5H():
   global home
   return Mesh(home + '/greenland/greenland_3D_5H_mesh.xml')
Пример #23
0
 def get_greenland_2D_5H_sealevel():
   global home
   return Mesh(home + '/greenland/greenland_2D_5H_sealevel.xml')
Пример #24
0
 def get_antarctica_3D_10k():
   global home
   return Mesh(home + '/antarctica/antarctica_3D_10k.xml')
Пример #25
0
 def get_antarctica_coarse():
   global home
   return Mesh(home + '/antarctica/antarctica_50H_5l.xml')
Пример #26
0
 def get_greenland_medium():
   global home
   return Mesh(home + '/greenland/greenland_medium_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
 def get_antarctica_2D_medium():
   global home
   return Mesh(home + '/antarctica/antarctica_2D_medium_mesh.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
 def get_antarctica_3D_100H():
   global home
   return Mesh(home + '/antarctica/antarctica_3D_100H_mesh.xml')