コード例 #1
0
ファイル: mfem.py プロジェクト: tianjuxue/crack
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
コード例 #2
0
    def __compute_shape_derivative(self):
        """Computes the shape derivative.

		Returns
		-------
		None

		Notes
		-----
		This only works properly if differential operators only
		act on state and adjoint variables, else the results are incorrect.
		A corresponding warning whenever this could be the case is issued.
		"""

        # Shape derivative of Lagrangian w/o regularization and pull-backs
        self.shape_derivative = fenics.derivative(
            self.lagrangian.lagrangian_form,
            fenics.SpatialCoordinate(self.mesh), self.test_vector_field)

        # Add pull-backs
        if self.use_pull_back:
            self.state_adjoint_ids = [coeff.id() for coeff in self.states] + [
                coeff.id() for coeff in self.adjoints
            ]

            self.material_derivative_coeffs = []
            for coeff in self.lagrangian.lagrangian_form.coefficients():
                if coeff.id() in self.state_adjoint_ids:
                    pass
                else:
                    if not (coeff.ufl_element().family() == 'Real'):
                        self.material_derivative_coeffs.append(coeff)

            if len(self.material_derivative_coeffs) > 0:
                warning(
                    'Shape derivative might be wrong, if differential operators act on variables other than states and adjoints. \n'
                    'You can check for correctness of the shape derivative with cashocs.verification.shape_gradient_test\n'
                )

            for coeff in self.material_derivative_coeffs:
                # temp_space = fenics.FunctionSpace(self.mesh, coeff.ufl_element())
                # placeholder = fenics.Function(temp_space)
                # temp_form = fenics.derivative(self.lagrangian.lagrangian_form, coeff, placeholder)
                # material_derivative = replace(temp_form, {placeholder : fenics.dot(fenics.grad(coeff), self.test_vector_field)})

                material_derivative = fenics.derivative(
                    self.lagrangian.lagrangian_form, coeff,
                    fenics.dot(fenics.grad(coeff), self.test_vector_field))
                material_derivative = expand_derivatives(material_derivative)

                self.shape_derivative += material_derivative

        # Add regularization
        self.shape_derivative += self.regularization.compute_shape_derivative()
コード例 #3
0
ファイル: pde.py プロジェクト: tianjuxue/crack
    def build_weak_form_staggered(self):
        self.x_hat = fe.variable(fe.SpatialCoordinate(self.mesh))
        self.x = map_function_ufl(self.x_hat, self.control_points,
                                  self.impact_radii, self.map_type,
                                  self.boundary_info)
        self.grad_gamma = fe.diff(self.x, self.x_hat)

        def mfem_grad_wrapper(grad):
            def mfem_grad(u):
                return fe.dot(grad(u), fe.inv(self.grad_gamma))

            return mfem_grad

        self.mfem_grad = mfem_grad_wrapper(fe.grad)

        # A special note (Tianju): We hope to use Model C, but Newton solver fails without the initial guess by Model A
        if self.i < 2:
            self.psi_plus = partial(psi_plus_linear_elasticity_model_A,
                                    lamda=self.lamda,
                                    mu=self.mu)
            self.psi_minus = partial(psi_minus_linear_elasticity_model_A,
                                     lamda=self.lamda,
                                     mu=self.mu)
        else:
            self.psi_plus = partial(psi_plus_linear_elasticity_model_C,
                                    lamda=self.lamda,
                                    mu=self.mu)
            self.psi_minus = partial(psi_minus_linear_elasticity_model_C,
                                     lamda=self.lamda,
                                     mu=self.mu)
            print("use model C")

        self.psi = partial(psi_linear_elasticity, lamda=self.lamda, mu=self.mu)

        self.sigma_plus = cauchy_stress_plus(
            strain(self.mfem_grad(self.x_new)), self.psi_plus)
        self.sigma_minus = cauchy_stress_minus(
            strain(self.mfem_grad(self.x_new)), self.psi_minus)

        # self.sigma = cauchy_stress_plus(strain(self.mfem_grad(self.x_new)), self.psi)
        # self.sigma_degraded = g_d(self.d_new) * self.sigma_plus + self.sigma_minus

        self.G_u = (g_d(self.d_new) * fe.inner(self.sigma_plus, strain(self.mfem_grad(self.eta))) \
            + fe.inner(self.sigma_minus, strain(self.mfem_grad(self.eta)))) * fe.det(self.grad_gamma) * fe.dx

        if self.solution_scheme == 'explicit':
            self.G_d = (self.H_old * self.zeta * g_d_prime(self.d_new, g_d) \
                    + self.G_c / self.l0 * (self.zeta * self.d_new + self.l0**2 * fe.inner(self.mfem_grad(self.zeta), self.mfem_grad(self.d_new)))) * fe.det(self.grad_gamma) * fe.dx
        else:
            self.G_d = (history(self.H_old, self.psi_plus(strain(self.mfem_grad(self.x_new))), self.psi_cr) * self.zeta * g_d_prime(self.d_new, g_d) \
                    + self.G_c / self.l0 * (self.zeta * self.d_new + self.l0**2 * fe.inner(self.mfem_grad(self.zeta), self.mfem_grad(self.d_new)))) * fe.det(self.grad_gamma) * fe.dx
