def nonzero_initial_guess(self, x): x1 = x[0] x2 = x[1] u1 = fe.Constant(0.) u2 = self.fix_load * x2 / self.height u_initial = fe.as_vector([u1, u2]) return u_initial
def fenics_p_electric(self, my_d): """ @description: Solve poisson equation to get potential and electric field @Modify: 2021/08/31 """ if "plugin3D" in self.det_model: bc_l = [] bc_l = self.boundary_definition_3D(my_d, "Possion") elif "planar3D" in self.det_model: bc_l = self.boundary_definition_2D(my_d, "Possion") u = fenics.TrialFunction(self.V) v = fenics.TestFunction(self.V) if self.det_dic['name'] == "lgad3D": if self.det_dic['part'] == 2: bond = self.det_dic['bond1'] doping_avalanche = self.f_value(my_d, self.det_dic['doping1']) doping = self.f_value(my_d, self.det_dic['doping2']) f = fenics.Expression('x[2] < width ? doping1 : doping2', degree=1, width=bond, doping1=doping_avalanche, doping2=doping) elif self.det_dic['part'] == 3: bond1 = self.det_dic['bond1'] bond2 = self.det_dic['bond2'] doping1 = self.f_value(my_d, self.det_dic['doping1']) doping2 = self.f_value(my_d, self.det_dic['doping2']) doping3 = self.f_value(my_d, self.det_dic['doping3']) f = fenics.Expression( 'x[2] < bonda ? dopinga : x[2] > bondb ? dopingc : dopingb', degree=1, bonda=bond1, bondb=bond2, dopinga=doping1, dopingb=doping2, dopingc=doping3) else: print("The structure of lgad is wrong.") else: f = fenics.Constant(self.f_value(my_d)) a = fenics.dot(fenics.grad(u), fenics.grad(v)) * fenics.dx L = f * v * fenics.dx # Compute solution self.u = fenics.Function(self.V) fenics.solve(a == L, self.u, bc_l, solver_parameters=dict(linear_solver='gmres', preconditioner='ilu')) #calculate electric field W = fenics.VectorFunctionSpace(self.mesh3D, 'P', 1) self.E_field = fenics.project( fenics.as_vector((self.u.dx(0), self.u.dx(1), self.u.dx(2))), W)
def compute_analytical_solutions_fully_broken(self, x): x1 = x[0] x2 = x[1] u1 = fe.Constant(0.) u2 = fe.conditional(fe.gt(x2, self.height / 2.), self.fix_load, fe.Constant(0.)) u_exact = fe.as_vector([u1, u2]) distance_field, _ = distance_function_segments_ufl( x, self.control_points, self.impact_radii) d_exact = fe.exp(-distance_field / (self.l0)) return u_exact, d_exact
w = fe.Function(V) # most recently computed solution (u, p) = fe.split(w) (v, q) = fe.TestFunctions(V) dw = fe.TrialFunction(V) # Kinematics d = u.geometric_dimension() I = fe.Identity(d) # Identity tensor F = fe.variable(I + grad(u)) # Deformation gradient C = fe.variable(F.T * F) # Right Cauchy-Green tensor J = fe.det(C) DE = lambda v: 0.5 * (F.T * grad(v) + grad(v).T * F) a_0 = fe.as_vector([[1.0], [0.], [0.]]) # Invariants I_1 = tr(C) I_2 = 0.5 * (tr(C)**2 - tr(C * C)) I_4 = dot(a_0.T, C * a_0) # Continuation parameter lmbda = 0.01 # parameters taken from O. Roehrle and Heidlauf # Mooney-Rivlin parameters (in kPa) b_1 = 2.756e-5
V = fe.VectorElement("Lagrange", mesh.ufl_cell(), 2) P = fe.FiniteElement("Lagrange", mesh.ufl_cell(), 1) NU = fe.FiniteElement("Lagrange", mesh.ufl_cell(), 1) if MODEL: M = fe.MixedElement([V, P, NU]) else: M = fe.MixedElement([V, P]) W = fe.FunctionSpace(mesh, M) W0 = fe.Function(W) We = fe.Function(W) u0, p0 = fe.split(We) #u0 = fe.Function((W0[0], W0[1]), 'Velocity000023.vtu') #p0 = fe.Function(W0[2]) v, q = fe.TestFunctions(W) #u, p = fe.split(W0) u, p = (fe.as_vector((W0[0], W0[1])), W0[2]) #------------------------------------------------------- # Defining essential/Dirichlet boundary conditions # Step 1: Identify all boundary segments forming Gamma_d #------------------------------------------------------- # (-3., 2.5) # | # | # |_______(0, 1.) # bc1 | # bc2|__________(3., ,0.) # (0,0) bc3 # surface before step
def map_function_ufl(x_hat, control_points, impact_radii, map_type, boundary_info=None): if len(control_points) == 0: return x_hat x_hat = fe.variable(x_hat) df, rho = distance_function_segments_ufl(x_hat, control_points, impact_radii) grad_x_hat = fe.diff(df, x_hat) delta_x_hat = fe.conditional( fe.gt(df, rho), fe.Constant((0., 0.)), grad_x_hat * (rho * ratio_function_ufl(df / rho, map_type) - df)) if boundary_info is None: return delta_x_hat + x_hat else: last_control_point = control_points[-1] points, directions, rho_default = boundary_info mid_point, mid_point1, mid_point2 = points direct_vec, rotated_vec = directions aux_control_point1 = last_control_point + rho_default * rotated_vec aux_control_point2 = last_control_point - rho_default * rotated_vec w1 = np.linalg.norm(mid_point1 - aux_control_point1) w2 = np.linalg.norm(mid_point2 - aux_control_point2) w0 = np.linalg.norm(mid_point - last_control_point) assert np.absolute(2 * w0 - w1 - w2) < 1e-5 AB = mid_point - last_control_point AP = x_hat - last_control_point x1 = AB[0] y1 = AB[1] x2 = AP[0] y2 = AP[1] mod = fe.sqrt(x1**2 + y1**2) df_to_direct = (x1 * y2 - y1 * x2) / mod # AB x AP df_to_rotated = (x1 * x2 + y1 * y2) / mod k1 = rho_default * (w1 + w2) / (rho_default * (w1 + w2) + df_to_direct * (w1 - w2)) new_df_to_direct = rho_default * ratio_function_ufl( df_to_direct / rho_default, map_type) k2 = rho_default * (w1 + w2) / (rho_default * (w1 + w2) + new_df_to_direct * (w1 - w2)) new_df_to_rotated = df_to_rotated * k1 / k2 x = fe.as_vector(last_control_point + direct_vec * new_df_to_rotated + rotated_vec * new_df_to_direct) return fe.conditional( fe.gt(df_to_rotated, 0), fe.conditional(fe.gt(np.absolute(df_to_direct), rho), x_hat, x), delta_x_hat + x_hat)
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))
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='-')