Ejemplo n.º 1
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.º 2
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.º 3
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)
                    choices=["elasticity", "laplace"])
parser.add_argument("--alpha", type=float, default=None)
parser.add_argument("--clscale", type=float, default=0.1)
parser.add_argument("--maxiter", type=int, default=50)
parser.add_argument("--weighted", default=False, action="store_true")
parser.add_argument("--rstar", type=float, default=0.79)
args = parser.parse_args()

mesh = fd.Mesh("annulus.msh")
R = 1.0
r = 0.5
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:
Ejemplo n.º 5
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.º 6
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.º 7
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.º 8
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)