コード例 #4
0
	def compute_shape_derivative(self):
		"""Computes the part of the shape derivative that comes from the regularization

		Returns
		-------
		ufl.form.Form
			The weak form of the shape derivative coming from the regularization

		"""

		V = self.form_handler.test_vector_field
		if self.has_regularization:
			
			x = fenics.SpatialCoordinate(self.form_handler.mesh)
			n = fenics.FacetNormal(self.form_handler.mesh)
			I = fenics.Identity(self.form_handler.mesh.geometric_dimension())

			self.shape_form = Constant(self.mu_surface)*(self.current_surface - Constant(self.target_surface))*t_div(V, n)*self.ds
			
			self.shape_form += Constant(self.mu_curvature)*(inner((I - (t_grad(x, n) + (t_grad(x, n)).T))*t_grad(V, n), t_grad(self.kappa_curvature, n))*self.ds \
						+ Constant(0.5)*t_div(V, n)*t_div(self.kappa_curvature, n)*self.ds)
			
			if not self.measure_hole:
				self.shape_form += Constant(self.mu_volume)*(self.current_volume - Constant(self.target_volume))*div(V)*self.dx
				self.shape_form += Constant(self.mu_barycenter)*(self.current_barycenter_x - Constant(self.target_barycenter_list[0]))\
								   		*(self.current_barycenter_x/self.current_volume*div(V) + 1/self.current_volume*(V[0] + self.spatial_coordinate[0]*div(V)))*self.dx \
								   + Constant(self.mu_barycenter)*(self.current_barycenter_y - Constant(self.target_barycenter_list[1]))\
								   		*(self.current_barycenter_y/self.current_volume*div(V) + 1/self.current_volume*(V[1] + self.spatial_coordinate[1]*div(V)))*self.dx

				if self.form_handler.mesh.geometric_dimension() == 3:
					self.shape_form += Constant(self.mu_barycenter)*(self.current_barycenter_z - Constant(self.target_barycenter_list[2]))\
									   *(self.current_barycenter_z/self.current_volume*div(V) + 1/self.current_volume*(V[2] + self.spatial_coordinate[2]*div(V)))*self.dx


			else:
				self.shape_form -= Constant(self.mu_volume)*(self.current_volume - Constant(self.target_volume))*div(V)*self.dx
				self.shape_form += Constant(self.mu_barycenter)*(self.current_barycenter_x - Constant(self.target_barycenter_list[0]))\
								   		*(self.current_barycenter_x/self.current_volume*div(V) - 1/self.current_volume*(V[0] + self.spatial_coordinate[0]*div(V)))*self.dx \
								   + Constant(self.mu_barycenter)*(self.current_barycenter_y - Constant(self.target_barycenter_list[1]))\
								   		*(self.current_barycenter_y/self.current_volume*div(V) - 1/self.current_volume*(V[1] + self.spatial_coordinate[1]*div(V)))*self.dx

				if self.form_handler.mesh.geometric_dimension() == 3:
					self.shape_form += Constant(self.mu_barycenter)*(self.current_barycenter_z - Constant(self.target_barycenter_list[2]))\
									   		*(self.current_barycenter_z/self.current_volume*div(V) - 1/self.current_volume*(V[2] + self.spatial_coordinate[2]*div(V)))*self.dx


			return self.shape_form

		else:
			dim = self.form_handler.mesh.geometric_dimension()
			return inner(fenics.Constant([0]*dim), V)*self.dx
コード例 #5
0
    def solve_initial_problem_v2(self):
        V = fn.FunctionSpace(self.mesh, 'Lagrange', 2)

        # Define test and trial functions.
        v = fn.TestFunction(V)
        u = fn.TrialFunction(V)

        # Define radial coordinates.
        r = fn.SpatialCoordinate(self.mesh)[0]

        # Define the relative permittivity.

        class relative_perm(fn.UserExpression):
            def __init__(self, markers, subdomain_ids, **kwargs):
                super().__init__(**kwargs)
                self.markers = markers
                self.subdomain_ids = subdomain_ids

            def eval_cell(self, values, x, cell):
                if self.markers[cell.index] == self.subdomain_ids['Vacuum']:
                    values[0] = 1.
                else:
                    values[0] = 10.

        rel_perm = relative_perm(self.subdomains,
                                 self.subdomains_ids,
                                 degree=0)

        # Define the variational form.
        a = r * rel_perm * fn.inner(fn.grad(u), fn.grad(v)) * self.dx
        L = fn.Constant(0.) * v * self.dx

        # Define the boundary conditions.
        bc1 = fn.DirichletBC(V, fn.Constant(0.), self.boundaries,
                             self.boundaries_ids['Bottom_Wall'])
        bc4 = fn.DirichletBC(V, fn.Constant(-10.), self.boundaries,
                             self.boundaries_ids['Top_Wall'])
        bcs = [bc1, bc4]

        # Solve the problem.
        init_phi = fn.Function(V)
        fn.solve(a == L, init_phi, bcs)

        return Poisson.block_project(init_phi,
                                     self.mesh,
                                     self.restrictions_dict['vacuum_rtc'],
                                     self.subdomains,
                                     self.subdomains_ids['Vacuum'],
                                     space_type='scalar')
コード例 #6
0
ファイル: pde.py プロジェクト: tianjuxue/crack
        def obj(x):
            p = fe.Constant(x)
            x_coo = fe.SpatialCoordinate(self.mesh)
            control_points = list(self.control_points)
            control_points.append(p)
            pseudo_radii = np.zeros(len(control_points))
            distance_field, _ = distance_function_segments_ufl(
                x_coo, control_points, pseudo_radii)
            d_artificial = fe.exp(-distance_field / self.l0)

            d_clipped = fe.conditional(fe.gt(self.d_new, 0.5), self.d_new, 0.)

            L_tape = fe.assemble((d_clipped - d_artificial)**2 *
                                 fe.det(self.grad_gamma) * fe.dx)
            # L_tape = fe.assemble((self.d_new - d_artificial)**2 * fe.det(self.grad_gamma) * fe.dx)

            L = float(L_tape)
            return L
