Exemplo n.º 1
0
def test_export_xdmf():
    mesh = fenics.UnitSquareMesh(3, 3)
    V = fenics.FunctionSpace(mesh, 'P', 1)
    folder = "Solution"
    exports = {
        "xdmf": {
            "functions": ['solute', 'retention'],
            "labels":  ['a', 'b'],
            "folder": folder
        }
        }
    files = [fenics.XDMFFile(folder + "/" + "a.xdmf"),
             fenics.XDMFFile(folder + "/" + "b.xdmf")]
    assert FESTIM.export_xdmf(
        [fenics.Function(V), fenics.Function(V)],
        exports, files, 20) is None

    exports["xdmf"]["functions"] = ['solute', 'blabla']

    with pytest.raises(KeyError, match=r'blabla'):
        FESTIM.export_xdmf(
            [fenics.Function(V), fenics.Function(V)],
            exports, files, 20)

    exports["xdmf"]["functions"] = ['solute', '13']
    with pytest.raises(KeyError, match=r'13'):
        FESTIM.export_xdmf(
            [fenics.Function(V), fenics.Function(V)],
            exports, files, 20)
Exemplo n.º 2
0
def construct_mesh_and_observation_coordinates(mesh_type, mesh_resolution,
                                               obs_resolution):
    if mesh_type == "square":
        mesh = fenics.UnitSquareMesh(mesh_resolution, mesh_resolution)
        observation_coordinates = np.stack(
            np.meshgrid(
                np.linspace(0, 1, 2 * obs_resolution + 1)[1:-1:2],
                np.linspace(0, 1, 2 * obs_resolution + 1)[1:-1:2],
            ),
            -1,
        ).reshape((-1, 2))
    elif mesh_type == "circle":
        mesh = fenics.UnitDiscMesh.create(fenics.MPI.comm_world,
                                          mesh_resolution, 1, 2)
        observation_coordinates = []
        for i, radius in enumerate(np.linspace(0, 1, obs_resolution, False)):
            angles = np.linspace(0, 2 * np.pi, max(1, i * obs_resolution),
                                 False)
            observation_coordinates.append(
                np.stack([np.sin(angles) * radius,
                          np.cos(angles) * radius], -1))
        observation_coordinates = np.concatenate(observation_coordinates, 0)
    else:
        raise ValueError(f"Unknown mesh type {mesh_type}")
    return mesh, observation_coordinates
