def verify_michalek2003_natural_convection_water(w, mesh):
    """Verify directly against steady-state data from michalek2003 published in 

        @article{michalek2003simulations,
          title={Simulations of the water freezing process--numerical benchmarks},
          author={MICHA{\L}EK, TOMASZ and KOWALEWSKI, TOMASZ A},
          journal={Task Quarterly},
          volume={7},
          number={3},
          pages={389--408},
          year={2003}
        }
    """
    verified_solution = {
        'y': 0.5,
        'x': [0.00, 0.05, 0.12, 0.23, 0.40, 0.59, 0.80, 0.88, 1.00],
        'theta': [1.00, 0.66, 0.56, 0.58, 0.59, 0.62, 0.20, 0.22, 0.00]
    }

    bbt = mesh.bounding_box_tree()

    for i, true_theta in enumerate(verified_solution['theta']):

        p = fenics.Point(
            fenics.Point(verified_solution['x'][i], verified_solution['y']))

        if bbt.collides_entity(p):

            wval = w(p)

            theta = wval[3]

            assert (abs(theta - true_theta) < 2.e-2)
Example #2
0
def problem(f, nx=8, ny=8, degrees=[1, 2]):
    """
    Plot u along x=const or y=const for Lagrange elements,
    of given degrees, on a nx times ny mesh. f is a SymPy expression.
    """
    f = sym.printing.ccode(f)
    f = fe.Expression(f, degree=2)
    mesh = fe.RectangleMesh(fe.Point(-1, 0), fe.Point(1, 2), 2, 2)
    for degree in degrees:
        if degree == 0:
            # The P0 element is specified like this in FEniCS
            V = fe.FunctionSpace(mesh, 'DG', 0)
        else:
            # The Lagrange Pd family of elements, d=1,2,3,...
            V = fe.FunctionSpace(mesh, 'P', degree)
        u = fe.project(f, V)
        u_error = fe.errornorm(f, u, 'L2')
        print('||u-f||=%g' % u_error, degree)
        comparison_plot2D(u,
                          f,
                          n=50,
                          value=0.4,
                          variation='x',
                          plottitle='Approximation by P%d elements' % degree,
                          filename='approx_fenics_by_P%d' % degree,
                          tol=1E-3)
Example #3
0
    def build_mesh(self):
        length = 60
        height = 30
        radius = 5
        plate = mshr.Rectangle(fe.Point(0, 0), fe.Point(length, height))
        circle1 = mshr.Circle(fe.Point(length/3, height/3), radius)
        circle2 = mshr.Circle(fe.Point(length*2/3, height*2/3), radius)
        material_domain = plate - circle1 - circle2
        self.mesh = mshr.generate_mesh(material_domain, 50)

        # Add dolfin-adjoint dependency
        self.mesh  = create_overloaded_object(self.mesh)

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

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

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

        self.left = Left()
        self.right = Right()
        self.corner = Corner()
Example #4
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')
Example #5
0
 def verify(self):
     """ Test regression based on a previous solution from Phaseflow.
     
     In Paraview, the $T = 0.01$ (i.e. the regularization_central_temperature) contour was drawn
     at time $t = 30.$ (i.e. the end_time).
     
     A point from this contour in the upper portion of the domain, 
     where the PCI has advanced more quickly, was recorded to be (0.278, 0.875).
     This was checked for commit a8a8a039e5b89d71b6cceaef519dfbf136322639.
     
     Here we verify that the temperature is above the melting temperature left of the expected PCI,
     which is advancing to the right, and is below the melting temperature right of the expected PCI.
     """
     pci_y_position_to_check =  0.88
     
     reference_pci_x_position = 0.28
     
     position_offset = 0.01
     
     left_temperature = self.state.solution.leaf_node()(
         fenics.Point(reference_pci_x_position - position_offset, pci_y_position_to_check))[3]
     
     right_temperature = self.state.solution.leaf_node()(
         fenics.Point(reference_pci_x_position + position_offset, pci_y_position_to_check))[3]
     
     assert((left_temperature > self.regularization_central_temperature) 
         and (self.regularization_central_temperature > right_temperature))
