def generate_rectangle_mesh(mesh_resolution):
    # Generate domain and mesh
    xmin, xmax = -2, 2
    ymin, ymax = -2, 2
    mesh = generate_mesh(Rectangle(Point(xmin, ymin), Point(xmax, ymax)),
                         mesh_resolution)
    return mesh
Example #2
0
    def build_mesh(self, resolution=20):
        from mshr import Rectangle, Circle, generate_mesh

        domain = Rectangle(Point(0.0, 0.0), Point(self.L, self.L)) - Circle(
            Point(0.0, 0.0), self.radius
        )
        return generate_mesh(domain, resolution)
Example #3
0
def build_wave_breaker(start_loc, length, n_fins, l, d, rod_start, rod_stop):
    """
    Build the wave breaker

    Input:
        start_loc - starting location
        length - length of breaker
        n_fins - number of fins
        l - length of fin wing
        d - width of fin wing
        rod_start - starting position for support rod
        rot_stop - stopping position for support rod
    Output:
        breaker - domain of wave breaker
    """

    # build support rod
    rod_pt1 = Point(rod_start)
    rod_pt2 = Point(rod_stop)

    # get fins
    fins = fin_sequence(start_loc, length, n_fins, l, d)

    # assemble together
    domain = Rectangle(rod_pt1, rod_pt2)

    for fin in fins:
        # += may have odd behavior
        domain = domain + fin

    return domain
Example #4
0
def initialise(dem, bounds, res):
    """
    Function to initialise the model space

    :param dem: 0 = no input DEM; 1 = input DEM
    :param bounds: west, south, east, north - if no DEM [0, 0, lx, ly]; if DEM [west, south, east, north]
    :param res: model resolution along the y-axis.
    :return model_space, u_n, mesh, V, bc:
    """

    if dem == 0:
        lx = bounds[1]
        ly = bounds[3]

        # Create mesh and define function space
        domain = Rectangle(Point(0, 0), Point(lx / ly, ly / ly))
        mesh = generate_mesh(domain, res)

        V = FunctionSpace(mesh, 'P', 1)

        # Define initial value
        u_D = Constant(0)
        eps = 10 / ly
        u_n = interpolate(u_D, V)
        u_n.vector().set_local(u_n.vector().get_local() +
                               eps * np.random.random(u_n.vector().size()))

    if dem == 1:
        u_n, lx, ly, mesh, V = read_dem(bounds, res)

    # boundary conditions

    class East(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[0], lx / ly)

    class West(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[0], 0.0)

    class North(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[1], ly / ly)

    class South(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[1], 0.0)

    # Should make this into an option!

    bc = [DirichletBC(V, u_n, West()), DirichletBC(V, u_n, East())]

    # def boundary(x, on_boundary):
    #   return on_boundary
    # bc = DirichletBC(V, u_n, boundary)

    model_space = [lx, ly, res]

    return model_space, u_n, mesh, V, bc
Example #5
0
def get_space(resolution):
    # Create a fin geometry
    geometry = Rectangle(Point(2.5, 0.0), Point(3.5, 4.0)) \
            + Rectangle(Point(0.0, 0.75), Point(2.5, 1.0)) \
            + Rectangle(Point(0.0, 1.75), Point(2.5, 2.0)) \
            + Rectangle(Point(0.0, 2.75), Point(2.5, 3.0)) \
            + Rectangle(Point(0.0, 3.75), Point(2.5, 4.0)) \
            + Rectangle(Point(3.5, 0.75), Point(6.0, 1.0)) \
            + Rectangle(Point(3.5, 1.75), Point(6.0, 2.0)) \
            + Rectangle(Point(3.5, 2.75), Point(6.0, 3.0)) \
            + Rectangle(Point(3.5, 3.75), Point(6.0, 4.0)) \

    mesh = generate_mesh(geometry, resolution)

    V = FunctionSpace(mesh, 'CG', 1)
    return V