コード例 #7
0
    def build_weak_form_staggered(self):
        self.x_hat = fe.variable(fe.SpatialCoordinate(self.mesh))
        self.x = fe.variable(
            map_function_ufl(self.x_hat, self.control_points,
                             self.impact_radii, self.map_type,
                             self.boundary_info))
        self.grad_gamma = fe.diff(self.x, self.x_hat)

        def mfem_grad_wrapper(grad):
            def mfem_grad(u):
                return fe.dot(grad(u), fe.inv(self.grad_gamma))

            return mfem_grad

        self.mfem_grad = mfem_grad_wrapper(fe.grad)

        self.psi_plus = partial(self.psi_plus_linear_elasticity,
                                lamda=self.lamda,
                                mu=self.mu)
        self.psi_minus = partial(self.psi_minus_linear_elasticity,
                                 lamda=self.lamda,
                                 mu=self.mu)
        self.psi = partial(psi_linear_elasticity, lamda=self.lamda, mu=self.mu)

        sigma_plus = cauchy_stress_plus(strain(self.mfem_grad(self.x_new)),
                                        self.psi_plus)
        sigma_minus = cauchy_stress_minus(strain(self.mfem_grad(self.x_new)),
                                          self.psi_minus)

        self.u_exact, self.d_exact = self.compute_analytical_solutions_fully_broken(
            self.x)

        self.G_u = (g_d(self.d_exact) * fe.inner(sigma_plus, strain(self.mfem_grad(self.eta))) \
            + fe.inner(sigma_minus, strain(self.mfem_grad(self.eta)))) * fe.det(self.grad_gamma) * fe.dx

        self.G_d = (self.d_new - self.d_exact) * self.zeta * fe.det(
            self.grad_gamma) * fe.dx

        self.u_initial = self.nonzero_initial_guess(self.x)
        self.x_new.assign(fe.project(self.u_initial, self.U))
コード例 #8
0
ファイル: test_dolfin.py プロジェクト: AxlaCode/AmorFEA
import fenics as fa
import dolfin_adjoint as da
import numpy as np
import moola

n = 64
alpha = da.Constant(0)
mesh = da.UnitSquareMesh(n, n)

# case_flag = 0 runs the default case by
# http://www.dolfin-adjoint.org/en/latest/documentation/poisson-mother/poisson-mother.html
# change to any other value runs the other case
case_flag = 1

x = fa.SpatialCoordinate(mesh)
w = da.Expression("sin(pi*x[0])*sin(pi*x[1])", degree=3)

V = fa.FunctionSpace(mesh, "CG", 1)
W = fa.FunctionSpace(mesh, "DG", 0)

# g is the ground truth for source term
# f is the control variable
if case_flag == 0:
    g = da.interpolate(
        da.Expression("1/(1+alpha*4*pow(pi, 4))*w", w=w, alpha=alpha,
                      degree=3), W)
    f = da.interpolate(
        da.Expression("1/(1+alpha*4*pow(pi, 4))*w", w=w, alpha=alpha,
                      degree=3), W)
else:
    g = da.interpolate(da.Expression(("sin(2*pi*x[0])"), degree=3), W)
コード例 #9
0
import matplotlib.pyplot as plt
import fenics as fe
from ufl import bessel_I

mesh = fe.IntervalMesh(100, 0, 10)
V = fe.FunctionSpace(mesh, 'P', 1)

x = fe.SpatialCoordinate(mesh)
bs = bessel_I(0, x[0])
expr = fe.Expression('cos(x[0]*b)', b=10, element=V.ufl_element())

expr_bessel = expr * bs
proj_expr = fe.project(expr_bessel, V)

# fe.plot(proj_expr)
# plt.show()

# class MyExpression(fe.UserExpression):
#     def eval(self, values, x):
#         values[0] = x[0] ** 2
#     def value_shape(self):
#         return ()
# expr = MyExpression(degree=1)