Example #6
0
 def square(self, length, origin=None):
     if origin is None:
         x, y = 0, 0
     else:
         x, y = origin[0], origin[1]
     return mshr.Rectangle(FEN.Point(0 + x, 0 + y),
                           FEN.Point(length + x, length + y))
Example #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)
Example #8
0
    def build_mesh(self):
        self.length = 100
        self.height = 100

        plate = mshr.Rectangle(fe.Point(0, 0),
                               fe.Point(self.length, self.height))
        notch = mshr.Polygon([
            fe.Point(0, self.height / 2 + 1),
            fe.Point(0, self.height / 2 - 1),
            fe.Point(6, self.height / 2)
        ])
        self.mesh = mshr.generate_mesh(plate - notch, 30)

        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)

        self.lower = Lower()
        self.upper = Upper()
        self.corner = Corner()
Example #9
0
 def _build_mesh(self):
     args = self.args
     self.width = 0.5
     # mesh = fa.Mesh(args.root_path + '/' + args.solutions_path + '/saved_mesh/mesh_robot.xml')
     mesh = fa.RectangleMesh(fa.Point(0, 0), fa.Point(
         self.width, 10), 2, 20, 'crossed')
     self.mesh = mesh
Example #10
0
def calc_system_variables(*, coords, advect_params, flags, pert_params):
    dx = (coords.we[1] - coords.we[0]) * 1000
    dy = (coords.sn[1] - coords.sn[0]) * 1000  # dx, dy in m not km
    max_horizon = pd.Timedelta(advect_params['max_horizon'])
    ci_crop_shape = np.array([coords.sn_crop.size, coords.we_crop.size],
                             dtype='int')
    U_crop_shape = np.array([coords.sn_crop.size, coords.we_stag_crop.size],
                            dtype='int')
    V_crop_shape = np.array([coords.sn_stag_crop.size, coords.we_crop.size],
                            dtype='int')
    U_crop_size = U_crop_shape[0] * U_crop_shape[1]
    V_crop_size = V_crop_shape[0] * V_crop_shape[1]
    wind_size = U_crop_size + V_crop_size
    num_of_horizons = int((max_horizon / 15).seconds / 60)
    sys_vars = {
        'dx': dx,
        'dy': dy,
        'num_of_horizons': num_of_horizons,
        'max_horizon': max_horizon,
        'ci_crop_shape': ci_crop_shape,
        'U_crop_shape': U_crop_shape,
        'V_crop_shape': V_crop_shape,
        'U_crop_size': U_crop_size,
        'V_crop_size': V_crop_size,
        'wind_size': wind_size
    }
    if flags['div']:
        mesh = fe.RectangleMesh(
            fe.Point(0, 0),
            fe.Point(int(V_crop_shape[1] - 1), int(U_crop_shape[0] - 1)),
            int(V_crop_shape[1] - 1), int(U_crop_shape[0] - 1))
        FunctionSpace_wind = fe.FunctionSpace(mesh, 'P', 1)
        sys_vars['FunctionSpace_wind'] = FunctionSpace_wind
    if flags['perturbation']:
        rf_eig, rf_vectors = eig_2d_covariance(x=coords.we_crop,
                                               y=coords.sn_crop,
                                               Lx=pert_params['Lx'],
                                               Ly=pert_params['Ly'],
                                               tol=pert_params['tol'])
        rf_approx_var = (rf_vectors * rf_eig[None, :] *
                         rf_vectors).sum(-1).mean()
        sys_vars['rf_eig'] = rf_eig
        sys_vars['rf_vectors'] = rf_vectors
        sys_vars['rf_approx_var'] = rf_approx_var
    if flags['perturb_winds']:
        rf_eig, rf_vectors = eig_2d_covariance(coords.we_crop,
                                               coords.sn_crop,
                                               Lx=pert_params['Lx_wind'],
                                               Ly=pert_params['Ly_wind'],
                                               tol=pert_params['tol_wind'])
        rf_approx_var = (rf_vectors * rf_eig[None, :] *
                         rf_vectors).sum(-1).mean()
        rf_eig = rf_eig * pert_params['Lx_wind']**2
        sys_vars['rf_eig_wind'] = rf_eig
        sys_vars['rf_vectors_wind'] = rf_vectors
        sys_vars['rf_approx_var_wind'] = rf_approx_var
    sys_vars = dict2nt(sys_vars, 'sys_vars')
    return sys_vars