Exemplo n.º 3
0
    def create_simple_mesh(self):

        #domain      = mesher.Circle(fe.Point(0,0), 1)
        #mesh        = mesher.generate_mesh(domain, 64)
        '''
        domain_vertices = [\
                fe.Point(0.0, 0.0),\
                fe.Point(10.0, 0.0),\
                fe.Point(10.0, 2.0),\
                fe.Point(8.0, 2.0),\
                fe.Point(7.5, 1.0),\
                fe.Point(2.5, 1.0),\
                fe.Point(2.0, 4.0),\
                fe.Point(0.0, 4.0),\
                fe.Point(0.0, 0.0)]

        geo = mesher.Polygon(domain_vertices)
        self.mesh   = mesher.generate_mesh(geo, 64);
        '''
        print('Creating simple mesh')
        nx = ny = 8

        if self.dimension == 1:
            self.mesh = fe.UnitIntervalMesh(nx)
            #self.mesh = fe.IntervalMesh(nx,-4, 4)

        if self.dimension == 2:
            self.mesh = fe.UnitSquareMesh(nx, ny)
        '''
Exemplo n.º 4
0
    def __init__(self, K):
        # Variables
        x, y = sym.symbols('x[0], x[1]', real=True, positive=True)
        f = sym.Function('f')(x, y)

        grid = np.linspace(0, 1, K + 2)[1:-1]
        x_obs, y_obs = np.meshgrid(grid, grid)
        self.x_obs, self.y_obs = x_obs.reshape(K * K), y_obs.reshape(K * K)

        # --- THIS PART USED TO NOT BE PARALELLIZABLE --- #
        # Create mesh and define function space
        n_mesh = 80
        self.mesh = fen.UnitSquareMesh(n_mesh, n_mesh)
        self.f_space = fen.FunctionSpace(self.mesh, 'P', 2)

        # Define boundary condition
        # u_boundary = fen.Expression('x[0] + x[1]', degree=2)
        u_boundary = fen.Expression('0', degree=2)
        self.bound_cond = fen.DirichletBC(self.f_space, u_boundary,
                                          lambda x, on_boundary: on_boundary)

        # Define variational problem
        self.trial_f = fen.TrialFunction(self.f_space)
        self.test_f = fen.TestFunction(self.f_space)
        rhs = fen.Constant(50)

        self.lin_func = rhs * self.test_f * fen.dx
Exemplo n.º 5
0
    def create_simple_mesh(self):

        print('Creating simple mesh')
        nx = ny = self.mesh_density

        if self.dimension == 1:

            self.mesh = fe.IntervalMesh(nx, self.x_left, self.x_right)

        if self.dimension == 2:
            self.mesh = fe.UnitSquareMesh(nx, ny)
Exemplo n.º 6
0
def calTrueSol(para):
    nx, ny = para['mesh_N'][0], para['mesh_N'][1]
    mesh = fe.UnitSquareMesh(nx, ny)
    Vu = fe.FunctionSpace(mesh, 'P', para['P'])
    Vc = fe.FunctionSpace(mesh, 'P', para['P'])
    al = fe.Constant(para['alpha'])
    f = fe.Expression(para['f'], degree=5)
    q1 = fe.interpolate(fe.Expression(para['q1'], degree=5), Vc)
    q2 = fe.interpolate(fe.Expression(para['q2'], degree=5), Vc)
    q3 = fe.interpolate(fe.Expression(para['q3'], degree=5), Vc)
    theta = fe.interpolate(fe.Expression(para['q4'], degree=5), Vc)

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

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

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

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

    boundaries = fe.MeshFunction('size_t', mesh, mesh.topology().dim() - 1)
    boundaries.set_all(0)
    bc0, bc1, bc2, bc3 = BoundaryX0(), BoundaryX1(), BoundaryY0(), BoundaryY1()
    bc0.mark(boundaries, 1)
    bc1.mark(boundaries, 2)
    bc2.mark(boundaries, 3)
    bc3.mark(boundaries, 4)

    domains = fe.MeshFunction("size_t", mesh, mesh.topology().dim())
    domains.set_all(0)

    bcD = fe.DirichletBC(Vu, theta, boundaries, 4)
    dx = fe.Measure('dx', domain=mesh, subdomain_data=domains)
    ds = fe.Measure('ds', domain=mesh, subdomain_data=boundaries)

    u_trial, u_test = fe.TrialFunction(Vu), fe.TestFunction(Vu)
    u = fe.Function(Vu)
    left = fe.inner(al * fe.nabla_grad(u_trial), fe.nabla_grad(u_test)) * dx
    right = f * u_test * dx + (q1 * u_test * ds(1) + q2 * u_test * ds(2) +
                               q3 * u_test * ds(3))

    left_m, right_m = fe.assemble_system(left, right, bcD)
    fe.solve(left_m, u.vector(), right_m)

    return u
Exemplo n.º 7
0
 def __init__(self, para):
     # para = [nx, ny, FunctionSpace, degree, ...]
     self.nx, self.ny = para['mesh_N'][0], para['mesh_N'][1]
     self.mesh = fe.UnitSquareMesh(self.nx, self.ny)
     self.Vu = fe.FunctionSpace(self.mesh, 'P', para['P'])
     self.Vc = fe.FunctionSpace(self.mesh, 'P', para['P'])
     self.sol = []
     self.al = fe.Constant(1.0)
     self.f = fe.Constant(0.0)
     self.q = fe.Constant(0.0)
     self.theta = []
     self.mE = 0
Exemplo n.º 8
0
 def __init__(self, para):
     self.nx, self.ny = para['mesh_N'][0], para['mesh_N'][1]
     self.mesh = fe.UnitSquareMesh(self.nx, self.ny)
     self.Vu = fe.FunctionSpace(self.mesh, 'P', para['P'])
     self.Vc = fe.FunctionSpace(self.mesh, 'P', para['P'])
     self.al = fe.Expression(para['alpha'], degree=5)
     self.q1 = fe.interpolate(fe.Expression(para['q1'], degree=5), self.Vc)
     self.q2 = fe.interpolate(fe.Expression(para['q2'], degree=5), self.Vc)
     self.q3 = fe.interpolate(fe.Expression(para['q3'], degree=5), self.Vc)
     self.f = fe.Expression(para['f'], degree=5)
     self.theta = fe.Constant(0.0)
     self.u = fe.Function(self.Vu)
Exemplo n.º 9
0
 def mesh_gen_default(self, intervals, typ='P', order=1):
     """
     creates a square with sides of 1, divided by intervals
     by default the type of the volume associated with the mesh
     is considered to be Lagrangian, with order 1.
     """
     self._mesh = FEN.UnitSquareMesh(intervals, intervals)
     self.input['mesh'] = self._mesh
     self._V = FEN.FunctionSpace(self._mesh, typ, order)
     self.input['V'] = self._V
     self._u = FEN.TrialFunction(self._V)
     self._v = FEN.TestFunction(self._V)
Exemplo n.º 10
0
def test_input_data_read_and_interp(temp_model, monkeypatch):
    """Test the reading & interpolation of input data into InputData object"""

    work_dir = temp_model["work_dir"]
    toml_file = temp_model["toml_filename"]

    # Switch to the working directory
    monkeypatch.chdir(work_dir)

    params = test_parse_config(temp_model)
    dd = params.io.input_dir
    data_file = params.io.data_file

    # Load the mesh & input data
    inmesh = fice.mesh.get_mesh(params)
    indata = inout.InputData(params)

    # Create a function space for interpolation
    test_space = fe.FunctionSpace(inmesh, 'Lagrange', 1)

    # Check successfully reads bed & data_mask
    bed_interp = indata.interpolate("bed", test_space).vector()[:]

    # Check the actual value of an interpolated field:
    # TODO - this is a little ad hoc, can it be incorporated into test definition?
    if "ismip" in toml_file:
        # test_x = np.hsplit(test_space.tabulate_dof_coordinates(), 2)[0][:,0]
        test_y = np.hsplit(test_space.tabulate_dof_coordinates(), 2)[1][:, 0]
        test_bed = 1e4 - test_y * np.tan(0.1 * np.pi / 180.0) - 1e3

    elif "ice_stream" in toml_file:
        test_x = np.hsplit(test_space.tabulate_dof_coordinates(), 2)[0][:, 0]
        test_bed = -500.0 - (test_x / 500.0)
    else:
        raise Exception("Unrecognised test setup")

    assert np.linalg.norm(test_bed - bed_interp) < 1e-10

    # Check unfound data raises error...
    with pytest.raises(KeyError):
        indata.interpolate("a_madeup_name", test_space)

    # ...unless a default is supplied
    outfun = indata.interpolate("a_madeup_name", test_space, default=1.0)
    assert np.all(outfun.vector()[:] == 1.0)

    # Check that an out-of-bounds mesh returns an error
    bad_mesh = fe.UnitSquareMesh(2, 2)
    fe.MeshTransformation.translate(bad_mesh, fe.Point(-1e10, -1e10))
    bad_space = fe.FunctionSpace(bad_mesh, 'Lagrange', 1)
    with pytest.raises(ValueError):
        indata.interpolate("bed", bad_space)
Exemplo n.º 11
0
    def __init__(self, N, K):
        # Variables
        x, y = sym.symbols('x[0], x[1]', real=True, positive=True)
        f = sym.Function('f')(x, y)

        # Precision (inverse covariance) operator, when α = 1
        tau, alpha = 3, 2
        precision = (-sym.diff(f, x, x) - sym.diff(f, y, y) + tau**2 * f)

        indices = [(m, n) for m in range(0, N) for n in range(0, N)]
        # indices = indices[:-1]
        self.indices = sorted(indices, key=max)
        eig_f = [
            sym.cos(i[0] * sym.pi * x) * sym.cos(i[1] * sym.pi * y)
            for i in self.indices
        ]

        # Eigenvalues of the covariance operator
        self.eig_v = [
            1 / (precision.subs(f, e).doit() / e).simplify()**alpha
            for e in eig_f
        ]

        grid = np.linspace(0, 1, K + 2)[1:-1]
        x_obs, y_obs = np.meshgrid(grid, grid)
        self.x_obs, self.y_obs = x_obs.reshape(K * K), y_obs.reshape(K * K)

        # Basis_functions
        self.functions = [
            f * np.sqrt(float(v)) for f, v in zip(eig_f, self.eig_v)
        ]

        # --- THIS PART USED TO NOT BE PARALELLIZABLE --- #
        # Create mesh and define function space
        n_mesh = 80
        mesh = fen.UnitSquareMesh(n_mesh, n_mesh)
        self.f_space = fen.FunctionSpace(mesh, 'P', 2)

        # Define boundary condition
        # u_boundary = fen.Expression('x[0] + x[1]', degree=2)
        u_boundary = fen.Expression('0', degree=2)
        self.bound_cond = fen.DirichletBC(self.f_space, u_boundary,
                                          lambda x, on_boundary: on_boundary)

        # Define variational problem
        self.trial_f = fen.TrialFunction(self.f_space)
        self.test_f = fen.TestFunction(self.f_space)
        rhs = fen.Constant(50)
        # rhs = fen.Expression('sin(x[0])*sin(x[1])', degree=2)
        self.lin_func = rhs * self.test_f * fen.dx
Exemplo n.º 12
0
def solve_poisson_with_fem(lightweight=False):
    # Create mesh and define function space
    mesh = fs.UnitSquareMesh(8, 8)
    V = fs.FunctionSpace(mesh, 'P', 1)

    # Define boundary condition
    u_code = 'x[0] + 2*x[1] + 1'
    u_D = fs.Expression(u_code, degree=2)

    def boundary(x, on_boundary):
        return on_boundary

    bc = fs.DirichletBC(V, u_D, boundary)

    # Define variational problem
    u = fs.Function(V)  # Note: not TrialFunction!
    v = fs.TestFunction(V)

    # f = fs.Expression(f_code, degree=2)
    f_code = '-10*x[0] - 20*x[1] - 10'
    f = fs.Expression(f_code, degree=2)

    F = q(u) * fs.dot(fs.grad(u), fs.grad(v)) * fs.dx - f * v * fs.dx

    # Compute solution
    fs.solve(F == 0, u, bc)

    # Plot solution
    fs.plot(u)

    # Compute maximum error at vertices. This computation illustrates
    # an alternative to using compute_vertex_values as in poisson.py.
    u_e = fs.interpolate(u_D, V)

    # Restore numpy object
    image1d = np.empty((81, ), dtype=np.float)
    for v in fs.vertices(mesh):
        image1d[v.index()] = u(*mesh.coordinates()[v.index()])

    if not lightweight:
        error_max = np.abs(u_e.vector().get_local() -
                           u.vector().get_local()).max()
        print('error_max = ', error_max)

        fs.plot(u)
        plt.show()
        save_contour(image1d, 1.0, 1.0, 'poisson')

    return image1d
def test_ghia1982_steady_lid_driven_cavity():

    lid = "near(x[1],  1.)"

    fixed_walls = "near(x[0],  0.) | near(x[0],  1.) | near(x[1],  0.)"

    bottom_left_corner = "near(x[0], 0.) && near(x[1], 0.)"

    m = 20

    w, mesh = phaseflow.run(
        mesh=fenics.UnitSquareMesh(fenics.dolfin.mpi_comm_world(), m, m,
                                   'crossed'),
        end_time=1.e12,
        time_step_size=1.e12,
        nlp_relative_tolerance=1.e-4,
        liquid_viscosity=0.01,
        gravity=(0., 0.),
        stefan_number=1.e16,
        output_dir='output/test_ghia1982_steady_lid_driven_cavity',
        initial_values_expression=(lid, "0.", "0.", "1."),
        boundary_conditions=[{
            'subspace': 0,
            'value_expression': ("1.", "0."),
            'degree': 3,
            'location_expression': lid,
            'method': 'topological'
        }, {
            'subspace': 0,
            'value_expression': ("0.", "0."),
            'degree': 3,
            'location_expression': fixed_walls,
            'method': 'topological'
        }, {
            'subspace': 1,
            'value_expression': "0.",
            'degree': 2,
            'location_expression': bottom_left_corner,
            'method': 'pointwise'
        }, {
            'subspace': 2,
            'value_expression': "1.",
            'degree': 2,
            'location_expression': bottom_left_corner,
            'method': 'pointwise'
        }])

    verify_against_ghia1982(w, mesh)
Exemplo n.º 14
0
    def __init__(self, h, eps, dim):
        """
        Initializing poisson solver
        :param h: mesh size (of unit interval discretisation)
        :param eps: small parameter
        :param dim: dimension (in {1,2,3})
        """
        self.h = h
        self.n = int(1 / h)
        self.eps = eps
        self.dim = dim
        self.mesh = fe.UnitIntervalMesh(self.n)
        a_eps = '1./(2+cos(2*pi*x[0]/eps))'
        self.e_is = [fe.Constant(1.)]
        if self.dim == 2:
            self.mesh = fe.UnitSquareMesh(self.n, self.n)
            a_eps = '1./(2+cos(2*pi*(x[0]+2*x[1])/eps))'
            self.e_is = [fe.Constant((1., 0.)), fe.Constant((0., 1.))]
        elif self.dim == 3:
            self.mesh = fe.UnitCubeMesh(self.n, self.n, self.n)
            a_eps = '1./(2+cos(2*pi*(x[0]+3*x[1]+6*x[2])/eps))'
            self.e_is = [
                fe.Constant((1., 0., 0.)),
                fe.Constant((0., 1., 0.)),
                fe.Constant((0., 0., 1.))
            ]
        else:
            self.dim = 1
        print("Solving rapid varying Poisson problem in R^%d" % self.dim)
        self.diff_coef = fe.Expression(a_eps,
                                       eps=self.eps,
                                       degree=2,
                                       domain=self.mesh)
        self.a_y = fe.Expression(a_eps.replace("/eps", ""),
                                 degree=2,
                                 domain=self.mesh)
        self.function_space = fe.FunctionSpace(self.mesh, 'P', 2)
        self.solution = fe.Function(self.function_space)
        self.cell_solutions = [
            fe.Function(self.function_space) for _ in range(self.dim)
        ]
        self.eff_diff = np.zeros((self.dim, self.dim))
        # Define boundary condition
        self.bc_function = fe.Constant(0.0)

        self.f = fe.Constant(1)
Exemplo n.º 15
0
    def _setup(self, **kwargs):

        if not self._custom_params_set_flag:
            raise RuntimeError

        for key in kwargs:
            if key not in self.params:
                raise KeyError

        if kwargs:
            raise RuntimeError

        def gp(key):

            value = kwargs.get(key, None)
            if value is None:
                value = self.params[key]

            if value is None:
                raise ValueError
            return value

        dtype, device = fetch_dtype_device(gp('dtype'), gp('device'))

        nx_fom = gp('nx_rom') * (2**gp('num_refines'))
        ny_fom = gp('ny_rom') * (2**gp('num_refines'))
        mesh_rom = df.UnitSquareMesh(df.MPI.comm_self, gp('nx_rom'),
                                     gp('ny_rom'))
        mesh_fom = refine(mesh_rom, gp('num_refines'))

        ########## Physics #########
        physics = dict()
        physics['fom'] = LinearEllipticPhysics('fom', gp('ptype'), mesh_fom)
        physics['rom'] = LinearEllipticPhysics('rom', gp('ptype'), mesh_rom)
        dh = PhysicsResolutionInterpolator(physics, dtype=torch.double)
        physics['W'] = dh._W.detach().cpu().numpy().T.copy()

        return physics, gp, ny_fom, nx_fom, dtype, device
Exemplo n.º 16
0
"""CS tutorial demo program: Poisson equation with Dirichlet conditions.
Test problem is chosen to give an exact solution at all nodes of the mesh.
  -Laplace(u) = f    in the unit square
            u = u_D  on the boundary
  u_D = 1 + x^2 + 2y^2
    f = -6
"""

from __future__ import print_function
import fenics as fex
import matplotlib.pyplot as plt

# Create mesh and define function space
mesh = fex.UnitSquareMesh(8, 8)
V = fex.FunctionSpace(mesh, 'P', 1)

# Define boundary condition
u_D = fex.Expression('1 + x[0]*x[0] + 2*x[1]*x[1]', degree=2)


def boundary(x, on_boundary):
    return on_boundary


bc = fex.DirichletBC(V, u_D, boundary)

# Define variational problem
u = fex.TrialFunction(V)
v = fex.TestFunction(V)
f = fex.Constant(-6.0)
a = fex.dot(fex.grad(u), fex.grad(v)) * fex.dx
Exemplo n.º 17
0
def melt_toy_pcm(output_dir="output/test_melt_toy_pcm/",
                 restart=False,
                 restart_filepath='',
                 start_time=0.):

    # Make the mesh.
    initial_mesh_size = 1

    mesh = fenics.UnitSquareMesh(initial_mesh_size, initial_mesh_size,
                                 'crossed')

    initial_hot_wall_refinement_cycles = 6

    class HotWall(fenics.SubDomain):
        def inside(self, x, on_boundary):

            return on_boundary and fenics.near(x[0], 0.)

    hot_wall = HotWall()

    for i in range(initial_hot_wall_refinement_cycles):

        edge_markers = fenics.EdgeFunction("bool", mesh)

        hot_wall.mark(edge_markers, True)

        fenics.adapt(mesh, edge_markers)

        mesh = mesh.child()

    # Run phaseflow.
    T_hot = 1.

    T_cold = -0.1

    w, mesh = phaseflow.run(
        stefan_number=1.,
        rayleigh_number=1.e6,
        prandtl_number=0.71,
        solid_viscosity=1.e4,
        liquid_viscosity=1.,
        mesh=mesh,
        time_step_size=1.e-3,
        start_time=start_time,
        end_time=0.02,
        stop_when_steady=True,
        temperature_of_fusion=T_f,
        regularization_smoothing_factor=0.025,
        adaptive=True,
        adaptive_metric='phase_only',
        adaptive_solver_tolerance=1.e-4,
        nlp_relative_tolerance=1.e-8,
        initial_values_expression=("0.", "0.", "0.",
                                   "(" + str(T_hot) + " - " + str(T_cold) +
                                   ")*(x[0] < 0.001) + " + str(T_cold)),
        boundary_conditions=[{
            'subspace': 0,
            'value_expression': ("0.", "0."),
            'degree': 3,
            'location_expression':
            "near(x[0],  0.) | near(x[0],  1.) | near(x[1], 0.) | near(x[1],  1.)",
            'method': "topological"
        }, {
            'subspace': 2,
            'value_expression': str(T_hot),
            'degree': 2,
            'location_expression': "near(x[0],  0.)",
            'method': "topological"
        }, {
            'subspace': 2,
            'value_expression': str(T_cold),
            'degree': 2,
            'location_expression': "near(x[0],  1.)",
            'method': "topological"
        }],
        output_dir=output_dir,
        restart=restart,
        restart_filepath=restart_filepath)

    return w
Exemplo n.º 18
0
def solve_heat_with_fem(lightweight=False):
    T = 2.0  # final time
    num_steps = 100  # number of time steps
    dt = T / num_steps  # time step size
    alpha = 3  # parameter alpha
    beta = 1.2  # parameter beta

    # Create mesh and define function space
    nx = ny = 8
    mesh = fs.UnitSquareMesh(nx, ny)
    V = fs.FunctionSpace(mesh, 'P', 1)

    # Define boundary condition
    u_D = fs.Expression('1 + x[0]*x[0] + alpha*x[1]*x[1] + beta*t',
                        degree=2,
                        alpha=alpha,
                        beta=beta,
                        t=0)

    bc = fs.DirichletBC(V, u_D, boundary)

    # Define initial value
    u_n = fs.interpolate(u_D, V)
    # u_n = project(u_D, V)

    # Define variational problem
    u = fs.TrialFunction(V)
    v = fs.TestFunction(V)
    f = fs.Constant(beta - 2 - 2 * alpha)

    F = u * v * fs.dx + dt * fs.dot(
        fs.grad(u), fs.grad(v)) * fs.dx - (u_n + dt * f) * v * fs.dx
    a, L = fs.lhs(F), fs.rhs(F)

    # Time-stepping
    u = fs.Function(V)
    t = 0

    images1d = []

    for n in range(num_steps):
        # Update current time
        t += dt
        u_D.t = t

        # Compute solution
        fs.solve(a == L, u, bc)

        # Restore numpy object
        image1d = np.empty((81, ), dtype=np.float)
        for v in fs.vertices(mesh):
            image1d[v.index()] = u(*mesh.coordinates()[v.index()])

        images1d.append(image1d)

        if not lightweight:
            # Compute error at vertices
            u_e = fs.interpolate(u_D, V)
            error = np.abs(u_e.vector().get_local() -
                           u.vector().get_local()).max()
            print('t = %.2f: error = %.3g' % (t, error))

        # Update previous solution
        u_n.assign(u)

    # Plotting
    if not lightweight:
        fs.plot(u)
        plt.show()
        save_dynamic_contours(images1d, 1.0, 1.0, 'heat2d')

    return images1d
def natural_convection_water(
        restart=False,
        restart_filepath='',
        output_dir='output/test_natural_convection_water/',
        start_time=0.,
        end_time=10.,
        time_step_size=0.001):

    m = 40

    Ra = 2.518084e6

    Pr = 6.99

    T_h = 10.  # [deg C]

    T_c = 0.  # [deg C]

    theta_hot = 1.

    theta_cold = 0.

    T_f = T_fusion = 0.  # [deg C]

    T_ref = T_fusion

    theta_f = theta_fusion = T_fusion - T_ref

    T_m = 4.0293  # [deg C]

    rho_m = 999.972  # [kg/m^3]

    w = 9.2793e-6  # [(deg C)^(-q)]

    q = 1.894816

    def rho(theta):

        return rho_m * (1. - w * abs((T_h - T_c) * theta + T_ref - T_m)**q)

    def ddtheta_rho(theta):

        return -q*rho_m*w*abs(T_m - T_ref + theta*(T_c - T_h))**(q - 1.)* \
            fenics.sign(T_m - T_ref + theta*(T_c - T_h))*(T_c - T_h)

    beta = 6.91e-5  # [K^-1]

    def m_B(T, Ra, Pr, Re):

        return Ra / (Pr * Re * Re) / (beta *
                                      (T_h - T_c)) * (rho(theta_f) -
                                                      rho(T)) / rho(theta_f)

    def ddT_m_B(T, Ra, Pr, Re):

        return -Ra / (Pr * Re *
                      Re) / (beta *
                             (T_h - T_c)) * (ddtheta_rho(T)) / rho(theta_f)

    w, mesh = phaseflow.run(
        rayleigh_number=Ra,
        prandtl_number=Pr,
        stefan_number=1.e16,
        temperature_of_fusion=-1.,
        regularization_smoothing_factor=0.1,
        nlp_relative_tolerance=1.e-8,
        adaptive=False,
        m_B=m_B,
        ddT_m_B=ddT_m_B,
        mesh=fenics.UnitSquareMesh(m, m, 'crossed'),
        stop_when_steady=True,
        steady_relative_tolerance=1.e-5,
        initial_values_expression=("0.", "0.", "0.",
                                   str(theta_hot) + "*near(x[0],  0.) + " +
                                   str(theta_cold) + "*near(x[0],  1.)"),
        boundary_conditions=[{
            'subspace': 0,
            'value_expression': ("0.", "0."),
            'degree': 3,
            'location_expression':
            "near(x[0],  0.) | near(x[0],  1.) | near(x[1], 0.) | near(x[1],  1.)",
            'method': "topological"
        }, {
            'subspace': 2,
            'value_expression': str(theta_hot),
            'degree': 2,
            'location_expression': "near(x[0],  0.)",
            'method': "topological"
        }, {
            'subspace': 2,
            'value_expression': str(theta_cold),
            'degree': 2,
            'location_expression': "near(x[0],  1.)",
            'method': "topological"
        }],
        time_step_size=time_step_size,
        start_time=start_time,
        end_time=end_time,
        output_dir="output/test_natural_convection_water")

    return w, mesh
        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


if run_test:
    mesh = fenics.UnitSquareMesh(10, 10)
    V = fenics.FunctionSpace(mesh, 'CG', 2)

    V_evaluator = FenicsFunctionExtendByZeroEvaluator(V)

    u = fenics.Function(V)
    u.vector()[:] = np.random.randn(V.dim())

    p = np.array([0.5, 0.5])
    up_true = u(fenics.Point(p))
    up = V_evaluator(u.vector()[:], p)
    err_V_evaluator_single = np.abs(up - up_true) / np.abs(up_true)
    print('err_V_evaluator_single=', err_V_evaluator_single)

    N = 1000
    pp = 3 * np.random.rand(N, 2) - 1.0  # random points in [-1, 2]^2
Exemplo n.º 21
0
import fenics as fn
import fenics_adjoint as fa
import ufl

from jaxfenics_adjoint import build_jax_fem_eval
from jaxfenics_adjoint import from_numpy

import matplotlib.pyplot as plt

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

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

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

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

solve_templates = (fa.Function(W),)
assemble_templates = (fa.Function(V), fa.Function(W))
Exemplo n.º 22
0
import fenics
import matplotlib

N = 4

mesh = fenics.UnitSquareMesh(N, N)

P2 = fenics.VectorElement('P', mesh.ufl_cell(), 2)

P1 = fenics.FiniteElement('P', mesh.ufl_cell(), 1)

P2P1 = fenics.MixedElement([P2, P1])

W = fenics.FunctionSpace(mesh, P2P1)

psi_u, psi_p = fenics.TestFunctions(W)

w = fenics.Function(W)

u, p = fenics.split(w)

dynamic_viscosity = 0.01

mu = fenics.Constant(dynamic_viscosity)

inner, dot, grad, div, sym = fenics.inner, fenics.dot, fenics.grad, fenics.div, fenics.sym

momentum = dot(psi_u, dot(grad(u), u)) - div(psi_u) * p + 2. * mu * inner(
    sym(grad(psi_u)), sym(grad(u)))

mass = -psi_p * div(u)
Exemplo n.º 23
0
import fenics as fn
# set parameters
fn.parameters["form_compiler"]["representation"] = "uflacs"
fn.parameters["form_compiler"]["cpp_optimize"] = True

# mesh setup
nps = 64  # number of points
mesh = fn.UnitSquareMesh(nps, nps)
fileu = fn.File(mesh.mpi_comm(), "Output/1_3_Schnackenberg/u.pvd")
filev = fn.File(mesh.mpi_comm(), "Output/1_3_Schnackenberg/v.pvd")

# function spaces
P1 = fn.FiniteElement("Lagrange", mesh.ufl_cell(), 1)
Mh = fn.FunctionSpace(mesh, "Lagrange", 1)
Nh = fn.FunctionSpace(mesh, fn.MixedElement([P1, P1]))
Sol = fn.Function(Nh)

# trial and test functions
u, v = fn.TrialFunctions(Nh)
uT, vT = fn.TestFunctions(Nh)

# model constants
a = fn.Constant(0.1305)
b = fn.Constant(0.7695)
c1 = fn.Constant(0.05)
c2 = fn.Constant(1.0)
d = fn.Constant(170.0)

# initial value
uinit = fn.Expression('a + b + 0.001 * exp(-100.0 * (pow(x[0] - 1.0/3, 2)' +
                      ' + pow(x[1] - 0.5, 2)))',
Exemplo n.º 24
0
 def square(self, nx, ny):
     return FEN.UnitSquareMesh(nx, ny)
Exemplo n.º 25
0
    def xest_first_tutorial(self):
        T = 2.0  # final time
        num_steps = 10  # number of time steps
        dt = T / num_steps  # time step size
        alpha = 3  # parameter alpha
        beta = 1.2  # parameter beta
        # Create mesh and define function space
        nx = ny = 8
        mesh = fenics.UnitSquareMesh(nx, ny)
        V = fenics.FunctionSpace(mesh, 'P', 1)
        # Define boundary condition
        u_D = fenics.Expression('1 + x[0]*x[0] + alpha*x[1]*x[1] + beta*t',
                                degree=2,
                                alpha=alpha,
                                beta=beta,
                                t=0)

        def boundary(x, on_boundary):
            return on_boundary

        bc = fenics.DirichletBC(V, u_D, boundary)
        # Define initial value
        u_n = fenics.interpolate(u_D, V)  #u_n = project(u_D, V)
        # Define variational problem
        u = fenics.TrialFunction(V)
        v = fenics.TestFunction(V)
        f = fenics.Constant(beta - 2 - 2 * alpha)
        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)
        # Time-stepping
        u = fenics.Function(V)
        t = 0
        vtkfile = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output',
                         'heat_constructed_solution', 'solution.pvd'))
        not_initialised = True
        for n in range(num_steps):
            # Update current time
            t += dt
            u_D.t = t
            # Compute solution
            fenics.solve(a == L, u, bc)
            # Plot the solution
            vtkfile << (u, t)
            fenics.plot(u)
            if not_initialised:
                animation_camera = celluloid.Camera(plt.gcf())
                not_initialised = False
            animation_camera.snap()
            # Compute error at vertices
            u_e = fenics.interpolate(u_D, V)
            error = np.abs(u_e.vector().get_local() -
                           u.vector().get_local()).max()
            print('t = %.2f: error = %.3g' % (t, error))
            # Update previous solution
            u_n.assign(u)
            # Hold plot

        animation = animation_camera.animate()
        animation.save(
            os.path.join(os.path.dirname(__file__), 'output',
                         'heat_equation.mp4'))
# You should have received a copy of the GNU General Public License
# along with CASHOCS.  If not, see <https://www.gnu.org/licenses/>.
"""Tests for the geometry module.

"""

import os

import fenics
import numpy as np

import cashocs
from cashocs.geometry import MeshQuality

c_mesh, _, _, _, _, _ = cashocs.regular_mesh(5)
u_mesh = fenics.UnitSquareMesh(5, 5)


def test_mesh_import():
    os.system('cashocs-convert ./mesh/mesh.msh ./mesh/mesh.xdmf')
    mesh, subdomains, boundaries, dx, ds, dS = cashocs.import_mesh(
        './mesh/mesh.xdmf')

    gmsh_coords = np.array([[0, 0], [1, 0], [1, 1], [0, 1],
                            [0.499999999998694, 0], [1, 0.499999999998694],
                            [0.5000000000020591, 1], [0, 0.5000000000020591],
                            [0.2500000000010297, 0.7500000000010296],
                            [0.3749999970924328, 0.3750000029075671],
                            [0.7187499979760099, 0.2812500030636815],
                            [0.6542968741702071, 0.6542968818888233]])
Exemplo n.º 27
0
from pytest_check import check
import fdm
import jax
from jax.config import config
import jax.numpy as np

import fenics
import ufl

from jaxfenics import build_jax_solve_eval_fwd

config.update("jax_enable_x64", True)
fenics.parameters["std_out_all_processes"] = False
fenics.set_log_level(fenics.LogLevel.ERROR)

mesh = fenics.UnitSquareMesh(3, 2)
V = fenics.FunctionSpace(mesh, "P", 1)


def solve_fenics(kappa0, kappa1):

    f = fenics.Expression(
        "10*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.02)", degree=2)

    u = fenics.Function(V)
    bcs = [fenics.DirichletBC(V, fenics.Constant(0.0), "on_boundary")]

    inner, grad, dx = ufl.inner, ufl.grad, ufl.dx
    JJ = 0.5 * inner(kappa0 * grad(u), grad(u)) * dx - kappa1 * f * u * dx
    v = fenics.TestFunction(V)
    F = fenics.derivative(JJ, u, v)
Exemplo n.º 28
0
                                 div(u) = 0
"""

import fenics as fs
import numpy as np
import matplotlib.pyplot as plt

# scaled variables
T = 10.0                # final time
num_steps = 500         # number of time steps
dt = T / num_steps      # time step size
mu = 1                  # kinematic viscosity
rho = 1                 # density

# Create mesh and define function spaces SEPARATELY for pressure and velocity spaces. 
mesh = fs.UnitSquareMesh(16, 16)
V = fs.VectorFunctionSpace(mesh, 'P', 2)    # velocity space, a vector space
Q = fs.FunctionSpace(mesh, 'P', 1)          # pressure space, a scalar space

# Define trial and test functions
u = fs.TrialFunction(V)     # in velocity space
v = fs.TestFunction(V)
p = fs.TrialFunction(Q)     # in pressure space
q = fs.TestFunction(Q)

# Define functions for solutions at previous and current time steps
u_n = fs.Function(V)    # u^(n)
u_  = fs.Function(V)    # u^(n+1)
p_n = fs.Function(Q)    # p^(n)
p_  = fs.Function(Q)    # p^(n+1)
Exemplo n.º 29
0
FEniCS tutorial demo program: Poisson equation with Dirichlet conditions.
Test problem is chosen to give an exact solution at all nodes of the mesh.

  -Laplace(u) = f    in the unit square
            u = u_D  on the boundary

  u_D = 1 + x^2 + 2y^2
    f = -6
"""

import fenics as fs
import numpy as np
import matplotlib.pyplot as plt

# create mesh and define function space
mesh = fs.UnitSquareMesh(8, 8)
V = fs.FunctionSpace(mesh, 'P', 1)

# define boundary condition
u_D = fs.Expression('1 + x[0]*x[0] + 2*x[1]*x[1]', degree=2)


def boundary(x, on_boundary):
    return on_boundary


bc = fs.DirichletBC(V, u_D, boundary)

# define variational problem
u = fs.TrialFunction(V)
v = fs.TestFunction(V)
Exemplo n.º 30
0
    def coarse_mesh(self):

        return fenics.UnitSquareMesh(4, 4)