# class InitialConditions(fe.UserExpression):
#     def __init__(self, **kwargs):
#         # random.seed(2 + MPI.rank(MPI.comm_world))
#         super().__init__(**kwargs)
#     def eval(self, values, x):
#         values[0] = 0.63
#     def value_shape(self):
コード例 #10
0
ファイル: regularization.py プロジェクト: daveb-dev/cashocs
    def __init__(self, form_handler):
        """Initializes the regularization

		Parameters
		----------
		form_handler : cashocs._forms.ShapeFormHandler
			the corresponding shape form handler object
		"""

        self.form_handler = form_handler
        self.config = self.form_handler.config

        self.dx = fenics.Measure('dx', self.form_handler.mesh)
        self.ds = fenics.Measure('ds', self.form_handler.mesh)

        self.spatial_coordinate = fenics.SpatialCoordinate(
            self.form_handler.mesh)

        self.measure_hole = self.config.getboolean('Regularization',
                                                   'measure_hole',
                                                   fallback=False)
        if self.measure_hole:
            self.x_start = self.config.getfloat('Regularization',
                                                'x_start',
                                                fallback=0.0)
            self.x_end = self.config.getfloat('Regularization',
                                              'x_end',
                                              fallback=1.0)
            if not self.x_end >= self.x_start:
                raise ConfigError('Regularization', 'x_end',
                                  'x_end must not be smaller than x_start.')
            self.delta_x = self.x_end - self.x_start

            self.y_start = self.config.getfloat('Regularization',
                                                'y_start',
                                                fallback=0.0)
            self.y_end = self.config.getfloat('Regularization',
                                              'y_end',
                                              fallback=1.0)
            if not self.y_end >= self.y_start:
                raise ConfigError('Regularization', 'y_end',
                                  'y_end must not be smaller than y_start.')
            self.delta_y = self.y_end - self.y_start

            self.z_start = self.config.getfloat('Regularization',
                                                'z_start',
                                                fallback=0.0)
            self.z_end = self.config.getfloat('Regularization',
                                              'z_end',
                                              fallback=1.0)
            if not self.z_end >= self.z_start:
                raise ConfigError('Regularization', 'z_end',
                                  'z_end must not be smaller than z_start.')
            self.delta_z = self.z_end - self.z_start
            if self.form_handler.mesh.geometric_dimension() == 2:
                self.delta_z = 1.0

        self.mu_volume = self.config.getfloat('Regularization',
                                              'factor_volume',
                                              fallback=0.0)
        self.target_volume = self.config.getfloat('Regularization',
                                                  'target_volume',
                                                  fallback=0.0)
        if self.config.getboolean('Regularization',
                                  'use_initial_volume',
                                  fallback=False):
            if not self.measure_hole:
                self.target_volume = fenics.assemble(Constant(1) * self.dx)
            else:
                self.target_volume = self.delta_x * self.delta_y * self.delta_z - fenics.assemble(
                    Constant(1.0) * self.dx)

        self.mu_surface = self.config.getfloat('Regularization',
                                               'factor_surface',
                                               fallback=0.0)
        self.target_surface = self.config.getfloat('Regularization',
                                                   'target_surface',
                                                   fallback=0.0)
        if self.config.getboolean('Regularization',
                                  'use_initial_surface',
                                  fallback=False):
            self.target_surface = fenics.assemble(Constant(1) * self.ds)

        self.mu_barycenter = self.config.getfloat('Regularization',
                                                  'factor_barycenter',
                                                  fallback=0.0)
        self.target_barycenter_list = json.loads(
            self.config.get('Regularization',
                            'target_barycenter',
                            fallback='[0,0,0]'))

        if not type(self.target_barycenter_list) == list:
            raise ConfigError('Regularization', 'target_barycenter',
                              'This has to be a list.')

        if self.form_handler.mesh.geometric_dimension() == 2 and len(
                self.target_barycenter_list) == 2:
            self.target_barycenter_list.append(0.0)

        if self.config.getboolean('Regularization',
                                  'use_initial_barycenter',
                                  fallback=False):
            self.target_barycenter_list = [0.0, 0.0, 0.0]
            if not self.measure_hole:
                volume = fenics.assemble(Constant(1) * self.dx)
                self.target_barycenter_list[0] = fenics.assemble(
                    self.spatial_coordinate[0] * self.dx) / volume
                self.target_barycenter_list[1] = fenics.assemble(
                    self.spatial_coordinate[1] * self.dx) / volume
                if self.form_handler.mesh.geometric_dimension() == 3:
                    self.target_barycenter_list[2] = fenics.assemble(
                        self.spatial_coordinate[2] * self.dx) / volume
                else:
                    self.target_barycenter_list[2] = 0.0

            else:
                volume = self.delta_x * self.delta_y * self.delta_z - fenics.assemble(
                    Constant(1) * self.dx)
                self.target_barycenter_list[0] = (
                    0.5 * (pow(self.x_end, 2) - pow(self.x_start, 2)) *
                    self.delta_y * self.delta_z - fenics.assemble(
                        self.spatial_coordinate[0] * self.dx)) / volume
                self.target_barycenter_list[1] = (
                    0.5 * (pow(self.y_end, 2) - pow(self.y_start, 2)) *
                    self.delta_x * self.delta_z - fenics.assemble(
                        self.spatial_coordinate[1] * self.dx)) / volume
                if self.form_handler.mesh.geometric_dimension() == 3:
                    self.target_barycenter_list[2] = (
                        0.5 * (pow(self.z_end, 2) - pow(self.z_start, 2)) *
                        self.delta_x * self.delta_y - fenics.assemble(
                            self.spatial_coordinate[2] * self.dx)) / volume
                else:
                    self.target_barycenter_list[2] = 0.0

        if not (self.mu_volume >= 0.0 and self.mu_surface >= 0.0
                and self.mu_barycenter >= 0.0):
            raise ConfigError(
                'Regularization', 'mu_volume, mu_surface, or mu_barycenter',
                'All regularization constants have to be nonnegative.')

        if self.mu_volume > 0.0 or self.mu_surface > 0.0 or self.mu_barycenter > 0.0:
            self.has_regularization = True
        else:
            self.has_regularization = False

        # self.relative_scaling = self.config.getboolean('Regularization', 'relative_scaling')
        # if self.relative_scaling and self.has_regularization:
        # 	self.scale_weights()

        self.current_volume = fenics.Expression('val', degree=0, val=1.0)
        self.current_surface = fenics.Expression('val', degree=0, val=1.0)
        self.current_barycenter_x = fenics.Expression('val', degree=0, val=0.0)
        self.current_barycenter_y = fenics.Expression('val', degree=0, val=0.0)
        self.current_barycenter_z = fenics.Expression('val', degree=0, val=0.0)
