예제 #1
0
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
예제 #2
0
import firedrake as fd
import fireshape as fs
import fireshape.zoo as fsz
import ROL

dim = 2
mesh = fs.DiskMesh(0.4)
Q = fs.FeMultiGridControlSpace(mesh, refinements=4, order=2)
# Q = fs.FeControlSpace(mesh)
# inner = fs.SurfaceInnerProduct(Q)
inner = fs.ElasticityInnerProduct(Q)
extension = fs.ElasticityExtension(Q.V_r, direct_solve=True)

mesh_m = Q.mesh_m

if dim == 2:
    (x, y) = fd.SpatialCoordinate(mesh_m)
    f = (pow(x, 2)) + pow(0.5 * y, 2) - 1.
else:
    (x, y, z) = fd.SpatialCoordinate(mesh_m)
    f = (pow(x - 0.5, 2)) + pow(y - 0.5, 2) + pow(z - 0.5, 2) - 2.

q = fs.ControlVector(Q, inner, boundary_extension=extension)
out = fd.File("domain.pvd")
J = fsz.LevelsetFunctional(f, Q, cb=lambda: out.write(mesh_m.coordinates))
J.cb()
g = q.clone()
J.update(q, None, 1)
J.gradient(g, q, None)
g.scale(-0.3)
J.update(g, None, 1)
예제 #3
0
def test_periodic(dim, inner_t, use_extension, pytestconfig):
    verbose = pytestconfig.getoption("verbose")
    """ Test template for PeriodicControlSpace."""

    if dim == 2:
        mesh = fd.PeriodicUnitSquareMesh(30, 30)
    elif dim == 3:
        mesh = fd.PeriodicUnitCubeMesh(20, 20, 20)
    else:
        raise NotImplementedError

    Q = fs.FeControlSpace(mesh)

    inner = inner_t(Q)

    # levelset test case
    V = fd.FunctionSpace(Q.mesh_m, "DG", 0)
    sigma = fd.Function(V)
    if dim == 2:
        x, y = fd.SpatialCoordinate(Q.mesh_m)
        g = fd.sin(y * np.pi)  # truncate at bdry
        f = fd.cos(2 * np.pi * x) * g
        perturbation = 0.05 * fd.sin(x * np.pi) * g**2
        sigma.interpolate(g * fd.cos(2 * np.pi * x * (1 + perturbation)))
    elif dim == 3:
        x, y, z = fd.SpatialCoordinate(Q.mesh_m)
        g = fd.sin(y * np.pi) * fd.sin(z * np.pi)  # truncate at bdry
        f = fd.cos(2 * np.pi * x) * g
        perturbation = 0.05 * fd.sin(x * np.pi) * g**2
        sigma.interpolate(g * fd.cos(2 * np.pi * x * (1 + perturbation)))
    else:
        raise NotImplementedError

    class LevelsetFct(fs.ShapeObjective):
        def __init__(self, sigma, f, *args, **kwargs):
            super().__init__(*args, **kwargs)

            self.sigma = sigma  # initial
            self.f = f  # target
            Vdet = fd.FunctionSpace(Q.mesh_r, "DG", 0)
            self.detDT = fd.Function(Vdet)

        def value_form(self):
            # volume integral
            self.detDT.interpolate(fd.det(fd.grad(self.Q.T)))
            if min(self.detDT.vector()) > 0.05:
                integrand = (self.sigma - self.f)**2
            else:
                integrand = np.nan * (self.sigma - self.f)**2
            return integrand * fd.dx(metadata={"quadrature_degree": 1})

    # if running with -v or --verbose, then export the shapes
    if verbose:
        out = fd.File("sigma.pvd")

        def cb(*args):
            out.write(sigma)
    else:
        cb = None
    J = LevelsetFct(sigma, f, Q, cb=cb)

    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 """

    # ROL parameters
    grad_tol = 1e-4
    params_dict = {
        'Step': {
            'Type': 'Trust Region'
        },
        'General': {
            'Secant': {
                'Type': 'Limited-Memory BFGS',
                'Maximum Storage': 25
            }
        },
        'Status Test': {
            'Gradient Tolerance': grad_tol,
            'Step Tolerance': 1e-10,
            'Iteration Limit': 40
        }
    }

    # 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)
예제 #4
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))
예제 #5
0
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)