Ejemplo 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
Ejemplo n.º 2
0
def run_L2tracking_optimization(write_output=False):
    """ Test template for fsz.LevelsetFunctional."""

    # tool for developing new tests, allows storing shape iterates
    if write_output:
        out = fd.File("domain.pvd")

        def cb(*args):
            out.write(Q.mesh_m.coordinates)

        cb()
    else:
        cb = None

    # setup problem
    mesh = fd.UnitSquareMesh(30, 30)
    Q = fs.FeControlSpace(mesh)
    inner = fs.ElasticityInnerProduct(Q)
    q = fs.ControlVector(Q, inner)

    # setup PDE constraint
    mesh_m = Q.mesh_m
    e = PoissonSolver(mesh_m)

    # create PDEconstrained objective functional
    J_ = L2trackingObjective(e, Q, cb=cb)
    J = fs.ReducedObjective(J_, e)

    # ROL parameters
    params_dict = {
        'General': {
            'Secant': {
                'Type': 'Limited-Memory BFGS',
                'Maximum Storage': 10
            }
        },
        'Step': {
            'Type': 'Line Search',
            'Line Search': {
                'Descent Method': {
                    'Type': 'Quasi-Newton Step'
                }
            },
        },
        'Status Test': {
            'Gradient Tolerance': 1e-4,
            'Step Tolerance': 1e-5,
            'Iteration Limit': 15
        }
    }

    # 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-4)
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
# 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': {
        'Type': 'Line Search',
        'Line Search': {
            'Descent Method': {
                'Type': 'Quasi-Newton Step'
            }
        }
Ejemplo n.º 6
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
Ejemplo n.º 7
0
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)
J.checkGradient(q, g, 9, 1)

params_dict = {
    'General': {
        'Secant': {
            'Type': 'Limited-Memory BFGS',
            'Maximum Storage': 25
Ejemplo n.º 8
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))
Ejemplo n.º 9
0
out = fd.File("output/%s.pvd" % label)

if args.spectral:
    Js = fsz.MoYoSpectralConstraint(1e3, fd.Constant(0.5), Q)
    J = J + Js
if args.tikhonov > 0:
    Jt = args.tikhonov * fsz.CoarseDeformationRegularization(extension, Q)
    J = J + Jt

if args.smooth:
    control_constraint = fs.InteriorControlConstraint(Q.V_r_coarse,
                                                      form=extension)
else:
    dirichlet_extension = None
    control_constraint = None
q = fs.ControlVector(Q, innerp, control_constraint=control_constraint)
vol = fsz.LevelsetFunctional(fd.Constant(10.0), Q)
if args.problem == "pipe":
    econ_unscaled = fs.EqualityConstraint([vol])

    def wrap(f):
        return fs.DeformationCheckObjective(
            f,
            delta_threshold=0.25 if args.dim == 2 else 0.25,  # noqa
            strict=False)

    scale = 1e1
    J = wrap(scale * J)
    volweight = 0.1 if args.dim == 2 else 1.
    vol = wrap(volweight * scale**0.5 * vol)
    econ = fs.EqualityConstraint([vol])
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
0
    mu_cr = mu_base / args.alpha
    inner = CauchyRiemannAugmentation(mu_cr, inner)

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

a = 0.8
b = 2.0

expr = (fd.sqrt((x - a)**2 + b * y**2) - 1) \
    * (fd.sqrt((x + a)**2 + b * y**2) - 1) \
    * (fd.sqrt(b * x**2 + (y - a)**2) - 1) \
    * (fd.sqrt(b * x**2 + (y + a)**2) - 1) - 0.001

J = 0.1 * fsz.LevelsetFunctional(expr, Q, quadrature_degree=5)
q = fs.ControlVector(Q, inner)

params_dict = {
    "General": {
        "Secant": {
            "Type": "Limited-Memory BFGS",
            "Maximum Storage": 1
        }
    },
    "Step": {
        "Type": "Line Search",
        "Line Search": {
            "Descent Method": {
                "Type": "Quasi-Newton Step"
            }
        }
Ejemplo n.º 14
0
if not os.path.exists(directory):
    os.makedirs(directory, exist_ok=True)
out = fd.File(directory + "u.pvd")

vol = fsz.LevelsetFunctional(fd.Constant(1.0), Q)
baryx = fsz.LevelsetFunctional(x, Q)
baryy = fsz.LevelsetFunctional(y, Q)
econ = fs.EqualityConstraint([vol, baryx, baryy])
emul = ROL.StdVector(3)
econ_val = ROL.StdVector(3)

Je = fsz.EnergyObjective(e, Q, cb=None)
Jr = fs.ReducedObjective(Je, e)
# J = 2e-4 * Jr
J = 1e-2 * Jr
q = fs.ControlVector(Q, inner)

params_dict = {
    "General": {
        "Secant": {
            "Type": "Limited-Memory BFGS",
            "Maximum Storage": 5
        }
    },
    "Step": {
        "Type": "Augmented Lagrangian",
        "Line Search": {
            "Descent Method": {
                "Type": "Quasi-Newton Step"
            }
        },
Ejemplo n.º 15
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)
Ejemplo n.º 16
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)