Example #6
0
def get_space(resolution):
    # Create the thermal fin geometry as referenced in Tan's thesis

    geometry = Rectangle(Point(2.5, 0.0), Point(3.5, 4.0)) \
            + Rectangle(Point(0.0, 0.75), Point(2.5, 1.0)) \
            + Rectangle(Point(0.0, 1.75), Point(2.5, 2.0)) \
            + Rectangle(Point(0.0, 2.75), Point(2.5, 3.0)) \
            + Rectangle(Point(0.0, 3.75), Point(2.5, 4.0)) \
            + Rectangle(Point(3.5, 0.75), Point(6.0, 1.0)) \
            + Rectangle(Point(3.5, 1.75), Point(6.0, 2.0)) \
            + Rectangle(Point(3.5, 2.75), Point(6.0, 3.0)) \
            + Rectangle(Point(3.5, 3.75), Point(6.0, 4.0)) \

    mesh = generate_mesh(geometry, resolution)

    V = FunctionSpace(mesh, 'CG', 1)
    return V
def setup_geometry():
    # Generate mesh
    xmin, xmax = -10.0, 10.0
    ymin, ymax = -0.5, 0.5
    geometry = Rectangle(Point(xmin, ymin), Point(xmax, ymax))
    mesh_resolution = 50
    mesh = generate_mesh(geometry, mesh_resolution)

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

    return mesh, boundary
Example #8
0
def read_dem(bounds, res):
    """
    Function to read in a DEM from SRTM amd interplolate it onto a dolphyn mesh. This function uses the python package
    'elevation' (http://elevation.bopen.eu/en/stable/) and the gdal libraries.

    I will assume you want the 30m resolution SRTM model.

    :param bounds: west, south, east, north coordinates
    :return u_n, lx, ly: the elevation interpolated onto the dolphyn mesh and the lengths of the domain
    """
    west, south, east, north = bounds

    # Create a temporary file to store the DEM and go get it using elevation
    dem_path = 'tmp.tif'
    output = os.getcwd() + '/' + dem_path
    elv.clip(bounds=bounds, output=output, product='SRTM1')

    # read in the DEM into a numpy array
    gdal_data = gdal.Open(output)
    data_array = gdal_data.ReadAsArray().astype(np.float)

    # The DEM is 30m per pixel, so lets make a array for x and y at 30 m
    ny, nx = np.shape(data_array)
    lx = nx * 30
    ly = ny * 30

    x, y = np.meshgrid(np.linspace(0, lx / ly, nx), np.linspace(0, 1, ny))

    # Create mesh and define function space
    domain = Rectangle(Point(0, 0), Point(lx / ly, 1))
    mesh = generate_mesh(domain, res)
    V = FunctionSpace(mesh, 'P', 1)
    u_n = Function(V)

    # Get the global coordinates
    gdim = mesh.geometry().dim()
    gc = V.tabulate_dof_coordinates().reshape((-1, gdim))

    # Interpolate elevation into the initial condition
    elevation = interpolate.griddata((x.flatten(), y.flatten()),
                                     data_array.flatten(),
                                     (gc[:, 0], gc[:, 1]),
                                     method='nearest')
    u_n.vector()[:] = elevation

    # remove tmp DEM
    os.remove(output)

    return u_n, lx, ly, mesh, V
Example #9
0
def generate2DIdealizedBrainMesh(config):
    from mshr import Circle, Rectangle, generate_mesh
    ids = {dom["name"]:dom["id"] for dom in  config["domains"]}
    N = 1/config["h"]
    N = config["N"] #
    brain_radius = config["brain_radius"] # 0.1
    sas_radius = config["sas_radius"] # brain_radius*1.2
    ventricle_radius =  config["ventricle_radius"] # 0.03
    aqueduct_width = config["aqueduct_width"] # 0.005
    canal_width =  config["canal_width"] # 0.02
    canal_length = config["canal_length"] # 0.2
    
    path = f"../meshes/ideal_brain_2D_N{N}/ideal_brain_2D_N{N}"
    os.popen(f'mkdir -p {path}') 

    brain = Circle(Point(0,0), brain_radius)
    ventricle = Circle(Point(0,0), ventricle_radius)
    aqueduct = Rectangle(Point(-aqueduct_width/2, -brain_radius), Point(aqueduct_width/2, 0))
    brain = brain - ventricle - aqueduct

    spinal_canal = Rectangle(Point(-canal_width/2, -canal_length), Point(canal_width/2, 0))
    fluid = Circle(Point(0,0), sas_radius) + spinal_canal
    domain = fluid + brain
    domain.set_subdomain(ids["csf"], fluid)
    domain.set_subdomain(ids["parenchyma"], brain)
    domain.set_subdomain(ids["aqueduct"], aqueduct)
    domain.set_subdomain(ids["ventricle"], ventricle)

    mesh = generate_mesh(domain, N)
    subdomains = MeshFunction("size_t", mesh, 2, mesh.domains())
    subdomains.rename("subdomains", "subdomains")

    subdomains_outfile = XDMFFile(path + "_labels.xdmf")
    subdomains_outfile.write(subdomains)
    subdomains_outfile.close()
    return path