Example #11
0
    def build_mesh(self):
        self.length = 8.
        self.height = 2.
        self.notch_length = 0.2
        self.notch_height = 0.4

        domain = mshr.Polygon([fe.Point(0., 0.), 
                  fe.Point(self.length/2. - self.notch_length/2., 0.),
                  fe.Point(self.length/2., self.notch_height),
                  fe.Point(self.length/2. + self.notch_length/2., 0.),
                  fe.Point(self.length, 0.),
                  fe.Point(self.length, self.height),
                  fe.Point(self.length/2. + self.notch_length/2., self.height),
                  fe.Point(self.length/2., self.height),
                  fe.Point(self.length/2. - self.notch_length/2., self.height),
                  fe.Point(0., self.height)])

        # resolution = 100 if self.local_refinement_iteration == 0 else 200
        # self.mesh = mshr.generate_mesh(domain, resolution)

        self.mesh = mshr.generate_mesh(domain, 100)
        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] > 14./32.*self.length and p[0] < 18./32.*self.length and p[1] < self.height - self.notch_height:
                    cell_markers[cell] = True
            self.mesh = fe.refine(self.mesh, cell_markers)

        length = self.length
        height = self.height
        notch_length = self.notch_length

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


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

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

        class MiddlePoint(fe.SubDomain):
            def inside(self, x, on_boundary):                    
                # return fe.near(x[0], length/2.) and fe.near(x[1], height)
                return x[0] > length/2. - notch_length/2.  and  x[0] < length/2. + notch_length/2. and fe.near(x[1], height)

        self.upper = Upper()
        self.left = LeftCorner()
        self.right = RightCorner()
        self.middle = MiddlePoint()
Example #12
0
def mfem():
    files = glob.glob('data/pvd/mfem/*')
    for f in files:
        try:
            os.remove(f)
        except Exception as e:
            print('Failed to delete {}, reason: {}' % (f, e))

    plate = mshr.Rectangle(fe.Point(0, 0), fe.Point(100, 100))
    mesh = mshr.generate_mesh(plate, 50)
    # mesh = fe.RectangleMesh(fe.Point(-2, -2), fe.Point(2, 2), 50, 50)

    x_hat = fe.SpatialCoordinate(mesh)

    U = fe.VectorFunctionSpace(mesh, 'CG', 2)
    V = fe.FunctionSpace(mesh, "CG", 1)
    W = fe.FunctionSpace(mesh, "DG", 0)

    # n = 21
    # control_points = np.stack((np.linspace(0, 1, n), np.linspace(0, 1, n)), axis=1)
    # impact_radii = np.linspace(0., 0.5, n)

    rho_default = 25. / np.sqrt(5) * 2
    control_points = np.array([[50., 50.], [62.5, 25.]])
    impact_radii = np.array([rho_default, rho_default])

    mid_point = np.array([75., 0.])
    mid_point1 = np.array([100., 0.])
    mid_point2 = np.array([50., 0.])
    points = [mid_point, mid_point1, mid_point2]
    direct_vec = np.array([1., -2])
    rotated_vec = np.array([2., 1.])

    direct_vec /= np.linalg.norm(direct_vec)
    rotated_vec /= np.linalg.norm(rotated_vec)

    directions = [direct_vec, rotated_vec]
    boundary_info = [points, directions, rho_default]

    # df, xi = distance_function_segments_ufl(x_hat, control_points, impact_radii)
    # d = fe.project(df, V)

    delta_x = map_function_ufl(x_hat, control_points, impact_radii,
                               boundary_info) - x_hat
    u = fe.project(delta_x, U)

    # e = fe.Function(U)
    # int_exp = InterpolateExpression(u, control_points, impact_radii)
    # e = fe.interpolate(int_exp, U)
    # int_exp = InterpolateExpression(e, control_points, impact_radii)
    # e = fe.project(int_exp, U)

    vtkfile_u = fe.File('data/pvd/mfem/u.pvd')
    u.rename("u", "u")
    vtkfile_u << u
