def test_checkpointing(controlspace_t): mesh = fd.UnitSquareMesh(5, 5) if controlspace_t == fs.BsplineControlSpace: bbox = [(-1, 2), (-1, 2)] orders = [2, 2] levels = [4, 4] Q = fs.BsplineControlSpace(mesh, bbox, orders, levels) elif controlspace_t == fs.FeMultiGridControlSpace: Q = fs.FeMultiGridControlSpace(mesh, refinements=1, order=2) else: Q = controlspace_t(mesh) inner = fs.H1InnerProduct(Q) q = fs.ControlVector(Q, inner) p = fs.ControlVector(Q, inner) from firedrake.petsc import PETSc rand = PETSc.Random().create(mesh.comm) rand.setInterval((1, 2)) q.vec_wo().setRandom(rand) Q.store(q) Q.load(p) assert q.norm() > 0 assert abs(q.norm()-p.norm()) < 1e-14 p.axpy(-1, q) assert p.norm() < 1e-14
def mh_cb(mh_r): fd.File("output/fine_init.pvd").write(mh_r[-1].coordinates) fd.File("output/coarse_init.pvd").write(mh_r[0].coordinates) # sys.exit() d = distance_function(mh_r[0]) mu = 0.01 / (d + 0.01) extension[0] = fs.ElasticityForm(mu=mu) if args.cr > 0: mu_cr = args.cr * mu extension[0] = fs.CauchyRiemannAugmentation(extension[0], mu=mu_cr) if args.htwo > 0: mu_c1 = fd.Constant(args.htwo) extension[0] = C1Regulariser(extension[0], mu=mu_c1) if args.surf: Q[0] = fs.ScalarFeMultiGridControlSpace(mh_r, extension[0], order=args.order, fixed_bids=fixed_bids) else: Q[0] = fs.FeMultiGridControlSpace(mh_r, order=args.order) return Q[0].mh_m
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': {
def test_levelset(dim, inner_t, controlspace_t, use_extension, pytestconfig): verbose = pytestconfig.getoption("verbose") """ Test template for fsz.LevelsetFunctional.""" clscale = 0.1 if dim == 2 else 0.2 # make the mesh a bit coarser if we are using a multigrid control space as # we are refining anyway if controlspace_t == fs.FeMultiGridControlSpace: clscale *= 4 if dim == 2: mesh = fs.DiskMesh(clscale) elif dim == 3: mesh = fs.SphereMesh(clscale) else: raise NotImplementedError if controlspace_t == fs.BsplineControlSpace: if dim == 2: bbox = [(-2, 2), (-2, 2)] orders = [2, 2] levels = [4, 4] else: bbox = [(-3, 3), (-3, 3), (-3, 3)] orders = [2, 2, 2] levels = [3, 3, 3] Q = fs.BsplineControlSpace(mesh, bbox, orders, levels) elif controlspace_t == fs.FeMultiGridControlSpace: Q = fs.FeMultiGridControlSpace(mesh, refinements=1, order=2) else: Q = controlspace_t(mesh) inner = inner_t(Q) # if running with -v or --verbose, then export the shapes if verbose: out = fd.File("domain.pvd") def cb(*args): out.write(Q.mesh_m.coordinates) cb() else: cb = None # levelset test case if dim == 2: (x, y) = fd.SpatialCoordinate(Q.mesh_m) f = (pow(x, 2)) + pow(1.3 * y, 2) - 1. elif dim == 3: (x, y, z) = fd.SpatialCoordinate(Q.mesh_m) f = (pow(x, 2)) + pow(0.8 * y, 2) + pow(1.3 * z, 2) - 1. else: raise NotImplementedError J = fsz.LevelsetFunctional(f, Q, cb=cb, scale=0.1) if use_extension == "w_ext": ext = fs.ElasticityExtension(Q.V_r) if use_extension == "w_ext_fixed_dim": ext = fs.ElasticityExtension(Q.V_r, fixed_dims=[0]) else: ext = None q = fs.ControlVector(Q, inner, boundary_extension=ext) # these tolerances are not very stringent, but solutions are correct with # tighter tolerances, the combination # FeMultiGridControlSpace-ElasticityInnerProduct fails because the mesh # self-intersects (one should probably be more careful with the opt params) grad_tol = 1e-1 itlim = 15 itlimsub = 15 # Volume constraint vol = fsz.LevelsetFunctional(fd.Constant(1.0), Q, scale=1) initial_vol = vol.value(q, None) econ = fs.EqualityConstraint([vol], target_value=[initial_vol]) emul = ROL.StdVector(1) # ROL parameters params_dict = { 'Step': { 'Type': 'Augmented Lagrangian', 'Augmented Lagrangian': { 'Subproblem Step Type': 'Line Search', 'Penalty Parameter Growth Factor': 1.05, 'Print Intermediate Optimization History': True, 'Subproblem Iteration Limit': itlimsub }, 'Line Search': { 'Descent Method': { 'Type': 'Quasi-Newton Step' } }, }, 'General': { 'Secant': { 'Type': 'Limited-Memory BFGS', 'Maximum Storage': 50 } }, 'Status Test': { 'Gradient Tolerance': grad_tol, 'Step Tolerance': 1e-10, 'Iteration Limit': itlim } } params = ROL.ParameterList(params_dict, "Parameters") problem = ROL.OptimizationProblem(J, q, econ=econ, emul=emul) solver = ROL.OptimizationSolver(problem, params) solver.solve() # verify that the norm of the gradient at optimum is small enough # and that the volume has not changed too much state = solver.getAlgorithmState() assert (state.gnorm < grad_tol) assert abs(vol.value(q, None) - initial_vol) < 1e-2
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_levelset(dim, inner_t, controlspace_t, use_extension, pytestconfig): verbose = pytestconfig.getoption("verbose") """ Test template for fsz.LevelsetFunctional.""" clscale = 0.1 if dim == 2 else 0.2 # make the mesh a bit coarser if we are using a multigrid control space as # we are refining anyway if controlspace_t == fs.FeMultiGridControlSpace: clscale *= 2 if dim == 2: mesh = fs.DiskMesh(clscale) elif dim == 3: mesh = fs.SphereMesh(clscale) else: raise NotImplementedError if controlspace_t == fs.BsplineControlSpace: if dim == 2: bbox = [(-2, 2), (-2, 2)] orders = [2, 2] levels = [4, 4] else: bbox = [(-3, 3), (-3, 3), (-3, 3)] orders = [2, 2, 2] levels = [3, 3, 3] Q = fs.BsplineControlSpace(mesh, bbox, orders, levels) elif controlspace_t == fs.FeMultiGridControlSpace: Q = fs.FeMultiGridControlSpace(mesh, refinements=1, order=2) else: Q = controlspace_t(mesh) inner = inner_t(Q) # if running with -v or --verbose, then export the shapes if verbose: out = fd.File("domain.pvd") def cb(*args): out.write(Q.mesh_m.coordinates) cb() else: cb = None # levelset test case if dim == 2: (x, y) = fd.SpatialCoordinate(Q.mesh_m) f = (pow(x, 2)) + pow(1.3 * y, 2) - 1. elif dim == 3: (x, y, z) = fd.SpatialCoordinate(Q.mesh_m) f = (pow(x, 2)) + pow(0.8 * y, 2) + pow(1.3 * z, 2) - 1. else: raise NotImplementedError J = fsz.LevelsetFunctional(f, Q, cb=cb, scale=0.1) if use_extension == "w_ext": ext = fs.ElasticityExtension(Q.V_r) if use_extension == "w_ext_fixed_dim": ext = fs.ElasticityExtension(Q.V_r, fixed_dims=[0]) else: ext = None q = fs.ControlVector(Q, inner, boundary_extension=ext) """ move mesh a bit to check that we are not doing the taylor test in T=id """ g = q.clone() J.gradient(g, q, None) q.plus(g) J.update(q, None, 1) """ Start taylor test """ J.gradient(g, q, None) res = J.checkGradient(q, g, 5, 1) errors = [l[-1] for l in res] assert (errors[-1] < 0.11 * errors[-2]) q.scale(0) """ End taylor test """ grad_tol = 1e-6 if dim == 2 else 1e-4 # ROL parameters params_dict = { 'General': { 'Secant': { 'Type': 'Limited-Memory BFGS', 'Maximum Storage': 50 } }, 'Step': { 'Type': 'Line Search', 'Line Search': { 'Descent Method': { 'Type': 'Quasi-Newton Step' } } }, 'Status Test': { 'Gradient Tolerance': grad_tol, 'Step Tolerance': 1e-10, 'Iteration Limit': 150 } } # 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 < grad_tol)