Example #10
0
def test(n):
    domain = Rectangle(Point(0, 0), Point(2, 3))
    mesh = generate_mesh(domain, n)

    # Cell-cell connectivity will be defined over facet
    tdim = mesh.topology().dim()
    mesh.init(tdim, tdim - 1)
    mesh.init(tdim - 1, tdim)

    c2f = mesh.topology()(tdim, tdim - 1)
    f2c = mesh.topology()(tdim - 1, tdim)

    c2c = lambda c: set(np.hstack([f2c(f) for f in c2f(c)]))

    def cells_in_radius(c0, mesh, cell_connectivity, radius):
        x0 = c0.midpoint()
        c0 = c0.index()
        N = set([c0])  # cells in the patch
        C = cell_connectivity(c0)  # where to look elements of the patch
        C.remove(c0)

        while C:
            c = C.pop()
            x = Cell(mesh, c).midpoint()
            if x.distance(x0) < radius:
                N.add(c)
                new = cell_connectivity(c) - N
                C.update(new)
        return N

    f = CellFunction('size_t', mesh, 0)

    # c0 = Cell(mesh, choice(range(mesh.num_cells())))
    # for c in  cells_in_radius(c0, mesh, c2c, 0.4):
    #     f[int(c)] = 1
    # f[c0] = 2
    # plot(f, interactive=True)

    t = Timer('dt')
    c0 = choice(range(mesh.num_cells()))
    c0 = Cell(mesh, c0)
    t.start()
    print '\tPatch size', len(cells_in_radius(c0, mesh, c2c, 0.4))
    dt = t.stop()

    return mesh.num_cells(), dt
Example #11
0
 def __init__(self, w_sim, h_sim, w_wg, h_wg, res):
     # Create mesh with two domains, waveguide + cladding
     self.res = res
     domain = Rectangle(Point(-w_sim / 2, -h_sim / 2),
                        Point(w_sim / 2, h_sim / 2))
     domain.set_subdomain(
         1,
         Rectangle(Point(-w_sim / 2, -h_sim / 2),
                   Point(w_sim / 2, h_sim / 2)))
     domain.set_subdomain(
         2, Rectangle(Point(-w_wg / 2, -h_wg / 2),
                      Point(w_wg / 2, h_wg / 2)))
     self.mesh = generate_mesh(domain, self.res)
     self.mesh.init()
     # Initialize mesh function for interior domains
     self.waveguide = Waveguide(w_wg, h_wg)
     self.domains = MeshFunction("size_t", self.mesh, 2)
     self.domains.set_all(0)
     self.waveguide.mark(self.domains, 1)
     # Define new measures associated with the interior domains
     self.dx = Measure("dx")(subdomain_data=self.domains)
Example #12
0
import sys
sys.path.append('../')
import matplotlib.pyplot as plt
from dolfin import *
from mshr import Rectangle, generate_mesh
import numpy as np

from forward_solve import Fin

# Create a fin geometry
geometry = Rectangle(Point(2.5, 0.0), Point(3.5, 4.0)) \
        + Rectangle(Point(0.0, 0.75), Point(2.5, 1.0)) \
        + Rectangle(Point(0.0, 1.75), Point(2.5, 2.0)) \
        + Rectangle(Point(0.0, 2.75), Point(2.5, 3.0)) \
        + Rectangle(Point(0.0, 3.75), Point(2.5, 4.0)) \
        + Rectangle(Point(3.5, 0.75), Point(6.0, 1.0)) \
        + Rectangle(Point(3.5, 1.75), Point(6.0, 2.0)) \
        + Rectangle(Point(3.5, 2.75), Point(6.0, 3.0)) \
        + Rectangle(Point(3.5, 3.75), Point(6.0, 4.0)) \