コード例 #11
0
    def solve_initial_problem(self):
        """
        Solve a simple intial problem for a first guess on the iteration
        process of the main problem. This simple problem is defined as:
            div(r*grad(phiv)) = 0, in vacuum subdomain
            phil              = 0, in liquid subdomain
            sigma             = 0, at interface
        Returns
        -------
        phiv : dolfin.function.function.Function
            Solution of the potential at vacuum.
        phil : dolfin.function.function.Function
            Solution of potential at liquid.
        sigma : dolfin.function.function.Function
            Solution of the surface charge density.
        """

        V = fn.FunctionSpace(self.mesh, 'Lagrange', 2)

        # Define the restrictions.
        restrictions_init = []
        for key in self.subdomains_ids.keys():
            key = key.lower() + '_rtc'
            restrictions_init.append(self.restrictions_dict[key])
        restrictions_init.append(self.restrictions_dict['interface_rtc'])

        # Define the block Function Space.
        W = mp.BlockFunctionSpace([V, V, V], restrict=restrictions_init)

        # Define the trial and test functions.
        test = mp.BlockTestFunction(W)
        (v1, v2, l) = mp.block_split(test)

        trial = mp.BlockTrialFunction(W)
        (phiv, phil, sigma) = mp.block_split(trial)

        # Define auxiliary terms.
        r = fn.SpatialCoordinate(self.mesh)[0]

        #                                       phiv                                                         phil                                sigma             #
        aa = [
            [
                r * fn.inner(fn.grad(phiv), fn.grad(v1)) *
                self.dx(self.subdomains_ids['Vacuum']), 0, 0
            ],  # Test Function v1
            [0, phil * v2 * self.dx(self.subdomains_ids['Liquid']),
             0],  # Test function v2
            [0, 0, sigma("+") * l("+") * self.dS]
        ]  # Test function l
        bb = [
            fn.Constant(0.) * v1 * self.dx(self.subdomains_ids['Vacuum']),
            fn.Constant(0.) * v2 * self.dx(self.subdomains_ids['Liquid']),
            fn.Constant(0.) * l("+") * self.dS
        ]

        # Assemble the previous expressions.
        AA = mp.block_assemble(aa)
        BB = mp.block_assemble(bb)

        # Define the boundary conditions.
        bcs_v = []
        bcs_l = []
        bcs_i = []
        for i in self.boundary_conditions:
            if 'Dirichlet' in self.boundary_conditions[i]:
                sub_id = self.boundary_conditions[i]['Dirichlet'][1]
                if sub_id.lower() == list(
                        self.subdomains_ids.keys())[0].lower():
                    sub_id = 0
                elif sub_id.lower() == list(
                        self.subdomains_ids.keys())[1].lower():
                    sub_id = 1
                else:
                    raise ValueError(
                        f'Subdomain {sub_id} is not defined on the .geo file.')
                bc_val = self.boundary_conditions[i]['Dirichlet'][0]
                bc = mp.DirichletBC(W.sub(sub_id), bc_val, self.boundaries,
                                    self.boundaries_ids[i])
                # Check the created boundary condition.
                assert len(bc.get_boundary_values()
                           ) > 0., f'Wrongly defined boundary {i}'
                if sub_id == 0:
                    bcs_v.append(bc)
                elif sub_id == 1:
                    bcs_l.append(bc)
                else:
                    bcs_i.append(bc)
        bcs = mp.BlockDirichletBC([bcs_v, bcs_l, bcs_i])

        # Apply the boundary conditions.
        bcs.apply(AA)
        bcs.apply(BB)

        # Define the solution function and solve.
        sol = mp.BlockFunction(W)
        mp.block_solve(AA, sol.block_vector(), BB)

        # Split the solution.
        (phiv, phil, sigma) = sol.block_split()

        return phiv, phil, sigma
