def referencemesh(mesh, b, hinitial, Href): '''In-place modification of an extruded mesh to create the reference mesh. Changes the top surface to lambda = b + sqrt(Href^2 + (Hinitial - b)^2). Assumes b,hinitial are Functions defined on the base mesh. Assumes the input mesh is extruded 3D mesh with 0 <= z <= 1.''' if not _admissible(b, hinitial): assert ValueError('input hinitial not admissible') P1base = fd.FunctionSpace(mesh._base_mesh, 'P', 1) HH = fd.Function(P1base).interpolate(hinitial - b) # alternative: #lambase = fd.Function(P1base).interpolate(b + fd.max_value(Href, Hstart)) lambase = fd.Function(P1base).interpolate(b + fd.sqrt(HH**2 + Href**2)) lam = extend(mesh, lambase) Vcoord = mesh.coordinates.function_space() if mesh._base_mesh.cell_dimension() == 1: x, z = fd.SpatialCoordinate(mesh) XX = fd.Function(Vcoord).interpolate(fd.as_vector([x, lam * z])) elif mesh._base_mesh.cell_dimension() == 2: x, y, z = fd.SpatialCoordinate(mesh) XX = fd.Function(Vcoord).interpolate(fd.as_vector([x, y, lam * z])) else: raise ValueError('only 2D and 3D reference meshes are generated') mesh.coordinates.assign(XX) return 0
def test_scalar_field(): Nx, Ny = 16, 16 mesh2d = firedrake.UnitSquareMesh(Nx, Ny) mesh3d = firedrake.ExtrudedMesh(mesh2d, layers=1) x, y, z = firedrake.SpatialCoordinate(mesh3d) Q3D = firedrake.FunctionSpace(mesh3d, family='CG', degree=2, vfamily='GL', vdegree=5) q3d = firedrake.interpolate((x**2 + y**2) * (1 - z**4), Q3D) q_avg = depth_average(q3d) p3d = firedrake.interpolate(x**2 + y**2, Q3D) p_avg = depth_average(p3d, weight=1 - z**4) Q2D = firedrake.FunctionSpace(mesh2d, family='CG', degree=2) x, y = firedrake.SpatialCoordinate(mesh2d) q2d = firedrake.interpolate(4 * (x**2 + y**2) / 5, Q2D) assert q_avg.ufl_domain() is mesh2d assert norm(q_avg - q2d) / norm(q2d) < 1 / (Nx * Ny)**2 assert norm(p_avg - q2d) / norm(q2d) < 1 / (Nx * Ny)**2 Q0 = firedrake.FunctionSpace(mesh3d, family='CG', degree=2, vfamily='GL', vdegree=0) q_lift = lift3d(q_avg, Q0) assert norm(depth_average(q_lift) - q2d) / norm(q2d) < 1 / (Nx * Ny)**2
def test_vector_field(): Nx, Ny = 16, 16 mesh2d = firedrake.UnitSquareMesh(Nx, Ny) mesh3d = firedrake.ExtrudedMesh(mesh2d, layers=1) x, y, z = firedrake.SpatialCoordinate(mesh3d) V3D = firedrake.VectorFunctionSpace(mesh3d, "CG", 2, vfamily="GL", vdegree=5, dim=2) u3d = firedrake.interpolate(firedrake.as_vector((1 - z**4, 0)), V3D) u_avg = depth_average(u3d) V2D = firedrake.VectorFunctionSpace(mesh2d, "CG", 2) x, y = firedrake.SpatialCoordinate(mesh2d) u2d = firedrake.interpolate(firedrake.as_vector((4 / 5, 0)), V2D) assert norm(u_avg - u2d) / norm(u2d) < 1 / (Nx * Ny)**2 V0 = firedrake.VectorFunctionSpace(mesh3d, "CG", 2, vfamily="GL", vdegree=0, dim=2) u_lift = lift3d(u_avg, V0) assert norm(depth_average(u_lift) - u2d) / norm(u2d) < 1 / (Nx * Ny)**2
def test_order_0(): def h_expr(x): return h0 - dh * x / Lx def s_expr(x): return d + h0 - dh + ds * (1 - x / Lx) A = firedrake.Constant(icepack.rate_factor(254.15)) C = firedrake.Constant(0.001) opts = {'dirichlet_ids': [1], 'side_wall_ids': [3, 4], 'tolerance': 1e-14} Nx, Ny = 64, 64 mesh2d = firedrake.RectangleMesh(Nx, Ny, Lx, Ly) x, y = firedrake.SpatialCoordinate(mesh2d) Q2d = firedrake.FunctionSpace(mesh2d, family='CG', degree=2) V2d = firedrake.VectorFunctionSpace(mesh2d, family='CG', degree=2) h = firedrake.interpolate(h_expr(x), Q2d) s = firedrake.interpolate(s_expr(x), Q2d) u_expr = firedrake.as_vector((exact_u(x), 0)) u0 = firedrake.interpolate(u_expr, V2d) model2d = icepack.models.IceStream() solver2d = icepack.solvers.FlowSolver(model2d, **opts) u2d = solver2d.diagnostic_solve(velocity=u0, thickness=h, surface=s, fluidity=A, friction=C) mesh = firedrake.ExtrudedMesh(mesh2d, layers=1) x, y, ζ = firedrake.SpatialCoordinate(mesh) Q3d = firedrake.FunctionSpace(mesh, family='CG', degree=2, vfamily='DG', vdegree=0) V3d = firedrake.VectorFunctionSpace(mesh, dim=2, family='CG', degree=2, vfamily='GL', vdegree=0) h = firedrake.interpolate(h_expr(x), Q3d) s = firedrake.interpolate(s_expr(x), Q3d) u_expr = firedrake.as_vector((exact_u(x), 0)) u0 = firedrake.interpolate(u_expr, V3d) model3d = icepack.models.HybridModel() solver3d = icepack.solvers.FlowSolver(model3d, **opts) u3d = solver3d.diagnostic_solve(velocity=u0, thickness=h, surface=s, fluidity=A, friction=C) U2D, U3D = u2d.dat.data_ro, u3d.dat.data_ro assert np.linalg.norm(U3D - U2D) / np.linalg.norm(U2D) < 1e-2
def test_ilu(): """Tests that ILU functionality gives correct solution.""" k = 10.0 num_cells = utils.h_to_num_cells(k**-1.5,2) mesh = fd.UnitSquareMesh(num_cells,num_cells) V = fd.FunctionSpace(mesh,"CG",1) prob = hh.HelmholtzProblem(k,V) angle = 2.0 * np.pi/7.0 d = [np.cos(angle),np.sin(angle)] prob.f_g_plane_wave(d) for fill_in in range(40): prob.use_ilu_gmres(fill_in) prob.solve() x = fd.SpatialCoordinate(mesh) # This error was found out by eye assert np.abs(fd.norms.errornorm(fd.exp(1j * k * fd.dot(fd.as_vector(d),x)),uh=prob.u_h,norm_type='H1')) < 0.5
def test_interpolating_function(): nx, ny = 32, 32 mesh = firedrake.UnitSquareMesh(nx, ny) x = firedrake.SpatialCoordinate(mesh) Q = firedrake.FunctionSpace(mesh, "CG", 2) q = icepack.interpolate(x[0] ** 2 - x[1] ** 2, Q) assert abs(firedrake.assemble(q * dx)) < 1e-6
def test_n_min_ufl(): """Tests that the sharp cutoff function does what it should when n is given by a ufl expression.""" k = 10.0 mesh = fd.UnitSquareMesh(10,10) V = fd.FunctionSpace(mesh,"CG",1) x = fd.SpatialCoordinate(mesh) n = 1.0 + fd.sin(30*x[0]) prob = hh.HelmholtzProblem(k,V,n=n) n_min_val = 2.0 prob.n_min(n_min_val) V_DG = fd.FunctionSpace(mesh,"DG",0) n_fn = fd.Function(V_DG) n_fn.interpolate(prob._n) assert (n_fn.dat.data_ro >= n_min_val).all()
def test_sharp_cutoff_pre_ufl(): """Tests that the sharp cutoff function does what it should when the preconditioning coefficient is given by ufl.""" k = 10.0 mesh = fd.UnitSquareMesh(10,10) V = fd.FunctionSpace(mesh,"CG",1) x = fd.SpatialCoordinate(mesh) n_pre = 1.0 + fd.sin(30*x[0]) prob = hh.HelmholtzProblem(k,V,n_pre=n_pre,A_pre = fd.as_matrix([[1.0,0.0],[0.0,1.0]])) prob.sharp_cutoff(np.array([0.5,0.5]),0.5,True) V_DG = fd.FunctionSpace(mesh,"DG",0) n_fn = fd.Function(V_DG) n_fn.interpolate(prob._n_pre) # As above assert n_fn.dat.data_ro[97] == 1.0
def test_sharp_cutoff_ufl(): """Tests that the sharp cutoff function does what it should when the coefficient is given by a ufl expression.""" k = 10.0 mesh = fd.UnitSquareMesh(10,10) V = fd.FunctionSpace(mesh,"CG",1) x = fd.SpatialCoordinate(mesh) n = 1.0 + fd.sin(30*x[0]) prob = hh.HelmholtzProblem(k,V,n=n) prob.sharp_cutoff(np.array([0.5,0.5]),0.5) V_DG = fd.FunctionSpace(mesh,"DG",0) n_fn = fd.Function(V_DG) n_fn.interpolate(prob._n) # This is a rudimentary test that it's 1 on the boundary # Yes, I kind of made this pass by changing the value to check until it did. # But I've confirmed that it's doing (roughly) the right thing visually, so I'm content assert n_fn.dat.data_ro[97] == 1.0
def test_plot_field(): mesh = firedrake.UnitSquareMesh(32, 32) Q = firedrake.FunctionSpace(mesh, "CG", 1) x, y = firedrake.SpatialCoordinate(mesh) u = interpolate(x * y, Q) fig, axes = icepack.plot.subplots(nrows=2, ncols=2, sharex=True, sharey=True) filled_contours = icepack.plot.tricontourf(u, axes=axes[0, 0]) assert filled_contours is not None colorbar = plt.colorbar(filled_contours, ax=axes[0, 0]) assert colorbar is not None contours = icepack.plot.tricontour(u, axes=axes[0, 1]) assert contours is not None colors_flat = icepack.plot.tripcolor(u, shading="flat", axes=axes[1, 0]) assert colors_flat is not None colors_gouraud = icepack.plot.tripcolor(u, shading="gouraud", axes=axes[1, 1]) assert colors_flat.get_array().shape != colors_gouraud.get_array().shape
def test_hybrid_prognostic_solve(): Lx, Ly = 20e3, 20e3 h0, dh = 500.0, 100.0 T = 254.15 u_in = 100.0 model = icepack.models.HybridModel() opts = {'dirichlet_ids': [1], 'side_wall_ids': [3, 4], 'tol': 1e-12} Nx, Ny = 32, 32 mesh2d = firedrake.RectangleMesh(Nx, Ny, Lx, Ly) mesh = firedrake.ExtrudedMesh(mesh2d, layers=1) V = firedrake.VectorFunctionSpace(mesh, dim=2, family='CG', degree=2, vfamily='GL', vdegree=1) Q = firedrake.FunctionSpace(mesh, family='CG', degree=2, vfamily='DG', vdegree=0) x, y, ζ = firedrake.SpatialCoordinate(mesh) height_above_flotation = 10.0 d = -ρ_I / ρ_W * (h0 - dh) + height_above_flotation ρ = ρ_I - ρ_W * d**2 / (h0 - dh)**2 Z = icepack.rate_factor(T) * (ρ * g * h0 / 4)**n q = 1 - (1 - (dh / h0) * (x / Lx))**(n + 1) ux = u_in + Z * q * Lx * (h0 / dh) / (n + 1) u0 = interpolate(firedrake.as_vector((ux, 0)), V) thickness = h0 - dh * x / Lx β = 1 / 2 α = β * ρ / ρ_I * dh / Lx h = interpolate(h0 - dh * x / Lx, Q) h_inflow = h.copy(deepcopy=True) ds = (1 + β) * ρ / ρ_I * dh s = interpolate(d + h0 - dh + ds * (1 - x / Lx), Q) b = interpolate(s - h, Q) C = interpolate(α * (ρ_I * g * thickness) * ux**(-1 / m), Q) A = firedrake.Constant(icepack.rate_factor(T)) final_time, dt = 1.0, 1.0 / 12 num_timesteps = int(final_time / dt) u = model.diagnostic_solve(u0=u0, h=h, s=s, C=C, A=A, **opts) a0 = firedrake.Constant(0) a = interpolate((model.prognostic_solve(dt, h0=h, a=a0, u=u) - h) / dt, Q) for k in range(num_timesteps): h = model.prognostic_solve(dt, h0=h, a=a, u=u, h_inflow=h_inflow) s = icepack.compute_surface(h=h, b=b) u = model.diagnostic_solve(u0=u, h=h, s=s, C=C, A=A, **opts) assert icepack.norm(h, norm_type='Linfty') < np.inf
def __init__(self, mesh_r, refinements=1, order=1): mh = fd.MeshHierarchy(mesh_r, refinements) self.mesh_hierarchy = mh # Control space on coarsest mesh self.mesh_r_coarse = self.mesh_hierarchy[0] self.V_r_coarse = fd.VectorFunctionSpace(self.mesh_r_coarse, "CG", order) # Create self.id and self.T on refined mesh. element = self.V_r_coarse.ufl_element() self.intermediate_Ts = [] for i in range(refinements - 1): mesh = self.mesh_hierarchy[i + 1] V = fd.FunctionSpace(mesh, element) self.intermediate_Ts.append(fd.Function(V)) self.mesh_r = self.mesh_hierarchy[-1] element = self.V_r_coarse.ufl_element() self.V_r = fd.FunctionSpace(self.mesh_r, element) X = fd.SpatialCoordinate(self.mesh_r) self.id = fd.Function(self.V_r).interpolate(X) self.T = fd.Function(self.V_r, name="T") self.T.assign(self.id) self.mesh_m = fda.Mesh(self.T) self.V_m = fd.FunctionSpace(self.mesh_m, element)
def Bueler_profile(mesh, R): x, y = firedrake.SpatialCoordinate(mesh) r = firedrake.sqrt(x**2 + y**2) h_divide = (2 * R * (alpha/A0)**(1/n) * (n-1)/n)**(n/(2*n+2)) h_part2 = (n+1)*(r/R) - n*(r/R)**((n+1)/n) + n*(max_value(1-(r/R),0))**((n+1)/n) - 1 h_expr = (h_divide/((n-1)**(n/(2*n+2)))) * (max_value(h_part2,0))**(n/(2*n+2)) return h_expr
def surfaceelevation(mesh): x = fd.SpatialCoordinate(mesh) # z itself is an 'Indexed' object, so use a Function with a .dat attribute Q1 = fd.FunctionSpace(mesh, 'Q', 1) z = fd.Function(Q1).interpolate(x[mesh._base_mesh.cell_dimension()]) hbase, _ = _surfacevalue(mesh, z) return hbase
def create_function_marker(PHI, W, xlimits, ylimits): x, y, z = fd.SpatialCoordinate(PHI.ufl_domain()) x_func, y_func, z_func = ( fd.Function(PHI), fd.Function(PHI), fd.Function(PHI), ) with fda.stop_annotating(): x_func.interpolate(x) y_func.interpolate(y) z_func.interpolate(z) domain = "{[i, j]: 0 <= i < f.dofs and 0<= j <= 3}" instruction = f""" f[i, j] = 1.0 if (x[i, 0] < {xlimits[1]} and x[i, 0] > {xlimits[0]}) and (y[i, 0] < {ylimits[0]} or y[i, 0] > {ylimits[1]}) and z[i, 0] < 1e-7 else 0.0 """ I_BC = fd.Function(W) fd.par_loop( (domain, instruction), dx, { "f": (I_BC, fd.RW), "x": (x_func, fd.READ), "y": (y_func, fd.READ), "z": (z_func, fd.READ), }, is_loopy_kernel=True, ) return I_BC
def interpolate(self, mesh, k0L): V = fd.VectorFunctionSpace(mesh, "CG", 1) x = fd.SpatialCoordinate(mesh) pw = fd.interpolate(self.p * fd.exp(1j * k0L * fd.dot(self.s, x)), V) return pw
def __init__(self, mesh_r): # Create mesh_r and V_r self.mesh_r = mesh_r element = self.mesh_r.coordinates.function_space().ufl_element() self.V_r = fd.FunctionSpace(self.mesh_r, element) # Create self.id and self.T, self.mesh_m, and self.V_m. X = fd.SpatialCoordinate(self.mesh_r) self.id = fd.interpolate(X, self.V_r) self.T = fd.Function(self.V_r, name="T") self.T.assign(self.id) self.mesh_m = fd.Mesh(self.T) self.V_m = fd.FunctionSpace(self.mesh_m, element) self.is_DG = False """ ControlSpace for discontinuous coordinate fields (e.g. periodic domains) In Firedrake, periodic meshes are implemented using a discontinuous field. This implies that self.V_r contains discontinuous functions. To ensure domain updates do not create holes in the domain, use a continuous subspace self.V_c of self.V_r as control space. """ if element.family() == 'Discontinuous Lagrange': self.is_DG = True self.V_c = fd.VectorFunctionSpace(self.mesh_r, "CG", element._degree) self.Ip = fd.Interpolator(fd.TestFunction(self.V_c), self.V_r).callable().handle
def test_diagnostic_solver_side_friction(): model = icepack.models.IceShelf() opts = {"dirichlet_ids": [1], "side_wall_ids": [3, 4]} mesh = firedrake.RectangleMesh(32, 32, Lx, Ly) degree = 2 V = firedrake.VectorFunctionSpace(mesh, "CG", degree) Q = firedrake.FunctionSpace(mesh, "CG", degree) x, y = firedrake.SpatialCoordinate(mesh) u_initial = interpolate(as_vector((exact_u(x), 0)), V) h = interpolate(h0 - dh * x / Lx, Q) A = interpolate(firedrake.Constant(icepack.rate_factor(T)), Q) # Choose the side wall friction coefficient so that, assuming the ice is # sliding at the maximum speed for the solution without friction, the # stress is 10 kPa. from icepack.constants import weertman_sliding_law as m τ = 0.01 u_max = icepack.norm(u_initial, norm_type="Linfty") Cs = firedrake.Constant(τ * u_max**(-1 / m)) solver = icepack.solvers.FlowSolver(model, **opts) fields = { "velocity": u_initial, "thickness": h, "fluidity": A, "side_friction": Cs } u = solver.diagnostic_solve(**fields) assert icepack.norm(u) < icepack.norm(u_initial)
def manufactured_solution(mesh): x = fe.SpatialCoordinate(mesh)[0] s = parameters["smoothing"] return tanh(pi*x/s)
def terminus(u, h, s): r"""Return the terminal stress part of the hybrid model action functional The power exerted due to stress at the calving terminus :math:`\Gamma` is .. math:: E(u) = \int_\Gamma\int_0^1\left(\rho_Ig(1 - \zeta) - \rho_Wg(\zeta_{\text{sl}} - \zeta)_+\right)u\cdot\nu\; h\, d\zeta\; ds where :math:`\zeta_\text{sl}` is the relative depth to sea level and the :math:`(\zeta_\text{sl} - \zeta)_+` denotes only the positive part. Parameters ---------- u : firedrake.Function ice velocity h : firedrake.Function ice thickness s : firedrake.Function ice surface elevation ice_front_ids : list of int numeric IDs of the parts of the boundary corresponding to the calving front """ mesh = u.ufl_domain() zdegree = u.ufl_element().degree()[1] x, y, ζ = firedrake.SpatialCoordinate(mesh) b = s - h ζ_sl = firedrake.max_value(-b, 0) / h p_W = ρ_W * g * h * _pressure_approx(zdegree + 1)(ζ, ζ_sl) p_I = ρ_I * g * h * (1 - ζ) ν = facet_normal_2(mesh) return (p_I - p_W) * inner(u, ν) * h
def test_diagnostic_solver_convergence(): # Create an ice shelf model ice_shelf = icepack.models.IceShelf() opts = {'dirichlet_ids': [1], 'side_wall_ids': [3, 4], 'tol': 1e-12} # Solve the ice shelf model for successively higher mesh resolution for degree in range(1, 4): delta_x, error = [], [] for N in range(16, 97 - 32 * (degree - 1), 4): mesh = firedrake.RectangleMesh(N, N, Lx, Ly) x, y = firedrake.SpatialCoordinate(mesh) V = firedrake.VectorFunctionSpace(mesh, 'CG', degree) Q = firedrake.FunctionSpace(mesh, 'CG', degree) u_exact = interpolate(as_vector((exact_u(x), 0)), V) u_guess = interpolate(u_exact + as_vector((perturb_u(x, y), 0)), V) h = interpolate(h0 - dh * x / Lx, Q) A = interpolate(firedrake.Constant(icepack.rate_factor(T)), Q) u = ice_shelf.diagnostic_solve(h=h, A=A, u0=u_guess, **opts) error.append(norm(u_exact - u) / norm(u_exact)) delta_x.append(Lx / N) print(delta_x[-1], error[-1]) # Fit the error curve and check that the convergence rate is what we # expect log_delta_x = np.log2(np.array(delta_x)) log_error = np.log2(np.array(error)) slope, intercept = np.polyfit(log_delta_x, log_error, 1) print('log(error) ~= {:g} * log(dx) + {:g}'.format(slope, intercept)) assert slope > degree + 0.8
def test_n_min_pre_ufl(): """Tests that the sharp cutoff function does what it should when n_pre is given by a UFL expression.""" k = 10.0 mesh = fd.UnitSquareMesh(10,10) V = fd.FunctionSpace(mesh,"CG",1) x = fd.SpatialCoordinate(mesh) n_pre = 1.0 + fd.sin(30*x[0]) prob = hh.HelmholtzProblem(k,V,n_pre=n_pre,A_pre = fd.as_matrix([[1.0,0.0],[0.0,1.0]])) n_min_val = 2.0 prob.n_min(n_min_val,True) V_DG = fd.FunctionSpace(mesh,"DG",0) n_fn = fd.Function(V_DG) n_fn.interpolate(prob._n_pre) assert (n_fn.dat.data_ro >= n_min_val).all()
def setup_constants(self): x, y = fd.SpatialCoordinate(self.mesh) self.constants = { 'deltat': fd.Constant(self.prm['dt']), 'Kd': fd.Constant(0.01), 'k1': fd.Constant(0.005), 'k2': fd.Constant(0.00005), 'lamd1': fd.Constant(0.000005), 'lamd2': fd.Constant(0.0), 'rho_s': fd.Constant(1.), 'L': fd.Constant(1.), 'phi': fd.Constant(0.3), 'n': fd.FacetNormal(self.mesh), 'f': fd.Constant((0.0, 0.0)), 'nu': fd.Constant(0.001), 'frac': fd.Constant(1.), 'source1': fd.conditional( pow(x - 1, 2) + pow(y - 1.5, 2) < 0.25 * 0.25, 10.0, 0) }
def manufactured_solution(mesh): x = fe.SpatialCoordinate(mesh)[0] sin, pi = fe.sin, fe.pi return sin(pi*x)*exp(-t)
def test_interpolating_vector_field(): n = 32 array_vx = np.array([[(i + j) / n for j in range(n + 1)] for i in range(n + 1)]) missing = -9999.0 array_vx[0, 0] = missing array_vx = np.flipud(array_vx) array_vy = np.array([[(j - i) / n for j in range(n + 1)] for i in range(n + 1)]) array_vy[-1, -1] = -9999.0 array_vy = np.flipud(array_vy) vx = make_rio_dataset(array_vx, missing) vy = make_rio_dataset(array_vy, missing) mesh = make_domain(48, 48, xmin=1 / 4, ymin=1 / 4, width=1 / 2, height=1 / 2) x, y = firedrake.SpatialCoordinate(mesh) V = firedrake.VectorFunctionSpace(mesh, family='CG', degree=1) u = firedrake.interpolate(firedrake.as_vector((x + y, x - y)), V) v = icepack.interpolate((vx, vy), V) assert firedrake.norm(u - v) / firedrake.norm(u) < 1e-10
def manufactured_solution(sim): sin, pi = fe.sin, fe.pi x = fe.SpatialCoordinate(sim.mesh)[0] return sin(2.*pi*x)
def time_verification_solution(sim): exp = fe.exp x, y = fe.SpatialCoordinate(sim.mesh) t = sim.time u0 = sin(2. * pi * x) * sin(pi * y) u1 = sin(pi * x) * sin(2. * pi * y) ihat, jhat = sim.unit_vectors() u = exp(t) * (u0 * ihat + u1 * jhat) p = -0.5 * sin(pi * x) * sin(pi * y) T = exp(t) * sin(2. * pi * x) * sin(pi * y) mean_pressure = fe.assemble(p * fe.dx) p -= mean_pressure return p, u, T
def test_equality_constraint(pytestconfig): mesh = fs.DiskMesh(0.05, radius=2.) Q = fs.FeControlSpace(mesh) inner = fs.ElasticityInnerProduct(Q, direct_solve=True) mesh_m = Q.mesh_m (x, y) = fd.SpatialCoordinate(mesh_m) q = fs.ControlVector(Q, inner) if pytestconfig.getoption("verbose"): out = fd.File("domain.pvd") def cb(*args): out.write(Q.mesh_m.coordinates) else: cb = None f = (pow(2 * x, 2)) + pow(y - 0.1, 2) - 1.2 J = fsz.LevelsetFunctional(f, Q, cb=cb) vol = fsz.LevelsetFunctional(fd.Constant(1.0), Q) e = fs.EqualityConstraint([vol]) emul = ROL.StdVector(1) params_dict = { 'Step': { 'Type': 'Augmented Lagrangian', 'Augmented Lagrangian': { 'Subproblem Step Type': 'Line Search', 'Penalty Parameter Growth Factor': 2., 'Initial Penalty Parameter': 1., 'Subproblem Iteration Limit': 20, }, 'Line Search': { 'Descent Method': { 'Type': 'Quasi-Newton Step' } }, }, 'General': { 'Secant': { 'Type': 'Limited-Memory BFGS', 'Maximum Storage': 5 } }, 'Status Test': { 'Gradient Tolerance': 1e-4, 'Step Tolerance': 1e-10, 'Iteration Limit': 10 } } params = ROL.ParameterList(params_dict, "Parameters") problem = ROL.OptimizationProblem(J, q, econ=e, emul=emul) solver = ROL.OptimizationSolver(problem, params) solver.solve() state = solver.getAlgorithmState() assert (state.gnorm < 1e-4) assert (state.cnorm < 1e-6)
def test_firedrake_to_numpy_function(): # Functions in DG0 have nodes at centers of finite element cells mesh = firedrake.UnitIntervalMesh(10) V = firedrake.FunctionSpace(mesh, "DG", 0) x = firedrake.SpatialCoordinate(mesh) test_input = firedrake.interpolate(x[0], V) expected = numpy.linspace(0.05, 0.95, num=10) assert numpy.allclose(to_numpy(test_input), expected)
def __init__(self, pde_solver: PoissonSolver, *args, **kwargs): super().__init__(*args, **kwargs) self.pde_solver = pde_solver # target function, exact soln is disc of radius 0.6 centered at # (0.5,0.5) (x, y) = fd.SpatialCoordinate(pde_solver.mesh_m) self.u_target = 0.36 - (x - 0.5) * (x - 0.5) - (y - 0.5) * (y - 0.5)