mesh = generate_mesh(geometry, 40)
plot(mesh)
plt.show()

V = FunctionSpace(mesh, 'CG', 1)
dofs = len(V.dofmap().dofs())
print("DOFS: {}".format(dofs))

# Pick a more interesting conductivity to see what happens
#  m = Function(V)
Example #13
0
def setup(using_elbow=True, using_3D=False, compressible=False):
    from mshr import Box, Rectangle, generate_mesh
    zero_vel = Constant((0, 0))
    if using_elbow:
        x_min, x_max = 0 * length_scale, 2 * length_scale
        y_min, y_max = 0 * length_scale, 2 * length_scale
        x_mid, y_mid = 1 * length_scale, 1 * length_scale
        if using_3D:
            dim = 3
            z_min, z_max = 0 * length_scale, 1 * length_scale
            elbow = Box(Point(x_min, y_min, z_min), Point(
                x_mid, y_max, z_max)) + Box(Point(x_mid, y_mid, z_min),
                                            Point(x_max, y_max, z_max))
            mesh = generate_mesh(elbow, 20)
            front_back_boundary = AutoSubDomain(lambda x, on_boundary: on_boundary \
                                               and (near(x[2], z_min) or near(x[2], z_max)))
            zero_vel = Constant((0, 0, 0))
        else:
            dim = 2
            elbow = Rectangle(Point(x_min, y_min), Point(
                x_mid, y_max)) + Rectangle(Point(x_mid, y_mid),
                                           Point(x_max, y_max))
            mesh = generate_mesh(elbow, 20)

        static_boundary = AutoSubDomain(lambda x, on_boundary: on_boundary \
            and (near(x[0], x_min) or near(x[1], y_max) or near(x[0], x_mid) or near(x[1], y_mid)))
        bottom = AutoSubDomain(
            lambda x, on_boundary: on_boundary and near(x[1], y_min))
        outlet = AutoSubDomain(
            lambda x, on_boundary: on_boundary and near(x[0], x_max))
    else:
        #length_scale = 1
        mesh = UnitSquareMesh(40, 100)
        static_boundary = AutoSubDomain(lambda x, on_boundary: on_boundary and
                                        (near(x[0], 0) or near(x[0], 1)))

        bottom = AutoSubDomain(
            lambda x, on_boundary: on_boundary and near(x[1], 0))
        outlet = AutoSubDomain(
            lambda x, on_boundary: on_boundary and near(x[1], 1))
        #moving_boundary = AutoSubDomain(lambda x, on_boundary: on_boundary and near(x[1], 1) )
        #bcs_u["moving"] = {'boundary': top, 'boundary_id': 2, 'variable': "velocity", 'type': 'Dirichlet', 'value': Constant((1,0))}

    from collections import OrderedDict
    bcs_u = OrderedDict()

    bcs_u["static"] = {
        'boundary':
        static_boundary,
        'boundary_id':
        1,
        'values': [{
            'variable': "velocity",
            'type': 'Dirichlet',
            'value': zero_vel,
            'unit': 'm/s'
        }, {
            'variable': "temperature",
            'type': 'Dirichlet',
            'value': T_wall
        }]
    }
    if using_3D:
        bcs_u["front_back"] = {
            'boundary':
            front_back_boundary,
            'boundary_id':
            5,
            'values': [{
                'variable': "velocity",
                'type': 'Dirichlet',
                'value': zero_vel
            }, {
                'variable': "temperature",
                'type': 'Dirichlet',
                'value': T_wall
            }]
        }

    bcs_p = OrderedDict()
    bcs_p["outlet"] = {
        'boundary':
        outlet,
        'boundary_id':
        3,
        'values': [{
            'variable': "pressure",
            'type': 'Dirichlet',
            'value': p_outlet
        }, {
            'variable': "temperature",
            'type': 'Dirichlet',
            'value': T_ambient
        }]
    }

    #inlet_vel_expr = Expression('max_vel * (1.0 - pow(abs(x[0]-x_mid)/x_mid, 2))', max_vel=10, x_mid=0.5)
    x_c = 0.5 * length_scale
    if using_3D:
        _init_vel = (0, max_vel * 0.2, 0)

        class InletVelcotyExpression(Expression):
            def eval(self, value, x):
                value[0] = 0
                value[1] = max_vel * (1.0 - (abs(x[0] - x_c) / x_c)**2)
                value[2] = 0

            def value_shape(self):
                return (3, )
    else:
        _init_vel = (0, max_vel * 0.2)

        class InletVelcotyExpression(Expression):
            def eval(self, value, x):
                value[0] = 0
                value[1] = max_vel * (1.0 - (abs(x[0] - x_c) / x_c)**2)

            def value_shape(self):
                return (2, )

    bcs_u["inlet"] = {
        'boundary':
        bottom,
        'boundary_id':
        2,
        'values': [{
            'variable': "temperature",
            'type': 'Dirichlet',
            'value': T_ambient
        }]
    }
    if transient:
        vels = [
            Constant((0, max_vel)),
            InletVelcotyExpression(degree=1),
            InletVelcotyExpression(degree=1)
        ]
        bcs_u["inlet"]['values'].append({
            'variable': "velocity",
            'type': 'Dirichlet',
            'value': vels
        })
    else:
        vel = InletVelcotyExpression(
            degree=1)  # degree = 1, may not general enough, fixme
        #if compressible:
        #bcs_u["inlet"] ['values'].append({'variable': "pressure", 'type': 'Dirichlet', 'value': p_inlet})
        #else:
        bcs_u["inlet"]['values'].append({
            'variable': "velocity",
            'type': 'Dirichlet',
            'value': vel
        })

    bcs = bcs_p.copy()
    for k in bcs_u:
        bcs[k] = bcs_u[k]

    s = copy.copy(SolverBase.default_case_settings)
    '''
    dt = 0.001
    t_end = 0.005
    transient_settings = {'transient': True, 'starting_time': 0.0, 'time_step': dt, 'ending_time': t_end}
    s['solver_settings']['transient_settings'] = transient_settings
    '''

    s['mesh'] = mesh
    print(info(mesh))
    s['boundary_conditions'] = bcs
    s['initial_values'] = {
        'velocity': _init_vel,
        "temperature": T_ambient,
        "pressure": 1e5
    }
    s['solver_settings']['reference_values'] = {
        'velocity': (1, 1),
        "temperature": T_ambient,
        "pressure": 1e5
    }

    return s
