def s(theta, theta0=prm.theta_m, eps=em.EPS): return dolfin.conditional( abs(theta - theta0) < eps, prm.cp_m * eps + prm.L_m / 2, dolfin.conditional(theta > theta0, prm.cp_s * eps + prm.L_m, prm.cp_s * eps))
def updateCoefficients(self): x, y = SpatialCoordinate(self.mesh) # r = .1*sqrt((x-np.pi)**2 + (y-np.pi)**2) # self.u_ = pow(r,1.5) * sin(x) * sin(y) # Set up explicit solution self.u_ = sin(x) * sin(y) # Init coefficient matrix self.a1 = as_matrix([[2, .5], [ 0.5, 1.5 ]]) + conditional(x * y > 0, 1., -1.) * as_matrix([[1., .5], [.5, .5]]) self.a2 = as_matrix([[1.5, .5], [ 0.5, 2. ]]) + conditional(x * y > 0, 1., -1.) * as_matrix([[.5, .5], [.5, 1.]]) self.a = self.gamma[0] * self.a1 + (1. - self.gamma[0]) * self.a2 # Init right-hand side self.f1 = inner(self.a1, grad(grad(self.u_))) self.f2 = inner(self.a2, grad(grad(self.u_))) self.fcond = conditional(x * y > 0, 0., 1.) # self.f = self.fcond * self.f1 + (1.-self.fcond) * self.f2 self.f = self.gamma[0] * self.f1 + (1. - self.gamma[0]) * self.f2 # conditional(x*x*x-y>0.0,2.0,1.0)]]) # self.f = inner(self.a, grad(grad(self.u_))) # Set boundary conditions to exact solution self.g = Constant(0.0)
def nu_PWC_harm(phi, cc): A = df.conditional(df.gt(phi, 0.975), 1.0, 0.0) B = df.conditional(df.lt(phi, 0.025), 1.0, 0.0) nu = A * cc[r"\nu_1"]\ + B * cc[r"\nu_2"]\ + (1.0 - A - B) * 2.0 / (1.0 / cc[r"\nu_1"] + 1.0 / cc[r"\nu_2"]) return nu
def updateCoefficients(self): # Init coefficient matrix x = SpatialCoordinate(self.mesh)[0] self.a = as_matrix([[.5 * (x * self.gamma[0] * self.sigmax)**2]]) self.b = as_vector([x * (self.gamma[0] * (self.mu - self.r) + self.r)]) self.c = Constant(0.0) # Init right-hand side self.f = Constant(0.0) self.u_ = exp( ((self.mu - self.r)**2 / (2 * self.sigmax**2) * self.alpha / (1 - self.alpha) + self.r * self.alpha) * (self.T[1] - self.t)) * (x**self.alpha) / self.alpha self.u_T = (x**self.alpha) / self.alpha # Set boundary conditions # self.g_t = lambda t : [(Constant(0.0), "near(x[0],0)")] self.g = Constant(0.0) # self.g_t = lambda t : self.u_t(t) self.gamma_star = [ Constant((self.mu - self.r) / (self.sigmax**2 * (1 - self.alpha))) ] self.loc = conditional(x > 0.5, conditional(x < 1.5, 1, 0), 0)
def nu_PWC_arit(phi, cc): A = df.conditional(df.gt(phi, 0.975), 1.0, 0.0) B = df.conditional(df.lt(phi, 0.025), 1.0, 0.0) nu = A * cc[r"\nu_1"]\ + B * cc[r"\nu_2"]\ + (1.0 - A - B) * 0.5 * (cc[r"\nu_1"] + cc[r"\nu_2"]) return nu
def hs_C0(): if type(x) == np.ndarray: y = 0.0*x for pos, val in enumerate(x): if abs(val - x0) < eps: y[pos] = (val-x0)/(2*eps)+0.5 elif val > x0: y[pos] = 1 else: y[pos] = 0 return y return dolfin.conditional(abs(x-x0)<eps,(x-x0)/(2*eps)+0.5, dolfin.conditional(x>x0, 1, 0))
def _speed_squared(self, state): """ The velocity speed with turbine cut in and out speed limits """ speed_sq = dot(state[0], state[0]) + dot(state[1], state[1]) if self._cut_in_speed is not None: speed_sq *= conditional(speed_sq < self._cut_in_speed**2, self._eps, 1) if self._cut_out_speed is not None: speed_sq = conditional(speed_sq > self._cut_out_speed**2, self._cut_out_speed**2, speed_sq) return speed_sq
def updateCoefficients(self): x, y = SpatialCoordinate(self.mesh) self.a = as_matrix([[1.0, 0.], [0., 1.]]) # Init right-hand side xi = 0.5 + pi / 100 self.u_ = conditional(x <= xi, 0.0, 0.5 * (x - xi)**2) # self.f = inner(self.a, grad(grad(self.u_))) self.f = conditional(x <= xi, 0.0, 1.0) # Set boundary conditions to exact solution self.g = self.u_
def sign(x, x0=0.0): """ Give sign of the argument x-x0. Parameters ---------- x: float Input argument which position with respect to x0 we want to know x0: float, optional Center point. Returns ------- -1,1,0: float A float representing the sign of the argument x-x0 """ return dolfin.conditional(x<x0-dolfin.DOLFIN_EPS,-1,dolfin.conditional((x-x0)<dolfin.DOLFIN_EPS,0,1))
def navier_stokes_stabilization_penalties( simulation, nu, velocity_continuity_factor_D12=0, pressure_continuity_factor=0, no_coeff=False, ): """ Calculate the stabilization parameters needed in the DG scheme """ ndim = simulation.ndim mpm = simulation.multi_phase_model mesh = simulation.data['mesh'] use_const = simulation.input.get_value( 'solver/spatially_constant_penalty', False, 'bool' ) if no_coeff: mu_min = mu_max = 1.0 else: mu_min, mu_max = mpm.get_laminar_dynamic_viscosity_range() P = simulation.data['Vu'].ufl_element().degree() if use_const: simulation.log.info(' Using spatially constant elliptic penalty') penalty_dS = define_penalty( mesh, P, mu_min, mu_max, boost_factor=3, exponent=1.0 ) penalty_ds = penalty_dS * 2 simulation.log.info( ' DG SIP penalty: dS %.1f ds %.1f' % (penalty_dS, penalty_ds) ) penalty_dS = Constant(penalty_dS) penalty_ds = Constant(penalty_ds) else: simulation.log.info(' Using spatially varying elliptic penalties') penalty_dS = define_spatially_varying_penalty( simulation, P, mu_min, mu_max, boost_factor=3, exponent=1.0 ) penalty_ds = penalty_dS * 2 penalty_dS = dolfin.conditional( dolfin.lt(penalty_dS('+'), penalty_dS('-')), penalty_dS('-'), penalty_dS('+'), ) if velocity_continuity_factor_D12: D12 = Constant([velocity_continuity_factor_D12] * ndim) else: D12 = Constant([0] * ndim) if pressure_continuity_factor: h = simulation.data['h'] h = Constant(1.0) D11 = avg(h / nu) * Constant(pressure_continuity_factor) else: D11 = None return penalty_dS, penalty_ds, D11, D12
def forms_theta_linear(self, psih0, uh, dt, theta_map, theta_L=Constant(1.0), dpsi0=Constant(0.), dpsi00=Constant(0.), h=Constant(0.), neumann_idx=99, zeta=Constant(0)): (psi, lamb, psibar) = self.__trial_functions() (w, tau, wbar) = self.__test_functions() beta_map = self.beta_map n = self.n facet_integral = self.facet_integral psi_star = psih0 + (1-theta_L)*dpsi00 + theta_L * dpsi0 # LHS contributions gamma = conditional(ge(dot(uh, n), 0), 0, 1) # Standard formulation N_a = facet_integral(beta_map*dot(psi, w)) \ + zeta * dot(grad(psi), grad(w)) * dx G_a = dot(lamb, w)/dt * dx - theta_map * dot(uh, grad(lamb))*w*dx \ + theta_map * (1-gamma) * dot(uh, n) * \ lamb * w * self.ds(neumann_idx) L_a = -facet_integral(beta_map * dot(psibar, w)) # \ H_a = facet_integral(dot(uh, n)*psibar * tau) \ - dot(uh, n)*psibar * tau * self.ds(neumann_idx) B_a = facet_integral(beta_map * dot(psibar, wbar)) # RHS contributions Q_a = dot(Constant(0), w) * dx R_a = dot(psi_star, tau)/dt*dx \ + (1-theta_map)*dot(uh, grad(tau))*psih0*dx \ - (1-theta_map) * (1-gamma) * dot(uh, n) * psi_star * tau * self.ds(neumann_idx) \ - gamma*dot(h, tau) * self.ds(neumann_idx) S_a = facet_integral(Constant(0) * wbar) return self.__fem_forms(N_a, G_a, L_a, H_a, B_a, Q_a, R_a, S_a)
def get_colour_function(self, k): """ Return the colour function on timestep t^{n+k} """ if k == 0: if self.continuous_fields: c = self.continuous_c else: c = self.simulation.data['c'] elif k == -1: if self.continuous_fields: c = self.continuous_c_old else: c = self.simulation.data['cp'] elif k == -2: if self.continuous_fields: c = self.continuous_c_oldold else: c = self.simulation.data['cpp'] if self.force_bounded: c = dolfin.max_value(dolfin.min_value(c, Constant(1.0)), Constant(0.0)) if self.force_sharp: c = dolfin.conditional(dolfin.ge(c, 0.5), Constant(1.0), Constant(0.0)) return c
def get_transition_bounds(self): '''Returns dictionary of `(lower, upper)` bounds for energy transitions. See :py:meth:`get_transition_lower_bounds` for more. ''' lowers = self.get_transition_lower_bounds() upper_bound = ufl.as_ufl(self.inf_upper_bound.m_as(self.energy_unit)) r = {} for k, lower in lowers.items(): lst = [] for k2, lower2 in lowers.items(): if k == k2: continue # FIXME: this is WRONG if lower is exactly equal to lower2 lst.append( dolfin.conditional( ufl.as_ufl(lower2.m) < lower.m, upper_bound, lower2.m)) if not lst: lst.append(upper_bound) upper = self._ufl_minimum(lst) r[k] = (lower, upper * lower.units) return r
def get_strandberg_I(self): u = self.unit_registry h = u('1 planck_constant') c = u('1 speed_of_light') kT = self.pdd.kT mu = self.pdd.mesh_util n_r = 1 K = (8 * dolfin.pi * n_r **2) / (h**3 * c**2) E_L, E_U = self.get_absorption_bounds() # equivalent to flipping integration bounds if E_U < E_L sign = dolfin.conditional(dolfin.gt( E_U.magnitude, E_L.m_as(E_U.units)), +1, -1) # antiderivative of `E^2 exp(E/kT)` def F(E): return -kT*(2*kT**2 + 2*E*kT + E**2) * mu.exp(-E/kT) I = F(E_U) - F(E_L) ans = K * I * sign # to evaluate integrals # ans = (ans.m((0.0, 0.0)) * ans.units).to("1 / centimeter ** 2 / second") # print(self.src_band.key, self.dst_band.key, ans) return ans
def main(): fsr = FunctionSubspaceRegistry() deg = 2 mesh = dolfin.UnitSquareMesh(100, 3) muc = mesh.ufl_cell() el_w = dolfin.FiniteElement('DG', muc, deg - 1) el_j = dolfin.FiniteElement('BDM', muc, deg) el_DG0 = dolfin.FiniteElement('DG', muc, 0) el = dolfin.MixedElement([el_w, el_j]) space = dolfin.FunctionSpace(mesh, el) DG0 = dolfin.FunctionSpace(mesh, el_DG0) fsr.register(space) facet_normal = dolfin.FacetNormal(mesh) xyz = dolfin.SpatialCoordinate(mesh) trial = dolfin.Function(space) test = dolfin.TestFunction(space) w, c = dolfin.split(trial) v, phi = dolfin.split(test) sympy_exprs = derive_exprs() exprs = { k: sympy_dolfin_printer.to_ufl(sympy_exprs['R'], mesh, v) for k, v in sympy_exprs['quantities'].items() } f = exprs['f'] w0 = dolfin.project(dolfin.conditional(dolfin.gt(xyz[0], 0.5), 1.0, 0.3), DG0) w_BC = exprs['w'] dx = dolfin.dx() form = (+v * dolfin.div(c) * dx - v * f * dx + dolfin.exp(w + w0) * dolfin.dot(phi, c) * dx + dolfin.div(phi) * w * dx - (w_BC - w0) * dolfin.dot(phi, facet_normal) * dolfin.ds() - (w0('-') - w0('+')) * dolfin.dot(phi('+'), facet_normal('+')) * dolfin.dS()) solver = NewtonSolver(form, trial, [], parameters=dict(relaxation_parameter=1.0, maximum_iterations=15, extra_iterations=10, relative_tolerance=1e-6, absolute_tolerance=1e-7)) solver.solve() with closing(XdmfPlot("out/qflop_test.xdmf", fsr)) as X: CG1 = dolfin.FunctionSpace(mesh, dolfin.FiniteElement('CG', muc, 1)) X.add('w0', 1, w0, CG1) X.add('w_c', 1, w + w0, CG1) X.add('w_e', 1, exprs['w'], CG1) X.add('f', 1, f, CG1) X.add('cx_c', 1, c[0], CG1) X.add('cx_e', 1, exprs['c'][0], CG1)
def updateCoefficients(self): x, y = SpatialCoordinate(self.mesh) # Init coefficient matrix self.a = as_matrix([[ 2.0, sin(pi * (20 * x * y + .5)) * conditional(x * y > 0, 1, -1) ], [sin(pi * (20 * x * y + .5)) * conditional(x * y > 0, 1, -1), 2.0]]) self.u_ = x * y * sin(2 * pi * x) * \ sin(3 * pi * y) / (x ** 2 + y ** 2 + 1) # Init right-hand side self.f = inner(self.a, grad(grad(self.u_))) # Set boundary conditions to exact solution self.g = self.u_
def inside_absorption_bounds_conditional(self, E, value): E_L, E_U = self.get_absorption_bounds() E_L = E_L.m_as('eV') E_U = E_U.m_as('eV') E = E.m_as('eV') return value.units * dolfin.conditional( ufl.And(E_L <= E, E < E_U), value.magnitude, 0)
def norm_theta_grad_local(): delta_local = 1.5 local_proj = dolfin.conditional(abs(theta-prm.theta_m)<delta_local,1.,0.) norm_theta_grad = dolfin.project(local_proj*dolfin.sqrt(dolfin.inner(dolfin.grad(theta),dolfin.grad(theta))),theta.function_space(),solver_type="cg",preconditioner_type="hypre_amg") return norm_theta_grad.vector().norm('linf')
def initControl(self): # Initialize control spaces self.controlSpace = [FunctionSpace(self.mesh, "DG", 0)] # Initialize controls u_lapl = Dx(Dx(self.u, 0), 0) + Dx(Dx(self.u, 1), 1) # Method 1: self.gamma = [conditional(u_lapl >= 0, self.alpha0, self.alpha1)]
def df_C0(): if type(x) == np.ndarray: y = 0.0*x for pos, val in enumerate(x): if abs(val - x0) < eps: y[pos] = (1.0/(eps**2))*(eps-np.sign(val-x0)*(val-x0)) else: y[pos] = 0 return y return dolfin.conditional(abs(x-x0)<eps,(1.0/(eps**2))*(eps-sign(x-x0)*(x-x0)), 0)
def df_disC(): if type(x) == np.ndarray: y = 0.0*x for pos, val in enumerate(x): if abs(val - x0) < eps: y[pos] = 1.0/(2*eps) else: y[pos] = 0 return y return dolfin.conditional(abs(x-x0)<eps,1.0/(2*eps), 0.)
def initControl(self): # Initialize control spaces self.controlSpace = [FunctionSpace(self.mesh, "DG", 0)] # Initialize controls u_x = Dx(self.u, 0) u_y = Dx(self.u, 1) u_lapl = Dx(u_x, 0) + Dx(u_y, 1) self.gamma = [conditional(u_lapl >= 0, self.alpha0, self.alpha1)]
def df_C1(): if type(x) == np.ndarray: y = 0.0*x for pos, val in enumerate(x): if abs(val - x0) < eps: y[pos] = 15/(16*eps**5)*(((val-x0)+eps)**2*((val-x0)-eps)**2) else: y[pos] = 0 return y return dolfin.conditional(abs(x-x0)<eps, 15/(16*eps**5)*(((x-x0)+eps)**2*((x-x0)-eps)**2), 0)
def subplus(x): r""" Ramp function .. math:: \max\{x,0\} """ return dolfin.conditional(dolfin.ge(x, 0.0), x, 0.0)
def heaviside(x): r""" Heaviside function .. math:: \frac{\mathrm{d}}{\mathrm{d}x} \max\{x,0\} """ return dolfin.conditional(dolfin.ge(x, 0.0), 1.0, 0.0)
def after_last_compute(self, get): self.mag_ta_wss = get("Magnitude_TimeIntegral_WSS-OSI") self.ta_mag_wss = get("TimeIntegral_Magnitude_WSS-OSI") #print self.name, " Calling after_last_compute" expr = conditional(self.ta_mag_wss < 1e-15, 0.0, 0.5 * (1.0 - self.mag_ta_wss / self.ta_mag_wss)) self.osi.assign(project(expr, self.osi.function_space())) return self.osi
def updateCoefficients(self): # Init coefficient matrix x, y = SpatialCoordinate(self.mesh) self.a = as_matrix([[.02, .01], [0.01, conditional(x**3 - y > 0.0, 2.0, 1.0)]]) # Init right-hand side self.f = -1.0 # Set boundary conditions to exact solution self.g = Constant(0.0)
def setUp(self): self.mesh = mesh = dolfin.UnitSquareMesh(20, 2, "left") self.DG0_element = DG0e = dolfin.FiniteElement("DG", mesh.ufl_cell(), 0) self.DG0v_element = DG0ve = dolfin.VectorElement( "DG", mesh.ufl_cell(), 0) self.DG0 = DG0 = dolfin.FunctionSpace(mesh, DG0e) self.DG0v = DG0v = dolfin.FunctionSpace(mesh, DG0ve) self.fsr = fsr = FunctionSubspaceRegistry() fsr.register(DG0) fsr.register(DG0v) self.cellmid = cm = CellMidpointExpression(mesh, element=DG0ve) self.n = n = dolfin.FacetNormal(mesh) self.u = u = dolfin.Function(DG0) self.v = v = dolfin.TestFunction(DG0) u_bc = dolfin.Expression('x[0]', degree=2) x = dolfin.SpatialCoordinate(mesh) self.rho = rho = dolfin.conditional( dolfin.lt((x[0] - 0.5)**2 + (x[1] - 0.5)**2, 0.2**2), 0.0, 0.0) dot = dolfin.dot cellsize = dolfin.CellSize(mesh) self.h = h = cm('+') - cm('-') self.h_boundary = h_boundary = 2 * n * dot(x - cm, n) self.E = E = h / dot(h, h) * (u('-') - u('+')) self.E_boundary = E_boundary = h_boundary / dot( h_boundary, h_boundary) * (u - u_bc) dS = dolfin.dS eps = 1e-8 class BL(dolfin.SubDomain): def inside(self, x, on_boundary): return abs(x[0]) < eps class BR(dolfin.SubDomain): def inside(self, x, on_boundary): return abs(x[0] - 1) < eps ff = dolfin.FacetFunction('size_t', mesh, 0) BL().mark(ff, 1) BR().mark(ff, 1) ds = dolfin.Measure('ds', domain=mesh, subdomain_data=ff) self.F = (dot(E, n('+')) * v('+') * dS + dot(E, n('-')) * v('-') * dS - v * rho * dolfin.dx + dot(E_boundary, n) * v * ds(1))
def initControl(self): # Initialize control spaces self.controlSpace = [] self.controlSpace.append(FunctionSpace(self.mesh, "DG", 0)) self.controlSpace.append(FunctionSpace(self.mesh, "DG", 1)) self.controlSpace.append(FunctionSpace(self.mesh, "DG", 1)) # Initialize controls u_x = Dx(self.u, 0) u_y = Dx(self.u, 1) u_lapl = Dx(u_x, 0) + Dx(u_y, 1) g_a = conditional(u_lapl >= 0, self.alpha0, self.alpha1) u_norm = sqrt(u_x**2 + u_y**2) g_x = conditional(u_norm > 0, u_x / u_norm, 0) g_y = conditional(u_norm > 0, u_y / u_norm, 0) self.gamma = [] self.gamma.append(g_a) self.gamma.append(g_x) self.gamma.append(g_y)
def initControl(self): # Initialize control spaces self.controlSpace = [FunctionSpace(self.mesh, "DG", 1)] # Initialize controls x = SpatialCoordinate(self.mesh)[0] u_x = Dx(self.u, 0) u_xx = Dx(u_x, 0) g1 = conditional( x > 0, -(self.mu - self.r) * u_x / (x * self.sigmax**2 * u_xx), 0) self.gamma = [g1]
def updateCoefficients(self): # Init coefficient matrix x, y = SpatialCoordinate(self.mesh) off_diag = conditional(x * y > 0, 1.0, -1.0) self.a = as_matrix([[2.0, off_diag], [off_diag, 2.0]]) self.u_ = x * y * (1 - exp(1 - abs(x))) * (1 - exp(1 - abs(y))) # Init right-hand side self.f = inner(self.a, grad(grad(self.u_))) # Set boundary conditions to exact solution self.g = self.u_
def _normalize(self, graceful = True): if not isinstance(self, Function): raise Exception("Cannot normalize '%s'." % type(self)) f = self.copy(True) v = TestFunction(f.function_space()) # if graceful = True: (0,0,0) -> (1,0,0) # False: (0,0,0) -> (0,0,0) fx = 1.0 if graceful else 0.0 expr = conditional(eq(inner(f, f), 0.0), \ Constant((fx, 0.0, 0.0)), \ f / sqrt(inner(f, f))) result = Function(f.function_space()) assemble(inner(v, expr) * dP, result.vector()) setattr(self._state, self.name(), result)
def compute(self, get): # Requires the fields Magnitude(TimeIntegral("WSS", label="OSI")) and # TimeIntegral(Magnitude("WSS"), label="OSI") #self.mag_ta_wss = get("Magnitude_TimeIntegral_WSS_OSI") #self.ta_mag_wss = get("TimeIntegral_Magnitude_WSS_OSI") self.mag_ta_wss = get("Magnitude_TimeIntegral_WSS-OSI") self.ta_mag_wss = get("TimeIntegral_Magnitude_WSS-OSI") if self.params.finalize: return None elif self.mag_ta_wss == None or self.ta_mag_wss == None: return None else: expr = conditional(self.ta_mag_wss < 1e-15, 0.0, 0.5 * (1.0 - self.mag_ta_wss / self.ta_mag_wss)) self.osi.assign(project(expr, self.osi.function_space())) return self.osi