コード例 #12
0
    def solve(self, **kwargs):
        """
        Solves the variational form of the electrostatics as defined in the
        End of Master thesis from Ximo Gallud Cidoncha:
            A comprehensive numerical procedure for solving the Taylor-Melcher
            leaky dielectric model with charge evaporation.
        Parameters
        ----------
        **kwargs : dict
            Accepted kwargs are:
                - electrostatics_solver_settings: The user may define its own solver parameters. They must be defined
                as follows:
                solver_parameters = {"snes_solver": {"linear_solver": "mumps",
                                      "maximum_iterations": 50,
                                      "report": True,
                                      "error_on_nonconvergence": True,
                                      'line_search': 'bt',
                                      'relative_tolerance': 1e-4}}
                where:
                    - snes_solver is the type of solver to be used. In this
                    case, it is compulsory to use snes, since it's the solver
                    accepted by multiphenics. However, one may try other
                    options if only FEniCS is used. These are: krylov_solver
                    and lu_solver.
                    - linear_solver is the type of linear solver to be used.
                    - maximum_iterations is the maximum number of iterations
                    the solver will try to solve the problem. In case no
                    convergence is achieved, the variable
                    error_on_nonconvergence will raise an error in case this
                    is True. If the user preferes not to raise an error when
                    no convergence, the script will continue with the last
                    results obtained in the iteration process.
                    - line_search is the type of line search technique to be
                    used for solving the problem. It is stronly recommended to
                    use the backtracking (bt) method, since it has been proven
                    to be the most robust one, specially in cases where sqrt
                    are defined, where NaNs may appear due to a bad initial
                    guess or a bad step in the iteration process.
                    - relative_tolerance will tell the solver the parameter to
                    consider convergence on the solution.
                All this options, as well as all the other options available
                can be consulted by calling the method
                Poisson.check_solver_options().
                - initial_potential: Dolfin/FEniCS function which will be used as an initial guess on the iterative
                    process. This must be introduced along with kwarg initial_surface_charge_density. Optional.
                - initial_surface_charge_density: Dolfin/FEniCS function which will be used as an initial guess on the
                    iterative process. This must be introduced along with kwarg initial_potential. Optional.
        Raises
        ------
        TypeError
            This error will raise when the convection charge has not one of the
            following types:
                - Dolfin Function.
                - FEniCS UserExpression.
                - FEniCS Constant.
                - Integer or float number, which will be converted to a FEniCS
                Constant.
        Returns
        -------
        phi : dolfin.function.function.Function
            Dolfin function containing the potential solution.
        surface_charge_density : dolfin.function.function.Function
            Dolfin function conataining the surface charge density solution.
        """

        # --------------------------------------------------------------------
        # EXTRACT THE INPUTS #
        # --------------------------------------------------------------------

        # Check if the type of j_conv is the proper one.
        if not isinstance(self.j_conv, (int, float)) \
            and not Poisson.isDolfinFunction(self.j_conv) \
            and not Poisson.isfenicsexpression(self.j_conv) \
                and not Poisson.isfenicsconstant(self.j_conv):
            conv_type = type(self.j_conv)
            raise TypeError(
                f'Convection charge must be an integer, float, Dolfin function, FEniCS UserExpression or FEniCS constant, not {conv_type}.'
            )
        else:
            if isinstance(self.j_conv, (int, float)):
                self.j_conv = fn.Constant(float(self.j_conv))

        # Extract the solver parameters.
        solver_parameters = kwargs.get('electrostatics_solver_settings')

        # --------------------------------------------------------------------
        # FUNCTION SPACES #
        # --------------------------------------------------------------------
        # Extract the restrictions to create the function spaces.
        """ This variable will be used by multiphenics when creating function spaces. It will create function spaces
            on the introduced restrictions. 
        """
        restrictions_block = [
            self.restrictions_dict['domain_rtc'],
            self.restrictions_dict['interface_rtc']
        ]

        # Base Function Space.
        V = fn.FunctionSpace(self.mesh, 'Lagrange', 2)

        # Block Function Space.
        """ Block Function Spaces are similar to FEniCS function spaces. However, since we are creating function spaces
        based on the block of restrictions, we need to create a 'block of function spaces' for each of the restrictions.
        That block of functions is the list [V, V] from the line of code below this comment. They are assigned in the
        same order in which the block of restrictions has been created, that is:
            - V -> domain_rtc
            - V -> interface_rtc
        """
        W = mp.BlockFunctionSpace([V, V], restrict=restrictions_block)

        # Check the dimensions of the created block function spaces.
        for ix, _ in enumerate(restrictions_block):
            assert W.extract_block_sub_space(
                (ix, )).dim() > 0., f'Subdomain {ix} has dimension 0.'

        # --------------------------------------------------------------------
        # TRIAL/TEST FUNCTIONS #
        # --------------------------------------------------------------------
        # Trial Functions.
        dphisigma = mp.BlockTrialFunction(W)

        # Test functions.
        vl = mp.BlockTestFunction(W)
        (v, l) = mp.block_split(vl)

        phisigma = mp.BlockFunction(W)
        (phi, sigma) = mp.block_split(phisigma)

        # --------------------------------------------------------------------
        # MEASURES #
        # --------------------------------------------------------------------
        self.get_measures()
        self.dS = self.dS(
            self.boundaries_ids['Interface'])  # Restrict to the interface.

        # Check proper marking of the interface.
        assert fn.assemble(
            1 * self.dS(domain=self.mesh)
        ) > 0., "The length of the interface is zero, wrong marking. Check the files in Paraview."

        # --------------------------------------------------------------------
        # DEFINE THE F TERM #
        # --------------------------------------------------------------------
        n = fn.FacetNormal(self.mesh)
        t = fn.as_vector((n[1], -n[0]))

        # Define auxiliary terms.
        r = fn.SpatialCoordinate(self.mesh)[0]
        K = 1 + self.Lambda * (self.T_h - 1)

        E_v_n_aux = fn.dot(-fn.grad(phi("-")), n("-"))

        def expFun():
            sqrterm = E_v_n_aux
            expterm = (self.Phi /
                       self.T_h) * (1 - pow(self.B, 0.25) * fn.sqrt(sqrterm))
            return fn.exp(expterm)

        def sigma_fun():
            num = K * E_v_n_aux + self.eps_r * self.j_conv
            den = K + (self.T_h / self.Chi) * expFun()
            return r * num / den

        # Define the relative permittivity.

        class relative_perm(fn.UserExpression):
            def __init__(self, markers, subdomain_ids, relative, **kwargs):
                super().__init__(**kwargs)
                self.markers = markers
                self.subdomain_ids = subdomain_ids
                self.relative = relative

            def eval_cell(self, values, x, cell):
                if self.markers[cell.index] == self.subdomain_ids['Vacuum']:
                    values[0] = 1.
                else:
                    values[0] = self.relative

        rel_perm = relative_perm(self.subdomains,
                                 self.subdomains_ids,
                                 relative=self.eps_r,
                                 degree=0)

        # Define the variational form.
        # vacuum_int = r*fn.inner(fn.grad(phi), fn.grad(v))*self.dx(self.subdomains_ids['Vacuum'])
        # liquid_int = self.eps_r*r*fn.inner(fn.grad(phi), fn.grad(v))*self.dx(self.subdomains_ids['Liquid'])

        F = [
            r * rel_perm * fn.inner(fn.grad(phi), fn.grad(v)) * self.dx -
            r * sigma("-") * v("-") * self.dS,
            r * sigma_fun() * l("-") * self.dS -
            r * sigma("-") * l("-") * self.dS
        ]

        J = mp.block_derivative(F, phisigma, dphisigma)

        # --------------------------------------------------------------------
        # BOUNDARY CONDITIONS #
        # --------------------------------------------------------------------
        bcs_block = []
        for i in self.boundary_conditions:
            if 'Dirichlet' in self.boundary_conditions[i]:
                bc_val = self.boundary_conditions[i]['Dirichlet'][0]
                bc = mp.DirichletBC(W.sub(0), bc_val, self.boundaries,
                                    self.boundaries_ids[i])
                # Check the created boundary condition.
                assert len(bc.get_boundary_values()
                           ) > 0., f'Wrongly defined boundary {i}'
                bcs_block.append(bc)

        bcs_block = mp.BlockDirichletBC([bcs_block])

        # --------------------------------------------------------------------
        # SOLVE #
        # --------------------------------------------------------------------
        # Define and assign the initial guesses.
        if kwargs.get('initial_potential') is None:
            """
            Check if the user is introducing a potential from a previous
            iteration.
            """
            phiv, phil, sigma_init = self.solve_initial_problem()
            # phi_init = self.solve_initial_problem_v2()
            phi.assign(phiv)
            sigma.assign(sigma_init)
        else:
            phi.assign(kwargs.get('initial_potential'))
            sigma.assign(kwargs.get('initial_surface_charge_density'))

        # Apply the initial guesses to the main function.
        phisigma.apply('from subfunctions')

        # Solve the problem with the solver options (either default or user).
        problem = mp.BlockNonlinearProblem(F, phisigma, bcs_block, J)
        solver = mp.BlockPETScSNESSolver(problem)
        solver_type = [i for i in solver_parameters.keys()][0]
        solver.parameters.update(solver_parameters[solver_type])
        solver.solve()

        # Extract the solutions.
        (phi, _) = phisigma.block_split()
        self.phi = phi
        # --------------------------------------------------------------------

        # Compute the electric field at vacuum and correct the surface charge density.
        self.E_v = self.get_electric_field('Vacuum')
        self.E_v_n = self.get_normal_field(n("-"), self.E_v)
        self.E_t = self.get_tangential_component(t("+"), self.E_v)
        C = self.Phi / self.T_h * (1 - self.B**0.25 * fn.sqrt(self.E_v_n))
        self.sigma = (K * self.E_v_n) / (K + self.T_h / self.Chi * fn.exp(-C))