Example #14
0
def setup_geometry(interior_circle=True, num_mesh_refinements=0):
    # Generate mesh
    xmin, xmax = 0.0, 4.0
    ymin, ymax = 0.0, 1.0
    mesh_resolution = 30
    geometry1 = Rectangle(Point(xmin, ymin), Point(xmax, ymax))
    center = Point(0.5, 0.5)
    r = 0.1
    side_length = 0.1
    if interior_circle:
        geometry2 = Circle(center, r)
    else:
        l2 = side_length / 2
        geometry2 = Rectangle(Point(center[0] - l2, center[1] - l2),
                              Point(center[0] + l2, center[1] + l2))
    mesh = generate_mesh(geometry1 - geometry2, mesh_resolution)

    # Refine mesh around the interior boundary
    for i in range(0, num_mesh_refinements):
        cell_markers = MeshFunction("bool", mesh, mesh.topology().dim())
        for c in cells(mesh):
            p = c.midpoint()
            cell_markers[c] = (abs(p[0] - .5) < .5 and abs(p[1] - .5) < .3
                               and c.diameter() > .1) or c.diameter() > .2
        mesh = refine(mesh, cell_markers)

    # Mark regions for boundary conditions
    eps = 1e-5
    # Part of the boundary with zero pressure
    om = Expression("x[0] > XMAX - eps ? 1. : 0.",
                    XMAX=xmax,
                    eps=eps,
                    degree=1)
    # Part of the boundary with prescribed velocity
    im = Expression("x[0] < XMIN + eps ? 1. : 0.",
                    XMIN=xmin,
                    eps=eps,
                    degree=1)
    # Part of the boundary with zero velocity
    nm = Expression("x[0] > XMIN + eps && x[0] < XMAX - eps ? 1. : 0.",
                    XMIN=xmin,
                    XMAX=xmax,
                    eps=eps,
                    degree=1)

    # Define interior boundary
    class InteriorBoundary(SubDomain):
        def inside(self, x, on_boundary):
            # Compute squared distance to interior object midpoint
            d2 = (x[0] - center[0])**2 + (x[1] - center[1])**2
            return on_boundary and d2 < (2 * r)**2

    # Create mesh function over the cell facets
    sub_domains = MeshFunction("size_t", mesh, mesh.topology().dim() - 1)
    # Mark all facets as sub domain 0
    sub_domains.set_all(0)
    # Mark interior boundary facets as sub domain 1
    interior_boundary = InteriorBoundary()
    interior_boundary.mark(sub_domains, 1)

    return mesh, om, im, nm, ymax, sub_domains