Example #13
0
def make_mesh(num_cells: int) -> fenics.Mesh:
    """Generate mesh for FEM solver.

    """
    mesh = fenics.RectangleMesh(fenics.Point(0, 0),
                                fenics.Point(2 * np.pi, np.pi), num_cells,
                                num_cells)
    pbcs = lbe.periodic_boundary_conditions([0, 0], [2 * np.pi, np.pi],
                                            [True, False])

    return mesh, pbcs
Example #14
0
    def __init__(self, left, bottom, right, top, mesh_pts=0):
        self.left = left
        self.bottom = bottom
        self.right = right
        self.top = top
        self.seg_coords = (left, bottom, right, top)
        self.mesh_pts = mesh_pts

        self.rect = Rect(fe.Point(left, bottom), fe.Point(right, top))
        if self.mesh_pts > 0:
            self.mesh = generate_mesh(self.rect, self.mesh_pts)
Example #15
0
    def solve_point_source(me, point, point_type='ind', atol=0.0, rtol=1e-10, maxiter=100, verbose=False):
        me.b.zero()
        if point_type == 'coords':
            point_fenics = fenics.Point(point)
        elif point_type == 'ind':
            point_fenics = fenics.Point(me.dof_coords[point, :])
        elif point_type == 'fenics':
            point_fenics = point
        else:
            raise RuntimeError('invalid point_type')
        ps = fenics.PointSource(me.V, point_fenics, 1.0)
        ps.apply(me.b)

        return me.solve(me.b, atol=atol, rtol=rtol, maxiter=maxiter, verbose=verbose)
Example #16
0
    def _create_e_domain(self):
        box = Rect(fe.Point(0, 0), fe.Point(BOX_SIZE, BOX_SIZE))

        left, bottom, right, top = self.active_seg_coords
        # self.active_seg = Segment(0.3, 0.3, 0.7, 0.35)
        self.active_seg = Segment(left, bottom, right, top, mesh_pts=0)

        left, bottom, right, top = self.passive_seg_coords
        # self.passive_seg = Segment(0.3, 0.5, 0.7, 0.55)
        self.passive_seg = Segment(left, bottom, right, top)

        self.domain = box - self.active_seg.rect - self.passive_seg.rect

        return self.domain
