def test_TimeTracking(): """ Main test.""" # setup problem mesh = fd.UnitSquareMesh(20, 20) Q = fs.FeControlSpace(mesh) inner = fs.LaplaceInnerProduct(Q, fixed_bids=[1, 2, 3, 4]) q = fs.ControlVector(Q, inner) # create PDEconstrained objective functional J = TimeTracking(Q) # ROL parameters params_dict = { 'General': { 'Secant': { 'Type': 'Limited-Memory BFGS', 'Maximum Storage': 25 } }, 'Step': { 'Type': 'Trust Region' }, 'Status Test': { 'Gradient Tolerance': 1e-3, 'Step Tolerance': 1e-8, 'Iteration Limit': 20 } } # assemble and solve ROL optimization problem params = ROL.ParameterList(params_dict, "Parameters") problem = ROL.OptimizationProblem(J, q) solver = ROL.OptimizationSolver(problem, params) solver.solve() # verify that the norm of the gradient at optimum is small enough state = solver.getAlgorithmState() assert (state.gnorm < 1e-3)
import firedrake as fd import fireshape as fs import fireshape.zoo as fsz import ROL n = 30 # mesh = fd.UnitSquareMesh(n, n) mesh = fd.Mesh("UnitSquareCrossed.msh") mesh = fd.MeshHierarchy(mesh, 1)[-1] Q = fs.FeMultiGridControlSpace(mesh, refinements=3, order=2) inner = fs.LaplaceInnerProduct(Q) mesh_m = Q.mesh_m V_m = fd.FunctionSpace(mesh_m, "CG", 1) f_m = fd.Function(V_m) (x, y) = fd.SpatialCoordinate(mesh_m) f = (pow(x - 0.5, 2)) + pow(y - 0.5, 2) - 2. out = fd.File("domain.pvd") J = fsz.LevelsetFunctional(f, Q, cb=lambda: out.write(mesh_m.coordinates)) q = fs.ControlVector(Q, inner) params_dict = { 'General': { 'Secant': { 'Type': 'Limited-Memory BFGS', 'Maximum Storage': 5 } }, 'Step': {
print("Harmonic map exists for r^*/R^* = %.2f" % ((0.5 * (R / r + r / R))**-1)) Rs = 1.0 rs = args.rstar Q = fs.FeControlSpace(mesh) d = distance_function(Q.get_space_for_inner()[0].mesh(), boundary_ids=[1, 2]) if args.weighted: mu_base = 0.01 / (0.01 + d) else: mu_base = fd.Constant(1.) # mu_base = fd.Constant(1.0) if args.base_inner == "elasticity": inner = fs.ElasticityInnerProduct(Q, mu=mu_base, direct_solve=True) elif args.base_inner == "laplace": inner = fs.LaplaceInnerProduct(Q, mu=mu_base, direct_solve=True) else: raise NotImplementedError if args.alpha is not None: mu_cr = mu_base / args.alpha inner = CauchyRiemannAugmentation(mu_cr, inner) mesh_m = Q.mesh_m (x, y) = fd.SpatialCoordinate(mesh_m) r = fd.sqrt(x**2 + y**2) expr = (r - fd.Constant(rs)) * (r - fd.Constant(Rs)) J = 0.1 * fsz.LevelsetFunctional(expr, Q, quadrature_degree=5) q = fs.ControlVector(Q, inner)
fd.solve(self.F(t, self.u, self.u_old) == 0, self.u, bcs=self.bcs) t += self.dt self.J += fd.assemble(self.dt * (self.u - self.u_t(t))**2 * self.dx) def objective_value(self): """Return the value of the objective function.""" return self.J if __name__ == "__main__": # setup problem mesh = fd.UnitSquareMesh(20, 20) Q = fs.FeControlSpace(mesh) inner = fs.LaplaceInnerProduct(Q, fixed_bids=[1, 2, 3, 4]) q = fs.ControlVector(Q, inner) J = TimeTracking(Q) params_dict = { 'Step': { 'Type': 'Trust Region' }, 'General': { 'Secant': { 'Type': 'Limited-Memory BFGS', 'Maximum Storage': 25 } }, 'Status Test': { 'Gradient Tolerance': 1e-3,
import firedrake as fd import fireshape as fs import fireshape.zoo as fsz import ROL from PDEconstraint_pipe import NavierStokesSolver from objective_pipe import PipeObjective # setup problem mesh = fd.Mesh("pipe.msh") Q = fs.FeControlSpace(mesh) inner = fs.LaplaceInnerProduct(Q, fixed_bids=[10, 11, 12]) q = fs.ControlVector(Q, inner) # setup PDE constraint if mesh.topological_dimension() == 2: # in 2D viscosity = fd.Constant(1./400.) elif mesh.topological_dimension() == 3: # in 3D viscosity = fd.Constant(1/10.) # simpler problem in 3D else: raise NotImplementedError e = NavierStokesSolver(Q.mesh_m, viscosity) # save state variable evolution in file u2.pvd or u3.pvd if mesh.topological_dimension() == 2: # in 2D out = fd.File("solution/u2D.pvd") elif mesh.topological_dimension() == 3: # in 3D out = fd.File("solution/u3D.pvd") def cb(): return out.write(e.solution.split()[0])
def test_regularization(controlspace_t, use_extension): n = 10 mesh = fd.UnitSquareMesh(n, n) if controlspace_t == fs.FeMultiGridControlSpace: Q = fs.FeMultiGridControlSpace(mesh, refinements=1, order=2) else: Q = controlspace_t(mesh) if use_extension: inner = fs.SurfaceInnerProduct(Q) ext = fs.ElasticityExtension(Q.V_r) else: inner = fs.LaplaceInnerProduct(Q) ext = None q = fs.ControlVector(Q, inner, boundary_extension=ext) X = fd.SpatialCoordinate(mesh) q.fun.interpolate(0.5 * X) lower_bound = Q.T.copy(deepcopy=True) lower_bound.interpolate(fd.Constant((-0.0, -0.0))) upper_bound = Q.T.copy(deepcopy=True) upper_bound.interpolate(fd.Constant((+1.3, +0.9))) J1 = fsz.MoYoBoxConstraint(1, [1, 2, 3, 4], Q, lower_bound=lower_bound, upper_bound=upper_bound) J2 = fsz.MoYoSpectralConstraint(1, fd.Constant(0.2), Q) J3 = fsz.DeformationRegularization(Q, l2_reg=.1, sym_grad_reg=1., skew_grad_reg=.5) if isinstance(Q, fs.FeMultiGridControlSpace): J4 = fsz.CoarseDeformationRegularization(Q, l2_reg=.1, sym_grad_reg=1., skew_grad_reg=.5) Js = 0.1 * J1 + J2 + 2. * (J3 + J4) else: Js = 0.1 * J1 + J2 + 2. * J3 g = q.clone() def run_taylor_test(J): J.update(q, None, 1) J.gradient(g, q, None) return J.checkGradient(q, g, 7, 1) def check_result(test_result): for i in range(len(test_result) - 1): assert test_result[i + 1][3] <= test_result[i][3] * 0.11 check_result(run_taylor_test(J1)) check_result(run_taylor_test(J2)) check_result(run_taylor_test(J3)) if isinstance(Q, fs.FeMultiGridControlSpace): check_result(run_taylor_test(J4)) check_result(run_taylor_test(Js))
def test_box_constraint(pytestconfig): n = 5 mesh = fd.UnitSquareMesh(n, n) T = mesh.coordinates.copy(deepcopy=True) (x, y) = fd.SpatialCoordinate(mesh) T.interpolate(T + fd.Constant((1, 0)) * x * y) mesh = fd.Mesh(T) Q = fs.FeControlSpace(mesh) inner = fs.LaplaceInnerProduct(Q, fixed_bids=[1]) mesh_m = Q.mesh_m q = fs.ControlVector(Q, inner) if pytestconfig.getoption("verbose"): out = fd.File("domain.pvd") def cb(): out.write(mesh_m.coordinates) else: def cb(): pass lower_bound = Q.T.copy(deepcopy=True) lower_bound.interpolate(fd.Constant((-0.0, -0.0))) upper_bound = Q.T.copy(deepcopy=True) upper_bound.interpolate(fd.Constant((+1.3, +0.9))) J = fsz.MoYoBoxConstraint(1, [2], Q, lower_bound=lower_bound, upper_bound=upper_bound, cb=cb, quadrature_degree=100) g = q.clone() J.gradient(g, q, None) taylor_result = J.checkGradient(q, g, 9, 1) for i in range(len(taylor_result) - 1): if taylor_result[i][3] > 1e-7: assert taylor_result[i + 1][3] <= taylor_result[i][3] * 0.11 params_dict = { 'Step': { 'Type': 'Line Search', 'Line Search': { 'Descent Method': { 'Type': 'Quasi-Newton Step' } } }, 'General': { 'Secant': { 'Type': 'Limited-Memory BFGS', 'Maximum Storage': 2 } }, 'Status Test': { 'Gradient Tolerance': 1e-10, 'Step Tolerance': 1e-10, 'Iteration Limit': 150 } } params = ROL.ParameterList(params_dict, "Parameters") problem = ROL.OptimizationProblem(J, q) solver = ROL.OptimizationSolver(problem, params) solver.solve() Tvec = Q.T.vector() nodes = fd.DirichletBC(Q.V_r, fd.Constant((0.0, 0.0)), [2]).nodes assert np.all(Tvec[nodes, 0] <= 1.3 + 1e-4) assert np.all(Tvec[nodes, 1] <= 0.9 + 1e-4)
def test_objective_plus_box_constraint(pytestconfig): n = 10 mesh = fd.UnitSquareMesh(n, n) T = mesh.coordinates.copy(deepcopy=True) (x, y) = fd.SpatialCoordinate(mesh) T.interpolate(T + fd.Constant((0, 0))) mesh = fd.Mesh(T) Q = fs.FeControlSpace(mesh) inner = fs.LaplaceInnerProduct(Q) mesh_m = Q.mesh_m q = fs.ControlVector(Q, inner) if pytestconfig.getoption("verbose"): out = fd.File("domain.pvd") def cb(): out.write(mesh_m.coordinates) else: def cb(): pass lower_bound = Q.T.copy(deepcopy=True) lower_bound.interpolate(fd.Constant((-0.2, -0.2))) upper_bound = Q.T.copy(deepcopy=True) upper_bound.interpolate(fd.Constant((+1.2, +1.2))) # levelset test case (x, y) = fd.SpatialCoordinate(Q.mesh_m) f = (pow(x - 0.5, 2)) + pow(y - 0.5, 2) - 4. J1 = fsz.LevelsetFunctional(f, Q, cb=cb, quadrature_degree=10) J2 = fsz.MoYoBoxConstraint(10., [1, 2, 3, 4], Q, lower_bound=lower_bound, upper_bound=upper_bound, cb=cb, quadrature_degree=10) J3 = fsz.MoYoSpectralConstraint(100, fd.Constant(0.6), Q, cb=cb, quadrature_degree=100) J = 0.1 * J1 + J2 + J3 g = q.clone() J.gradient(g, q, None) taylor_result = J.checkGradient(q, g, 9, 1) for i in range(len(taylor_result) - 1): if taylor_result[i][3] > 1e-6 and taylor_result[i][3] < 1e-3: assert taylor_result[i + 1][3] <= taylor_result[i][3] * 0.15 params_dict = { 'Step': { 'Type': 'Line Search', 'Line Search': { 'Descent Method': { 'Type': 'Quasi-Newton Step' } } }, 'General': { 'Secant': { 'Type': 'Limited-Memory BFGS', 'Maximum Storage': 2 } }, 'Status Test': { 'Gradient Tolerance': 1e-10, 'Step Tolerance': 1e-10, 'Iteration Limit': 10 } } params = ROL.ParameterList(params_dict, "Parameters") problem = ROL.OptimizationProblem(J, q) solver = ROL.OptimizationSolver(problem, params) solver.solve() Tvec = Q.T.vector() nodes = fd.DirichletBC(Q.V_r, fd.Constant((0.0, 0.0)), [2]).nodes assert np.all(Tvec[nodes, 0] <= 1.2 + 1e-1) assert np.all(Tvec[nodes, 1] <= 1.2 + 1e-1)
def test_spectral_constraint(pytestconfig): n = 5 mesh = fd.UnitSquareMesh(n, n) T = fd.Function(fd.VectorFunctionSpace( mesh, "CG", 1)).interpolate(fd.SpatialCoordinate(mesh) - fd.Constant((0.5, 0.5))) mesh = fd.Mesh(T) Q = fs.FeControlSpace(mesh) inner = fs.LaplaceInnerProduct(Q) mesh_m = Q.mesh_m q = fs.ControlVector(Q, inner) if pytestconfig.getoption("verbose"): out = fd.File("domain.pvd") def cb(): out.write(mesh_m.coordinates) else: def cb(): pass J = fsz.MoYoSpectralConstraint(0.5, fd.Constant(0.1), Q, cb=cb) q.fun += Q.T g = q.clone() J.update(q, None, -1) J.gradient(g, q, None) cb() taylor_result = J.checkGradient(q, g, 7, 1) for i in range(len(taylor_result) - 1): assert taylor_result[i + 1][3] <= taylor_result[i][3] * 0.11 params_dict = { 'General': { 'Secant': { 'Type': 'Limited-Memory BFGS', 'Maximum Storage': 2 } }, 'Step': { 'Type': 'Line Search', 'Line Search': { 'Descent Method': { 'Type': 'Quasi-Newton Step' } } }, 'Status Test': { 'Gradient Tolerance': 1e-10, 'Step Tolerance': 1e-10, 'Iteration Limit': 150 } } params = ROL.ParameterList(params_dict, "Parameters") problem = ROL.OptimizationProblem(J, q) solver = ROL.OptimizationSolver(problem, params) solver.solve() Tvec = Q.T.vector()[:, :] for i in range(Tvec.shape[0]): assert abs(Tvec[i, 0]) < 0.55 + 1e-4 assert abs(Tvec[i, 1]) < 0.55 + 1e-4 assert np.any(np.abs(Tvec) > 0.55 - 1e-4)
use_cr = bool(args.use_cr) base_inner = args.base_inner mesh = fd.Mesh("Sphere2D.msh") Q = fs.FeControlSpace(mesh) d = distance_function(Q.get_space_for_inner()[0].mesh(), eps=fd.Constant(0.1)) mu_base = 0.01 / (0.01 + d) if base_inner == "elasticity": inner = fs.ElasticityInnerProduct(Q, fixed_bids=[1, 2, 3], mu=mu_base, direct_solve=True) elif base_inner == "laplace": inner = fs.LaplaceInnerProduct(Q, fixed_bids=[1, 2, 3], mu=mu_base, direct_solve=True) else: raise NotImplementedError if use_cr: mu_cr = 100.0 * mu_base inner = CauchyRiemannAugmentation(mu_cr, inner) mesh_m = Q.mesh_m (x, y) = fd.SpatialCoordinate(mesh_m) inflow_expr = fd.Constant((1.0, 0.0)) e = fsz.StokesSolver(mesh_m, inflow_bids=[1, 2, 3], inflow_expr=inflow_expr, noslip_bids=[4],