Example #15
0
 def unstructured_mesh_2d():
     domain = Rectangle(Point(0., 0.), Point(1., 1.))
     return generate_mesh(domain, 5)
Example #16
0
def setup_geometry(geometry, finesse):
    '''
  Setup different geometries.
  '''
    if geometry == 'centered_cylinders':
        tol = 0.02  # tolerance for boundary definition
        radii = [2.0, 0.5]

        class Outer_circle(SubDomain):
            def inside(self, x, on_boundary):
                r = math.sqrt(x[0] * x[0] + x[1] * x[1])
                return near(r, radii[0], tol)

        class Inner_circle(SubDomain):
            def inside(self, x, on_boundary):
                r = math.sqrt(x[0] * x[0] + x[1] * x[1])
                return near(r, radii[1], tol)

        outer_circle = Outer_circle()
        inner_circle = Inner_circle()

        circ_large = Circle(Point(0, 0), radii[0])
        circ_small = Circle(Point(0, 0), radii[1])
        domain = circ_large - circ_small
        mesh = generate_mesh(domain, finesse)

        boundaries = MeshFunction('size_t', mesh, mesh.topology().dim() - 1)
        boundaries.set_all(0)
        outer_circle.mark(boundaries, 1)
        inner_circle.mark(boundaries, 2)

        return mesh, boundaries

    elif geometry == 'centered_Lshape':
        tol = 0.02  # tolerance for boundary definition

        class Hor1(SubDomain):
            def inside(self, x, on_boundary):
                return near(x[1], 1)

        class Vert1(SubDomain):
            def inside(self, x, on_boundary):
                return near(x[0], 0.5) and x[1] >= 0.5

        class Hor2(SubDomain):
            def inside(self, x, on_boundary):
                return near(x[1], 0.5) and x[0] <= 0.5

        class Vert2(SubDomain):
            def inside(self, x, on_boundary):
                return near(x[0], 0)

        class Bottom(SubDomain):
            def inside(self, x, on_boundary):
                return near(x[1], 0)

        class Right(SubDomain):
            def inside(self, x, on_boundary):
                return near(x[0], 1)

        hor1 = Hor1()
        hor2 = Hor2()
        vert1 = Vert1()
        vert2 = Vert2()
        bottom = Bottom()
        right = Right()

        rectangle_large = Rectangle(Point(0, 0), Point(1, 1))
        rectangle_small = Rectangle(Point(0, 1), Point(0.5, 0.5))
        domain = rectangle_large - rectangle_small
        mesh = generate_mesh(domain, finesse)

        boundaries = MeshFunction('size_t', mesh, mesh.topology().dim() - 1)
        boundaries.set_all(0)
        hor1.mark(boundaries, 1)
        vert1.mark(boundaries, 1)
        hor2.mark(boundaries, 2)
        vert2.mark(boundaries, 2)
        bottom.mark(boundaries, 3)
        right.mark(boundaries, 4)

        return mesh, boundaries

    else:
        raise NotImplementedError