Example #17
0
    def xest_second_tutorial(self):
        T = 2.0  # final time
        num_steps = 50  # number of time steps
        dt = T / num_steps  # time step size
        # Create mesh and define function space
        nx = ny = 30
        mesh = fenics.RectangleMesh(fenics.Point(-2, -2), fenics.Point(2, 2),
                                    nx, ny)
        V = fenics.FunctionSpace(mesh, 'P', 1)

        # Define boundary condition
        def boundary(x, on_boundary):
            return on_boundary

        bc = fenics.DirichletBC(V, fenics.Constant(0), boundary)
        # Define initial value
        u_0 = fenics.Expression('exp(-a*pow(x[0], 2) - a*pow(x[1], 2))',
                                degree=2,
                                a=5)
        u_n = fenics.interpolate(u_0, V)
        # Define variational problem
        u = fenics.TrialFunction(V)
        v = fenics.TestFunction(V)
        f = fenics.Constant(0)
        F = u * v * fenics.dx + dt * fenics.dot(fenics.grad(u), fenics.grad(
            v)) * fenics.dx - (u_n + dt * f) * v * fenics.dx
        a, L = fenics.lhs(F), fenics.rhs(F)
        # Create VTK file for saving solution
        vtkfile = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output', 'heat_gaussian',
                         'solution.pvd'))
        # Time-stepping
        u = fenics.Function(V)
        t = 0
        not_initialised = True
        for n in range(num_steps):
            # Update current time
            t += dt
            # Compute solution
            fenics.solve(a == L, u, bc)
            # Save to file and plot solution
            vtkfile << (u, t)
            # Here we'll need to call tripcolor ourselves to get access to the color range
            fenics.plot(u)
            animation_camera.snap()
            u_n.assign(u)
        animation = animation_camera.animate()
        animation.save(
            os.path.join(os.path.dirname(__file__), 'output',
                         'heat_gaussian.mp4'))
    def setup_coarse_mesh(self):
        """ This creates the rectangular mesh, or rectangular prism in 3D. """
        if len(self.mesh_size) == 2:

            self.mesh = fenics.RectangleMesh(
                fenics.mpi_comm_world(), fenics.Point(self.xmin, self.ymin),
                fenics.Point(self.xmax, self.ymax), self.mesh_size[0],
                self.mesh_size[1], "crossed")

        elif len(self.mesh_size) == 3:

            self.mesh = fenics.BoxMesh(
                fenics.mpi_comm_world(),
                fenics.Point(self.xmin, self.ymin, self.zmin),
                fenics.Point(self.xmax, self.ymax, self.zmax),
                self.mesh_size[0], self.mesh_size[1], self.mesh_size[2])
Example #19
0
def get_mesh(length, nx, ny, nz=None):
    """获得 mesh

    """
    if nz is None:
        mesh = fs.RectangleMesh(fs.Point(0.0, 0.0), fs.Point(length, length),
                                nx, ny)
    else:
        mesh = fs.BoxMesh(
            fs.Point(0.0, 0.0, 0.0),
            fs.Point(length, length, length),
            nx,
            ny,
            nz,
        )
    return mesh
Example #20
0
    def __init__(self, left, bottom, right, top):
        self.left = left
        self.bottom = bottom
        self.right = right
        self.top = top
        self.seg_coords = (left, bottom, right, top)

        self.rect = Rect(fe.Point(left, bottom), fe.Point(right, top))

        def is_near(self, pt):
            x, y = x
            if (fe.near(y, self.bottom) or fe.near(y, self.top)) \
               and (x > self.left and x < self.right):
                return True
            else:
                return False
Example #21
0
    def create_coronal_section_mesh(self, model_z_n=0):

        brain_slice = self.image_manipulation_obj.\
                get_brain_slice_from_model_z_n(model_z_n)

        x_size = 65
        self.boundary_points = brain_slice.\
                generate_boundary_points_ccw(x_size)
        domain_vertices = []

        for x, y in zip(self.boundary_points[0], self.boundary_points[1]):
            domain_vertices.append(fe.Point(x, y))

        self.geometry = mesher.Polygon(domain_vertices)
        self.mesh = mesher.generate_mesh(self.geometry, 16)

        self.compute_mesh_volume()
        self.original_volume = self.mesh_volume
        print('Original volume', self.original_volume)
        self.generate_holes()
        #self.compute_hole_fractional_volume()
        self.puncture_mesh()
        self.compute_mesh_volume()
        domain_volume = self.mesh_volume
        print('New volume', domain_volume)
        self.hole_fractional_volume = 1 - domain_volume / self.original_volume
        print('Hole fractional volume:', self.hole_fractional_volume)
        print('# holes:', self.n_holes)
        print('Estimated hole fractional volume:',\
                self.compute_hole_fractional_volume())