コード例 #13
0
    def solve(self):
        """
        Solve the Stokes_sim problem based on the mathematical procedure presented by Ximo in this thesis.
        Returns:

        """

        # --------------------------------------------------------------------
        # DEFINE THE INPUTS #
        # --------------------------------------------------------------------
        self.get_mesh()
        self.get_boundaries()
        self.get_subdomains()
        self.get_restrictions()

        # Create a block of restrictions.
        """ This variable will be used by multiphenics when creating function spaces. It will create function spaces
        on the introduced restrictions. 
        """
        block_restrictions = [
            self.restrictions_dict['liquid_rtc'],
            self.restrictions_dict['liquid_rtc'],
            self.restrictions_dict['interface_rtc']
        ]

        # --------------------------------------------------------------------

        # --------------------------------------------------------------------
        # FUNCTION SPACES #
        # --------------------------------------------------------------------
        V = fn.VectorFunctionSpace(self.mesh, "CG", 2)
        Q = fn.FunctionSpace(self.mesh, "CG", 1)
        L = fn.FunctionSpace(self.mesh, "DGT", 0)  # DGT 0.

        # Create a block function space.
        """ Block Function Spaces are similar to FEniCS function spaces. However, since we are creating function spaces
        based on the block of restrictions, we need to create a 'block of function spaces' for each of the restrictions.
        That block of functions is the list [V, Q, L] from the line of code below this comment. They are assigned in the
        same order in which the block of restrictions has been created, that is:
            - V -> liquid_rtc
            - Q -> liquid_rtc
            - L -> interface_rtc
        """
        W = mp.BlockFunctionSpace([V, Q, L], restrict=block_restrictions)
        # --------------------------------------------------------------------

        # --------------------------------------------------------------------
        # TRIAL/TEST FUNCTIONS #
        # --------------------------------------------------------------------
        """ Trial and test functions are created the multiphenics commands for creating these functions. However, the
        difference wrt the FEniCS functions for this purpose, a trial/test function will be created for each of the
        restrictions (for each function space of the BlockFunctionSpace).
        """
        test = mp.BlockTestFunction(W)
        (v, q, l) = mp.block_split(test)

        trial = mp.BlockTrialFunction(W)
        (u, p, theta) = mp.block_split(trial)

        # Use a value of previous velocity to make the system linear, as explained by Ximo.
        u_prev = fn.Function(V)
        u_prev.assign(fn.Constant((0.1, 0.1)))

        # --------------------------------------------------------------------

        # --------------------------------------------------------------------
        # MEASURES #
        # --------------------------------------------------------------------
        self.get_measures()
        self.dS = self.dS(
            self.boundaries_ids['Interface'])  # Restrict to the interface.

        # Check proper marking of the interface.
        assert fn.assemble(
            1 * self.dS(domain=self.mesh)
        ) > 0., "The length of the interface is zero, wrong marking."

        # --------------------------------------------------------------------
        # DEFINE THE VARIATIONAL PROBLEM #
        # --------------------------------------------------------------------
        r = fn.SpatialCoordinate(self.mesh)[0]
        n = fn.FacetNormal(self.mesh)
        tan_vector = fn.as_vector((n[1], -n[0]))
        e_r = fn.Constant((1., 0.))  # Define unit radial vector
        e_z = fn.Constant((0., 1.))  # Define unit axial vector
        aux_term = (self.eps_r * self.Ca *
                    np.sqrt(self.B)) / (1 + self.Lambda * (self.T_h - 1))

        # Define the term a.
        a = r * aux_term * fn.inner((fn.grad(u) + fn.grad(u).T),
                                    (fn.grad(v) + fn.grad(v).T)) * self.dx(
                                        self.subdomains_ids['Liquid'])
        a += 2 / r * aux_term * fn.dot(u, e_r) * fn.dot(v, e_r) * self.dx(
            self.subdomains_ids['Liquid'])

        # Define the term d.
        del_operation = fn.dot(fn.grad(u), u_prev)
        d = r * self.eps_r**2 * self.We * fn.dot(del_operation, v) * self.dx(
            self.subdomains_ids['Liquid'])

        # Define the term l1.
        def evaporated_charge():
            return (self.sigma * self.T_h) / (self.eps_r * self.Chi) * fn.exp(
                -self.Phi / self.T_h *
                (1 - self.B**0.25 * fn.sqrt(self.E_v_n)))

        l1 = -r * evaporated_charge() * l("+") * self.dS

        # Define the term l2.
        l2 = r * self.sigma * fn.dot(self.E_v, tan_vector("-")) * fn.dot(
            v("+"), tan_vector("-")) * self.dS

        # Define the term b.
        def b(vector, scalar):
            radial_term = r * fn.dot(vector, e_r)
            axial_term = r * fn.dot(vector, e_z)
            return -(radial_term.dx(0) + axial_term.dx(1)) * scalar * self.dx(
                self.subdomains_ids['Liquid'])

        # Define the term c.
        c1 = -r * fn.dot(v("+"), n("-")) * theta("+") * self.dS
        c2 = -r * fn.dot(u("+"), n("-")) * l("+") * self.dS

        # Define the tensors to be solved.
        # The following order is used.
        #       u            p           theta       #
        aa = [
            [a + d, b(v, p), c1],  # Test function v
            [b(u, q), 0, 0],  # Test function q
            [c2, 0, 0]
        ]  # Test function l

        bb = [l2, fn.Constant(0.) * q("+") * self.dS, l1]

        # --------------------------------------------------------------------
        # DEFINE THE BOUNDARY CONDITIONS #
        # --------------------------------------------------------------------
        """ When creating Dirichlet boundary conditions with the multiphenics code, a function space from the Block
        must be selected, depending on which subdomain/boundary should it be applied. To do so, the .sub method is used.
        The input is an integer, which depends on the function space in which you want the BC to be applied. For this
        case, inputs of 0, 1 and 2 are accepted, because we have 3 restrictions. The assignments of these ids to the 
        function space is the one done in the block of restrictions.
        """
        bcs_u = []
        bcs_p = []
        for i in self.boundary_conditions:
            if 'Dirichlet' in self.boundary_conditions[i]:
                bc_val = self.boundary_conditions[i]['Dirichlet'][1]
                if self.boundary_conditions[i]['Dirichlet'][0] == 'v':
                    bc = mp.DirichletBC(W.sub(0), bc_val, self.boundaries,
                                        self.boundaries_ids[i])

                    # Check the created boundary condition.
                    assert len(bc.get_boundary_values()
                               ) > 0., f'Wrongly defined boundary {i}'
                    bcs_u.append(bc)
                elif self.boundary_conditions[i]['Dirichlet'][0] == 'p':
                    bc = mp.DirichletBC(W.sub(1), bc_val, self.boundaries,
                                        self.boundaries_ids[i])
                    # Check the created boundary condition.
                    assert len(bc.get_boundary_values()
                               ) > 0., f'Wrongly defined boundary {i}'
                    bcs_p.append(bc)

        bcs_block = mp.BlockDirichletBC([bcs_u, bcs_p])

        # --------------------------------------------------------------------

        # --------------------------------------------------------------------
        # SOLVE #
        # --------------------------------------------------------------------
        # Assemble the system.
        AA = mp.block_assemble(aa)
        BB = mp.block_assemble(bb)

        # Apply the boundary conditions.
        bcs_block.apply(AA)
        bcs_block.apply(BB)

        # Solve.
        uptheta = mp.BlockFunction(W)
        mp.block_solve(AA, uptheta.block_vector(), BB)
        (u, p, theta) = uptheta.block_split()

        self.u = u
        self.p_star = p
        self.theta = theta

        # Compute normal and tangential velocity components.
        u_n = fn.dot(u, n)
        self.u_n = Stokes.block_project(
            u_n,
            self.mesh,
            self.restrictions_dict['interface_rtc'],
            self.boundaries,
            self.boundaries_ids['Interface'],
            space_type='scalar',
            boundary_type='internal',
            sign='-')

        u_t = fn.dot(u, tan_vector)
        self.u_t = Stokes.block_project(
            u_t,
            self.mesh,
            self.restrictions_dict['interface_rtc'],
            self.boundaries,
            self.boundaries_ids['Interface'],
            space_type='scalar',
            boundary_type='internal',
            sign='+')

        # Compute the convection charge transport.
        special = (fn.Identity(self.mesh.topology().dim()) -
                   fn.outer(n, n)) * fn.grad(self.sigma)
        self.j_conv = self.Kc * self.B**(
            3 / 2) * (fn.dot(self.sigma * n, fn.dot(fn.grad(self.u), n)) -
                      fn.dot(self.u, special))
        self.j_conv = Stokes.block_project(
            self.j_conv,
            self.mesh,
            self.restrictions_dict['interface_rtc'],
            self.boundaries,
            self.boundaries_ids['Interface'],
            space_type='scalar',
            boundary_type='internal',
            sign='-')