Esempio n. 1
0
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
Esempio n. 2
0
def test_vectorkron():
    """ Collection of tests."""

    mesh = fd.UnitSquareMesh(1, 1)
    bbox = [(0, 1), (0, 1)]
    orders = [2, 2]
    levels = [2, 2]
    Q = fs.BsplineControlSpace(mesh, bbox, orders, levels)

    # test
    A = sp.sparse.csr_matrix(np.array([[0, 5, 7, 0, 9]]))
    B = sp.sparse.csr_matrix(np.array([[1, 2, 0]]))
    mytest_vectorkron(Q, A, B)

    # test
    A = sp.sparse.csr_matrix(np.array([[0, 2, 0, 5, 6]]))
    B = sp.sparse.csr_matrix(np.array([[0, 2, 0, 5, 6]]))
    mytest_vectorkron(Q, A, B)

    # test
    A = sp.sparse.csr_matrix(np.array([[]]))
    B = sp.sparse.csr_matrix(np.array([[0, 2, 0, 5, 6]]))
    mytest_vectorkron(Q, A, B)

    # test
    A = sp.sparse.csr_matrix(np.array([[1, 1.1, 10, 0, 2, 0, 5, 6]]))
    B = sp.sparse.csr_matrix(np.array([[0, 2, 0, -3, 6]]))
    mytest_vectorkron(Q, A, B)

    # test
    A = sp.sparse.csr_matrix(np.array([[0, 2, 0, 5, 6]]))
    B = sp.sparse.csr_matrix(np.array([[]]))
    mytest_vectorkron(Q, A, B)

    # test
    A = sp.sparse.csr_matrix(np.array([[0, 5, 6]]))
    B = sp.sparse.csr_matrix(np.array([[1e3, 0, 2, 0, 5, 6]]))
    mytest_vectorkron(Q, A, B)
Esempio n. 3
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
Esempio n. 4
0
import firedrake as fd
import fireshape.zoo as fsz
import fireshape as fs
import ROL

mesh = fs.DiskMesh(0.1)

bbox = [(-1.01, 1.01), (-1.01, 1.01)]
orders = [3, 3]
levels = [4, 4]
Q = fs.BsplineControlSpace(mesh,
                           bbox,
                           orders,
                           levels,
                           boundary_regularities=[0, 0])
inner = fs.H1InnerProduct(Q)
q = fs.ControlVector(Q, inner)

mesh_m = Q.mesh_m
(x, y) = fd.SpatialCoordinate(mesh_m)

f = (pow(x, 2)) + pow(2 * y, 2) - 1
outdef = fd.File("deformation.pvd")
out = fd.File("domain.pvd")
V, I = Q.get_space_for_inner()
T = fd.Function(V)


def cb():
    out.write(mesh_m.coordinates)
    Q.visualize_control(q, T)
Esempio n. 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)