def verify_against_ghia1982(w, mesh):

    data = {
        'Re':
        100,
        'x':
        0.5,
        'y': [
            1.0000, 0.9766, 0.9688, 0.9609, 0.9531, 0.8516, 0.7344, 0.6172,
            0.5000, 0.4531, 0.2813, 0.1719, 0.1016, 0.0703, 0.0625, 0.0547,
            0.0000
        ],
        'ux': [
            1.0000, 0.8412, 0.7887, 0.7372, 0.6872, 0.2315, 0.0033, -0.1364,
            -0.2058, -0.2109, -0.1566, -0.1015, -0.0643, -0.0478, -0.0419,
            -0.0372, 0.0000
        ]
    }

    bbt = mesh.bounding_box_tree()

    for i, true_ux in enumerate(data['ux']):

        p = fenics.Point(data['x'], data['y'][i])

        if bbt.collides_entity(p):

            wval = w(p)

            ux = wval[0]

            assert (abs(ux - true_ux) < 2.e-2)
Example #23
0
 def eval(self, values, x_hat):
     x = inverse_map_function_normal(
         map_function_normal(x_hat, self.control_points, self.impact_radii),
         self.control_points, self.impact_radii)
     point = fe.Point(x)
     # values[0] = self.e(point)
     # delta_x_hat = x - x_hat
     values = x - x_hat
Example #24
0
    def build_mesh(self):
        self.length = 100
        self.height = 100

        plate = mshr.Rectangle(fe.Point(0, 0),
                               fe.Point(self.length, self.height))
        notch = mshr.Polygon([
            fe.Point(0, self.height / 2 + 1),
            fe.Point(0, self.height / 2 - 1),
            fe.Point(6, self.height / 2)
        ])
        notch = mshr.Polygon([
            fe.Point(0, self.height / 2 + 1e-10),
            fe.Point(0, self.height / 2 - 1e-10),
            fe.Point(self.length / 2, self.height / 2)
        ])
        # notch = mshr.Polygon([fe.Point(self.length / 4, self.height / 2), fe.Point(self.length / 2, self.height / 2 - 1e-10), \
        #                       fe.Point(self.length * 3 / 4, self.height / 2), fe.Point(self.length / 2, self.height / 2 + 1e-10)])
        self.mesh = mshr.generate_mesh(plate - notch, 50)

        # self.mesh = da.RectangleMesh(fe.Point(0, 0), fe.Point(self.length, self.height), 40, 40, diagonal="crossed")

        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 Left(fe.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and fe.near(x[0], 0)

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

        class Notch(fe.SubDomain):
            def inside(self, x, on_boundary):
                return fe.near(x[1], height / 2) and x[0] < length / 20

        self.lower = Lower()
        self.upper = Upper()
        self.corner = Corner()

        self.left = Left()
        self.right = Right()
        self.notch = Notch()
Example #25
0
    def puncture_mesh(self):

        for p in self.hole_coordinates:
            circle = mesher.Circle(fe.Point(p), self.hole_radius)
            self.geometry -= circle

        self.mesh = mesher.generate_mesh(self.geometry, self.mesh_density)
        print('Done with the mesh generation')
Example #26
0
    def __init__(self):
        self.h = .4

        # Cell properties
        self.obs_length = 0.9
        self.obs_height = 0.001
        self.obs_ratio = self.obs_height / self.obs_length

        if self.h < self.eta:
            raise ValueError("Eta must be smaller than h")
        self.ref_T = 0.1

        self.eps = 2 * self.eta / MembraneSimulator.length
        self.mesh = fe.RectangleMesh(
            fe.Point(-1, 0),
            fe.Point(1, 2 * self.h / MembraneSimulator.length), 50, 50)
        self.cell_mesh = None
        self.D = np.matrix(((4 * self.ref_T * MembraneSimulator.d1 /
                             MembraneSimulator.length**2, -0.05),
                            (+0.05, 4 * self.ref_T * MembraneSimulator.d2 /
                             MembraneSimulator.length**2)))
        # Dirichlet boundary conditions
        self.u_l = 6E-5
        self.u_r = 0
        self.u_boundary = fe.Expression(
            '(u_l*(x[0] < - par) + u_r*(x[0] >= par))',
            u_l=self.u_l,
            u_r=self.u_r,
            par=MembraneSimulator.w / MembraneSimulator.length,
            degree=2)
        self.u_0 = self.u_boundary / 2

        # self.rhs = fe.Expression('(x[1]>par)*u',u=self.u_l*4,par=MembraneSimulator.eta/MembraneSimulator.length, degree=2)
        self.rhs = fe.Constant(0)
        self.time = 0
        self.T = 1
        self.dt = 0.01
        self.tol = 1E-4

        self.function_space = fe.FunctionSpace(self.mesh, 'P', 2)
        self.solution = fe.Function(self.function_space)
        self.cell_solutions = self.cell_fs = None
        self.unit_vectors = [fe.Constant((1., 0.)), fe.Constant((0., 1.))]
        self.eff_diff = np.zeros((2, 2))
        self.file = fe.File('results/solution.pvd')
Example #27
0
 def __init__(self, d, h, ell=1., degree=1, nu=0.3, E=1.0):
     self.d = d
     self.ell = ell
     self.degree = degree
     mesh = fenics.RectangleMesh(fenics.Point(0., -0.5 * d),
                                 fenics.Point(ell, 0.5 * d), int(ell / h),
                                 int(d / h))
     self.left = dolfin.CompiledSubDomain('on_boundary && x[0] <= atol',
                                          atol=1e-5 * h)
     self.right = dolfin.CompiledSubDomain(
         'on_boundary && x[0] >= ell-atol', ell=ell, atol=1e-5 * h)
     element = dolfin.VectorElement('P',
                                    cell=mesh.ufl_cell(),
                                    degree=degree,
                                    dim=DIM)
     self.V = dolfin.FunctionSpace(mesh, element)
     self.lambda_ = dolfin.Constant(E * nu / (1. + nu) / (1. - 2. * nu))
     self.mu = dolfin.Constant(E / 2. / (1. + nu))
    def __call__(me, f_vec, points_pp):
        me.f.vector()[:] = f_vec.copy()
        if len(points_pp.shape) == 1:
            N = 1
        else:  # len(points_pp.shape) == 2
            N, _ = points_pp.shape
        points_pp = points_pp.reshape((N, me.d))

        inds_of_points_in_mesh = []
        for k in range(N):
            pk = fenics.Point(points_pp[k, :])
            if me.bbt.compute_collisions(pk):
                inds_of_points_in_mesh.append(k)

        ff = np.zeros(N)
        for k in inds_of_points_in_mesh:
            pk = fenics.Point(points_pp[k, :])
            ff[k] = me.f(pk)
        return ff
Example #29
0
    def build_mesh(self):
        self.length = 1.
        self.height = 1.

        plate = mshr.Rectangle(fe.Point(0, 0),
                               fe.Point(self.length, self.height))
        notch = mshr.Polygon([
            fe.Point(0, self.height / 2 + 1e-10),
            fe.Point(0, self.height / 2 - 1e-10),
            fe.Point(self.length / 2, self.height / 2)
        ])

        resolution = 50 * np.power(2, self.local_refinement_iteration)
        self.mesh = mshr.generate_mesh(plate - notch, resolution)

        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 Left(fe.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and fe.near(x[0], 0)

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

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

        self.lower = Lower()
        self.upper = Upper()
        self.corner = Corner()
        self.left = Left()
        self.right = Right()
Example #30
0
 def getNoReflectionBC(self):
     (AR0, QR0) = self.getBoundaryAQ("right")
     c = self.getWavespeed(AR0)
     (lamR0, tmp) = self.getEigenvalues(AR0, QR0)
     xW1R = fe.Point(self.L - lamR0 * self.dt, 0, 0)
     (AR, QR) = self.U0.split()
     AR = AR(xW1R)
     QR = QR(xW1R)
     (W1R, tmp) = self.getCharacteristics(AR, QR)
     (ARBC, QRBC) = self.getAQfromChar(W1R, self.W2_initial)
     return (ARBC, QRBC)