Example #1
0
def error(config, eta0, k):
  state = Function(config.function_space)
  state.interpolate(SinusoidalInitialCondition(config, eta0, k, config.params["depth"]))
  u_exact = "eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t)" # The analytical veclocity of the shallow water equations has been multiplied by depth to account for the change of variable (\tilde u = depth u) in this code.
  ddu_exact = "(diffusion_coef * eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t) * k*k)"
  eta_exact = "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"
  # The source term
  source = Expression((ddu_exact, 
                       "0.0"), \
                       eta0 = eta0, g = config.params["g"], \
                       depth = config.params["depth"], t = config.params["current_time"], \
                       k = k, diffusion_coef = config.params["diffusion_coef"])

  adj_reset()
  shallow_water_model.sw_solve(config, state, annotate=False, u_source = source)

  analytic_sol = Expression((u_exact, \
                             "0", \
                             eta_exact), \
                             eta0=eta0, g=config.params["g"], \
                             depth=config.params["depth"], t=config.params["current_time"], k=k)
  exactstate = Function(config.function_space)
  exactstate.interpolate(analytic_sol)
  e = state - exactstate
  return sqrt(assemble(dot(e,e)*dx))
    def evaluate(self, annotate=True):
        """ Computes the functional value by running the forward model. """

        log(INFO, 'Start evaluation of j')
        timer = Timer("j evaluation")

        farm = self.solver.problem.parameters.tidal_farm

        # Configure dolfin-adjoint
        adj_reset()
        parameters["adjoint"]["record_all"] = True

        # Solve the shallow water system and integrate the functional of
        # interest.
        final_only = (not self.solver.problem._is_transient
                      or self._problem_params.functional_final_time_only)
        self.time_integrator = TimeIntegrator(self.solver.problem,
                                              self._functional, final_only)

        for sol in self.solver.solve(annotate=annotate):
            self.time_integrator.add(sol["time"], sol["state"], sol["tf"],
                                     sol["is_final"])

        j = self.time_integrator.integrate()

        timer.stop()

        log(INFO, 'Runtime: %f s.' % timer.elapsed()[0])
        log(INFO, 'j = %e.' % float(j))

        return j
Example #3
0
def error(config, eta0, k):
    state = Function(config.function_space)
    state.interpolate(
        SinusoidalInitialCondition(config, eta0, k, config.params["depth"]))
    u_exact = "eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t)"
    du_exact = "(- eta0*sqrt(g/depth) * sin(k*x[0]-sqrt(g*depth)*k*t) * k)"
    eta_exact = "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"
    # The source term
    source = Expression((u_exact + " * " + du_exact,
                               "0.0"), \
                               eta0=eta0, g=config.params["g"], \
                               depth=config.params["depth"], t=config.params["current_time"], k=k)

    adj_reset()
    shallow_water_model.sw_solve(config,
                                 state,
                                 annotate=False,
                                 u_source=source)

    analytic_sol = Expression((u_exact, \
                               "0", \
                               eta_exact), \
                               eta0=eta0, g=config.params["g"], \
                               depth=config.params["depth"], t=config.params["current_time"], k=k)
    exactstate = Function(config.function_space)
    exactstate.interpolate(analytic_sol)
    e = state - exactstate
    return sqrt(assemble(dot(e, e) * dx))
def error(config, eta0, k):
  state = Function(config.function_space)
  state.interpolate(SinusoidalInitialCondition(config, eta0, k, config.params["depth"]))
  u_exact = "eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t)" 
  du_exact = "(- eta0*sqrt(g/depth) * sin(k*x[0]-sqrt(g*depth)*k*t) * k)"
  ddu_exact = "(diffusion_coef * eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t) * k*k)"
  eta_exact = "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"
  friction = "friction/depth * " + u_exact + "*pow(pow(" + u_exact + ", 2), 0.5)"
  # The source term
  source = Expression((u_exact + " * " + du_exact + " + " + ddu_exact + " + " + friction, 
                             "0.0"), \
                             eta0 = eta0, g = config.params["g"], \
                             depth = config.params["depth"], t = config.params["current_time"], \
                             k = k, diffusion_coef = config.params["diffusion_coef"],
                             friction = config.params["friction"])

  adj_reset()
  shallow_water_model.sw_solve(config, state, annotate=False, u_source = source)

  analytic_sol = Expression((u_exact, \
                             "0", \
                             eta_exact), \
                             eta0=eta0, g=config.params["g"], \
                             depth=config.params["depth"], t=config.params["current_time"], k=k)
  exactstate = Function(config.function_space)
  exactstate.interpolate(analytic_sol)
  e = state - exactstate
  enorm = sqrt(assemble(dot(e,e)*dx))
  print enorm
  return enorm 
def error(config, eta0, k):
    state = Function(config.function_space)
    state.interpolate(
        SinusoidalInitialCondition(config, eta0, k, config.params["depth"]))
    u_exact = "eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t)"
    du_exact = "(- eta0*sqrt(g/depth) * sin(k*x[0]-sqrt(g*depth)*k*t) * k)"
    ddu_exact = "(diffusion_coef * eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t) * k*k)"
    eta_exact = "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"
    friction = "friction/depth * " + u_exact + "*pow(pow(" + u_exact + ", 2), 0.5)"
    # The source term
    source = Expression((u_exact + " * " + du_exact + " + " + ddu_exact + " + " + friction,
                               "0.0"), \
                               eta0 = eta0, g = config.params["g"], \
                               depth = config.params["depth"], t = config.params["current_time"], \
                               k = k, diffusion_coef = config.params["diffusion_coef"],
                               friction = config.params["friction"])

    adj_reset()
    shallow_water_model.sw_solve(config,
                                 state,
                                 annotate=False,
                                 u_source=source)

    analytic_sol = Expression((u_exact, \
                               "0", \
                               eta_exact), \
                               eta0 = eta0, g = config.params["g"], \
                               depth=config.params["depth"], t=config.params["current_time"], k=k)
    exactstate = Function(config.function_space)
    exactstate.interpolate(analytic_sol)
    e = state - exactstate
    enorm = sqrt(assemble(dot(e, e) * dx))
    print enorm
    return enorm
Example #6
0
    def evaluate(self, annotate=True):
        """ Computes the functional value by running the forward model. """

        log(INFO, 'Start evaluation of j')
        timer = Timer("j evaluation")

        farm = self.solver.problem.parameters.tidal_farm

        # Configure dolfin-adjoint
        adj_reset()
        parameters["adjoint"]["record_all"] = True

        # Solve the shallow water system and integrate the functional of
        # interest.
        final_only = (not self.solver.problem._is_transient or
                      self._problem_params.functional_final_time_only)
        self.time_integrator = TimeIntegrator(self.solver.problem,
                                              self._functional, final_only)

        for sol in self.solver.solve(annotate=annotate):
            self.time_integrator.add(sol["time"], sol["state"], sol["tf"],
                                     sol["is_final"])

        j = self.time_integrator.integrate()

        timer.stop()

        log(INFO, 'Runtime: %f s.' % timer.elapsed()[0])
        log(INFO, 'j = %e.' % float(j))

        return j
Example #7
0
def error(config, eta0, k):
    state = Function(config.function_space)
    state.interpolate(SinusoidalInitialCondition(config, eta0, k, config.params["depth"]))
    u_exact = "eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t)"
    du_exact = "(- eta0*sqrt(g/depth) * sin(k*x[0]-sqrt(g*depth)*k*t) * k)"
    eta_exact = "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"
    # The source term
    source = Expression(
        (u_exact + " * " + du_exact, "0.0"),
        eta0=eta0,
        g=config.params["g"],
        depth=config.params["depth"],
        t=config.params["current_time"],
        k=k,
    )

    adj_reset()
    shallow_water_model.sw_solve(config, state, annotate=False, u_source=source)

    analytic_sol = Expression(
        (u_exact, "0", eta_exact),
        eta0=eta0,
        g=config.params["g"],
        depth=config.params["depth"],
        t=config.params["current_time"],
        k=k,
    )
    exactstate = Function(config.function_space)
    exactstate.interpolate(analytic_sol)
    e = state - exactstate
    return sqrt(assemble(dot(e, e) * dx))
Example #8
0
def error(config, eta0, k):
    state = Function(config.function_space)
    state.interpolate(
        SinusoidalInitialCondition(config, eta0, k, config.params["depth"]))
    u_exact = "eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t)"  # The analytical veclocity of the shallow water equations has been multiplied by depth to account for the change of variable (\tilde u = depth u) in this code.
    ddu_exact = "(diffusion_coef * eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t) * k*k)"
    eta_exact = "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"
    # The source term
    source = Expression((ddu_exact,
                         "0.0"), \
                         eta0 = eta0, g = config.params["g"], \
                         depth = config.params["depth"], t = config.params["current_time"], \
                         k = k, diffusion_coef = config.params["diffusion_coef"])

    adj_reset()
    shallow_water_model.sw_solve(config,
                                 state,
                                 annotate=False,
                                 u_source=source)

    analytic_sol = Expression((u_exact, \
                               "0", \
                               eta_exact), \
                               eta0=eta0, g=config.params["g"], \
                               depth=config.params["depth"], t=config.params["current_time"], k=k)
    exactstate = Function(config.function_space)
    exactstate.interpolate(analytic_sol)
    e = state - exactstate
    return sqrt(assemble(dot(e, e) * dx))
Example #9
0
def pytest_runtest_setup(item):
    """ Hook function which is called before every test """

    # Reset dolfin parameter dictionary
    dolfin.parameters.update(default_params)

    # Reset adjoint state
    dolfin_adjoint.adj_reset()
Example #10
0
def pytest_runtest_setup(item):
    """ Hook function which is called before every test """

    # Reset dolfin parameter dictionary
    dolfin.parameters.update(default_params)

    # Reset adjoint state
    dolfin_adjoint.adj_reset()
Example #11
0
def setup_model(parameters, sin_ic, time_step, finish_time, mesh_x, mesh_y=2):
    # Note: The analytical solution is constant in the
    # y-direction, hence a coarse y-resolution is sufficient.

    # Reset the adjoint tape to keep dolfin-adjoint happy
    adj_reset()

    eta0 = 2.0
    k = pi / 3000.

    # Temporal settings
    parameters.start_time = Constant(0)
    parameters.finish_time = Constant(finish_time)
    parameters.dt = Constant(time_step)

    # Finite element
    parameters.finite_element = finite_elements.p1dgp2

    # Use Crank-Nicolson to get a second-order time-scheme
    parameters.theta = Constant(0.5)

    # Activate the relevant terms
    parameters.include_advection = True
    parameters.include_viscosity = False
    parameters.linear_divergence = True

    # Physical settings
    parameters.friction = Constant(0.25)
    parameters.viscosity = Constant(0.0)
    parameters.domain = domains.RectangularDomain(0, 0, 3000, 1000, mesh_x,
                                                  mesh_y)

    # Initial condition
    ic_expr = sin_ic(eta0=eta0,
                     k=k,
                     depth=parameters.depth,
                     start_time=parameters.start_time,
                     degree=2)
    parameters.initial_condition = ic_expr

    # Set the analytical boundary conditions
    flather_expr = Expression(
        ("2*eta0*sqrt(g/depth)*cos(-sqrt(g*depth)*k*t)", "0"),
        eta0=eta0,
        g=parameters.g,
        depth=parameters.depth,
        t=Constant(parameters.start_time),
        k=k,
        degree=2)

    bcs = BoundaryConditionSet()
    bcs.add_bc("u", flather_expr, facet_id=[1, 2], bctype="flather")
    bcs.add_bc("u", facet_id=3, bctype="free_slip")
    parameters.bcs = bcs

    return parameters, eta0, k
Example #12
0
def pytest_runtest_setup(item):
    """ Hook function which is called before every test """

    # Reset dolfin parameter dictionary
    dolfin.parameters.update(default_params)

    # Reset adjoint state
    dolfin_adjoint.adj_reset()

    # Fix the seed to avoid random test failures due to slight tolerance variations
    random.seed(21)
Example #13
0
def pytest_runtest_setup(item):
    """ Hook function which is called before every test """

    # Reset dolfin parameter dictionary
    dolfin.parameters.update(default_params)

    # Reset adjoint state
    dolfin_adjoint.adj_reset()

    # Fix the seed to avoid random test failures due to slight tolerance variations
    random.seed(21)
Example #14
0
    def error(self, problem, solution):

        adj_reset()
        parameters = CoupledSWSolver.default_parameters()
        parameters.dump_period = -1
        solver = CoupledSWSolver(problem, parameters)
        for sol in solver.solve(annotate=False):
            pass
        state = sol["state"]

        solution.t = problem.parameters.finish_time
        return errornorm(solution, state)
    def error(self, problem, solution):

        adj_reset()
        parameters = CoupledSWSolver.default_parameters()
        parameters.dump_period = -1
        solver = CoupledSWSolver(problem, parameters)
        for sol in solver.solve(annotate=False):
            pass
        state = sol["state"]

        solution.t = problem.parameters.finish_time
        return errornorm(solution, state)
Example #16
0
def setup_model(parameters, sin_ic, time_step, finish_time, mesh_x, mesh_y=2):
    # Note: The analytical solution is constant in the
    # y-direction, hence a coarse y-resolution is sufficient.

    # Reset the adjoint tape to keep dolfin-adjoint happy
    adj_reset()

    eta0 = 2.0
    k = pi/3000.

    # Temporal settings
    parameters.start_time = Constant(0)
    parameters.finish_time = Constant(finish_time)
    parameters.dt = Constant(time_step)

    # Finite element
    parameters.finite_element = finite_elements.p1dgp2

    # Use Crank-Nicolson to get a second-order time-scheme
    parameters.theta = Constant(0.5)

    # Activate the relevant terms
    parameters.include_advection = True
    parameters.include_viscosity = False
    parameters.linear_divergence = True

    # Physical settings
    parameters.friction = Constant(0.25)
    parameters.viscosity = Constant(0.0)
    parameters.domain = domains.RectangularDomain(0, 0, 3000, 1000, mesh_x,
                                                  mesh_y)

    # Initial condition
    ic_expr = sin_ic(eta0=eta0, k=k, depth=parameters.depth,
            start_time=parameters.start_time, degree=2)
    parameters.initial_condition = ic_expr

    # Set the analytical boundary conditions
    flather_expr = Expression(
        ("2*eta0*sqrt(g/depth)*cos(-sqrt(g*depth)*k*t)", "0"),
        eta0=eta0,
        g=parameters.g,
        depth=parameters.depth,
        t=Constant(parameters.start_time),
        k=k,
        degree=2)

    bcs = BoundaryConditionSet()
    bcs.add_bc("u", flather_expr, facet_id=[1, 2], bctype="flather")
    bcs.add_bc("u", facet_id=3, bctype="free_slip")
    parameters.bcs = bcs

    return parameters, eta0, k
Example #17
0
def pytest_runtest_teardown(item, nextitem):
    """Clear Thetis caches after running a test"""
    from firedrake.tsfc_interface import TSFCKernel
    from pyop2.op2 import Kernel
    from pyop2.base import JITModule
    from dolfin_adjoint import adj_reset

    # disgusting hack, clear the Class-Cached objects in PyOP2 and
    # Firedrake, otherwise these will never be collected.  The Kernels
    # get very big with bendy on.
    Kernel._cache.clear()
    TSFCKernel._cache.clear()
    JITModule._cache.clear()
    # clear the adjoint tape, so subsequent tests don't interfere
    adj_reset()
Example #18
0
def pytest_runtest_teardown(item, nextitem):
    """Clear Thetis caches after running a test"""
    from firedrake.tsfc_interface import TSFCKernel
    from pyop2.op2 import Kernel
    from pyop2.base import JITModule
    from dolfin_adjoint import adj_reset

    # disgusting hack, clear the Class-Cached objects in PyOP2 and
    # Firedrake, otherwise these will never be collected.  The Kernels
    # get very big with bendy on.
    Kernel._cache.clear()
    TSFCKernel._cache.clear()
    JITModule._cache.clear()
    # clear the adjoint tape, so subsequent tests don't interfere
    adj_reset()
Example #19
0
def error(config, eta0, k):
  state = Function(config.function_space)
  state.interpolate(SinusoidalInitialCondition(config, eta0, k, config.params["depth"]))

  adj_reset()
  shallow_water_model.sw_solve(config, state, annotate=False)

  analytic_sol = Expression(("eta0*sqrt(g/depth)*cos(k*x[0]-sqrt(g*depth)*k*t)", \
                             "0", \
                             "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"), \
                             eta0=eta0, g=config.params["g"], \
                             depth=config.params["depth"], t=config.params["current_time"], k=k)
  exactstate = Function(config.function_space)
  exactstate.interpolate(analytic_sol)
  e = state - exactstate
  return sqrt(assemble(dot(e,e)*dx))
Example #20
0
def test_iterate_gamma(problem):

    target_gamma = 0.1
    gamma = problem.material.activation

    if has_dolfin_adjoint:
        dolfin.parameters["adjoint"]["stop_annotating"] = False
        dolfin_adjoint.adj_reset()

    iterate(problem, gamma, target_gamma)

    assert all(gamma.vector().get_local() == target_gamma)
    assert dolfin.norm(problem.state.vector()) > 0

    if has_dolfin_adjoint:
        assert dolfin_adjoint.replay_dolfin(tol=1e-12)
Example #21
0
def error(config, eta0, k):
  state = Function(config.function_space)
  state.interpolate(SinusoidalInitialCondition(config, eta0, k, config.params["depth"]))

  adj_reset()
  shallow_water_model.sw_solve(config, state, annotate=False)

  analytic_sol = Expression(("eta0*sqrt(g/depth)*cos(k*x[0]-sqrt(g*depth)*k*t)", \
                             "0", \
                             "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"), \
                             eta0=config.params["eta0"], g=config.params["g"], \
                             depth=config.params["depth"], t=config.params["current_time"], k=config.params["k"])
  exactstate = Function(config.function_space)
  exactstate.interpolate(analytic_sol)
  e = state - exactstate
  return sqrt(assemble(dot(e,e)*dx))
Example #22
0
def j_and_dj(m, forward_only=None):
    adj_reset()

    # Change the control variables to the config parameters
    config.params["turbine_friction"] = m[:len(config.
                                               params["turbine_friction"])]
    mp = m[len(config.params["turbine_friction"]):]
    config.params["turbine_pos"] = numpy.reshape(mp, (-1, 2))

    # Get initial conditions
    state = Function(config.function_space, name="current_state")
    eta0 = 2.0
    k = pi / config.domain.basin_x
    state.interpolate(
        SinusoidalInitialCondition(config, eta0, k, config.params["depth"]))

    # Set the control values
    U = config.function_space.split()[0].sub(
        0)  # Extract the first component of the velocity function space
    U = U.collapse()  # Recompute the DOF map

    # Set up the turbine friction field using the provided control variable
    turbines = Turbines(U, config.params)
    tf = turbines()
    # The functional of interest is simply the l2 norm of the turbine field
    v = tf.vector()
    j = v.inner(v)

    if not forward_only:
        dj = []
        # Compute the derivatives with respect to the turbine friction
        for n in range(len(config.params["turbine_friction"])):
            tfd = turbines(derivative_index_selector=n,
                           derivative_var_selector='turbine_friction')
            dj.append(2 * v.inner(tfd.vector()))

        # Compute the derivatives with respect to the turbine position
        for n in range(len(config.params["turbine_pos"])):
            for var in ('turbine_pos_x', 'turbine_pos_y'):
                tfd = turbines(derivative_index_selector=n,
                               derivative_var_selector=var)
                dj.append(2 * v.inner(tfd.vector()))
        dj = numpy.array(dj)

        return j, dj
    else:
        return j, None
def main(params, passive_only=False):

    save_logger(params)

    setup_general_parameters()

    logger.info(Text.blue("Start Adjoint Contraction"))
    logger.info(pformat(params.to_dict()))
    logger.setLevel(params["log_level"])

    ############# GET PATIENT DATA ##################
    patient = initialize_patient_data(params["Patient_parameters"])

    # Save mesh and fibers to result file
    save_patient_data_to_simfile(patient, params["sim_file"])

    ############# RUN MATPARAMS OPTIMIZATION ##################

    # Make sure that we choose passive inflation phase
    params["phase"] = PHASES[0]
    if not passive_inflation_exists(params):

        if params["unload"]:

            run_unloaded_optimization(params, patient)

        else:
            run_passive_optimization(params, patient)

        adj_reset()

    if passive_only:
        logger.info("Running passive optimization only. Terminate....")
        import sys

        sys.exit()

    if params["unload"]:

        patient = update_unloaded_patient(params, patient)

    ################## RUN GAMMA OPTIMIZATION ###################

    # Make sure that we choose active contraction phase
    params["phase"] = PHASES[1]
    run_active_optimization(params, patient)
    def error(self, problem, eta0, k):

      adj_reset()
      params = CoupledSWSolver.default_parameters()
      params.dump_period = -1
      solver = CoupledSWSolver(problem, params)
      for s in solver.solve(annotate=False):
          pass
      state = s["state"]

      analytic_sol = Expression(
             ("eta0*sqrt(g/depth)*cos(k*x[0]-sqrt(g*depth)*k*t)", "0", \
             "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"), \
             eta0=eta0, g=problem.parameters.g, \
             depth=problem.parameters.depth, \
             t=float(problem.parameters.finish_time), k=k, degree=2)
      return errornorm(analytic_sol, state, degree_rise=2)
Example #25
0
    def error(self, problem, eta0, k):

        adj_reset()
        params = CoupledSWSolver.default_parameters()
        params.dump_period = -1
        solver = CoupledSWSolver(problem, params)
        for s in solver.solve(annotate=False):
            pass
        state = s["state"]

        analytic_sol = Expression(
               ("eta0*sqrt(g/depth)*cos(k*x[0]-sqrt(g*depth)*k*t)", "0", \
               "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"), \
               eta0=eta0, g=problem.parameters.g, \
               depth=problem.parameters.depth, \
               t=float(problem.parameters.finish_time), k=k, degree=2)
        return errornorm(analytic_sol, state, degree_rise=2)
Example #26
0
def active(params):

    logger.info(Text.blue("\nTest Passive Optimization"))
    logger.info(pformat(params.to_dict()))

    params["phase"] = "passive_inflation"
    params["optimize_matparams"] = False
    # patient.passive_filling_duration = 1
    run_passive_optimization(params, patient)
    adj_reset()

    logger.info(Text.blue("\nTest Active Optimization"))
    print(params["sim_file"])
    params["phase"] = "active_contraction"
    params["active_contraction_iteration_number"] = 0
    measurements, solver_parameters, p_lv, gamma \
        = setup_simulation(params, patient)

    solver_parameters["relax_adjoint_solver"] = False
    dolfin.parameters["adjoint"]["test_derivative"] = True
    logger.info("Replay dolfin1")
    replay_dolfin(tol=1e-12)

    rd, gamma = run_active_optimization_step(params, patient,
                                             solver_parameters, measurements,
                                             p_lv, gamma)

    # Dump html visualization of the forward and adjoint system
    adj_html("active_forward.html", "forward")
    adj_html("active_adjoint.html", "adjoint")

    # Replay the forward run, i.e make sure that the recording is correct.
    logger.info("Replay dolfin")
    assert replay_dolfin(tol=1e-12)

    # Test that the gradient is correct
    logger.info("Taylor test")
    my_taylor_test(rd, gamma)

    paramvec_arr = gather_broadcast(gamma.vector().array())
    rd(paramvec_arr)
    rd.for_res["initial_control"] = rd.initial_paramvec,
    rd.for_res["optimal_control"] = rd.paramvec
    store_results(params, rd, {})
Example #27
0
def moola_problem():
    adj_reset()
    mesh = UnitSquareMesh(256, 256)
    V = FunctionSpace(mesh, "CG", 1)
    f = interpolate(Constant(1), V)
    u = Function(V)
    phi = TestFunction(V)
    F = inner(grad(u), grad(phi)) * dx - f * phi * dx
    bc = DirichletBC(V, Constant(0), "on_boundary")
    solve(F == 0, u, bc)

    J = Functional(inner(u, u) * dx)
    m = Control(f)
    rf = ReducedFunctional(J, m)

    obj = rf.moola_problem().obj
    pf = moola.DolfinPrimalVector(f)

    return obj, pf
Example #28
0
def moola_problem():
    adj_reset()
    mesh = UnitSquareMesh(256, 256)
    V = FunctionSpace(mesh, "CG", 1)
    f = interpolate(Constant(1), V)
    u = Function(V)
    phi = TestFunction(V)
    F = inner(grad(u), grad(phi))*dx - f*phi*dx
    bc = DirichletBC(V, Constant(0), "on_boundary")
    solve(F == 0, u, bc)

    J = Functional(inner(u, u)*dx)
    m = Control(f)
    rf = ReducedFunctional(J, m)

    obj = rf.moola_problem().obj
    pf = moola.DolfinPrimalVector(f)

    return obj, pf
Example #29
0
def j_and_dj(m, forward_only = None):
  adj_reset()

  # Change the control variables to the config parameters
  config.params["turbine_friction"] = m[:len(config.params["turbine_friction"])]
  mp = m[len(config.params["turbine_friction"]):]
  config.params["turbine_pos"] = numpy.reshape(mp, (-1, 2))

  # Get initial conditions
  state = Function(config.function_space, name = "current_state")
  eta0 = 2.0
  k = pi/config.domain.basin_x
  state.interpolate(SinusoidalInitialCondition(config, eta0, k, config.params["depth"]))

  # Set the control values
  U = config.function_space.split()[0].sub(0) # Extract the first component of the velocity function space 
  U = U.collapse() # Recompute the DOF map

  # Set up the turbine friction field using the provided control variable
  turbines = Turbines(U, config.params)
  tf = turbines()
  # The functional of interest is simply the l2 norm of the turbine field
  v = tf.vector()
  j = v.inner(v)  

  if not forward_only:
      dj = []
      # Compute the derivatives with respect to the turbine friction
      for n in range(len(config.params["turbine_friction"])):
        tfd = turbines(derivative_index_selector=n, derivative_var_selector='turbine_friction')
        dj.append( 2 * v.inner(tfd.vector()) )

      # Compute the derivatives with respect to the turbine position
      for n in range(len(config.params["turbine_pos"])):
        for var in ('turbine_pos_x', 'turbine_pos_y'):
          tfd = turbines(derivative_index_selector=n, derivative_var_selector=var)
          dj.append( 2 * v.inner(tfd.vector()) )
      dj = numpy.array(dj)  
      
      return j, dj 
  else:
      return j, None 
Example #30
0
def test_iterate_gamma_pressure(problem):
    target_pressure = 1.0
    plv = [p.traction for p in problem.bcs.neumann if p.name == 'lv']
    pressure = plv[0]

    target_gamma = 0.1
    gamma = problem.material.activation

    if has_dolfin_adjoint:
        dolfin.parameters["adjoint"]["stop_annotating"] = False
        dolfin_adjoint.adj_reset()

    iterate(problem, (pressure, gamma), (target_pressure, target_gamma))

    assert all(gamma.vector().get_local() == target_gamma)
    assert float(plv[0]) == target_pressure
    assert dolfin.norm(problem.state.vector()) > 0

    if has_dolfin_adjoint:
        assert dolfin_adjoint.replay_dolfin(tol=1e-12)
Example #31
0
def test_iterate_pressure(problem):

    target_pressure = 1.0
    plv = [p.traction for p in problem.bcs.neumann if p.name == 'lv']
    pressure = plv[0]

    if has_dolfin_adjoint:
        dolfin.parameters["adjoint"]["stop_annotating"] = False
        dolfin_adjoint.adj_reset()

    iterate(problem, pressure, target_pressure)

    if has_dolfin_adjoint:
        # Check the recording
        assert dolfin_adjoint.replay_dolfin(tol=1e-12)

    # Check that the pressure is correct
    assert float(plv[0]) == target_pressure
    # Check that the state is nonzero
    assert dolfin.norm(problem.state.vector()) > 0
Example #32
0
def test_iterate_gamma_regional():
    problem = make_lv_mechanics_problem('regional')
    target_gamma = problem.material.activation.vector().get_local()
    for i in range(len(target_gamma)):
        target_gamma[i] = 0.1 - i * 0.001
    print(target_gamma)

    gamma = problem.material.activation

    if has_dolfin_adjoint:
        dolfin.parameters["adjoint"]["stop_annotating"] = False
        dolfin_adjoint.adj_reset()

    iterate(problem, gamma, target_gamma)

    print(gamma.vector().get_local())
    assert np.all(gamma.vector().get_local() - target_gamma < 1e-12)
    assert dolfin.norm(problem.state.vector()) > 0

    if has_dolfin_adjoint:
        assert dolfin_adjoint.replay_dolfin(tol=1e-12)
Example #33
0
def test_iterate_gamma_cg1(continuation):

    problem = make_lv_mechanics_problem('CG_1')
    V = problem.material.activation.function_space()
    target_gamma \
        = dolfin.interpolate(dolfin.Expression('0.1 * x[0]',
                                               degree=1), V)
    gamma = problem.material.activation

    if has_dolfin_adjoint:
        dolfin.parameters["adjoint"]["stop_annotating"] = False
        dolfin_adjoint.adj_reset()

    iterate(problem, gamma, target_gamma, continuation=continuation)

    assert np.all(
        gamma.vector().get_local() - target_gamma.vector().get_local() < 1e-12)
    assert dolfin.norm(problem.state.vector()) > 0

    if has_dolfin_adjoint:
        assert dolfin_adjoint.replay_dolfin(tol=1e-12)
Example #34
0
    def error(self, problem_params, eta0, k):

        # The analytical veclocity of the shallow water equations has been
        # multiplied by depth to account for the change of variable (\tilde u =
        # depth u) in this code.
        u_exact = "eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t)"
        ddu_exact = "(viscosity * eta0*sqrt(g/depth) * \
                     cos(k*x[0]-sqrt(g*depth)*k*t) * k*k)"

        eta_exact = "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"

        # The source term
        source = Expression((ddu_exact, "0.0"),
                            eta0=eta0,
                            g=problem_params.g,
                            depth=problem_params.depth,
                            t=problem_params.start_time,
                            k=k,
                            viscosity=problem_params.viscosity,
                            degree=2)
        problem_params.f_u = source
        problem = SWProblem(problem_params)

        adj_reset()
        parameters = CoupledSWSolver.default_parameters()
        parameters.dump_period = -1
        solver = CoupledSWSolver(problem, parameters)
        for sol in solver.solve(annotate=False):
            pass
        state = sol["state"]

        analytic_sol = Expression((u_exact, "0", eta_exact),
                                  eta0=eta0,
                                  g=problem.parameters.g,
                                  depth=problem.parameters.depth,
                                  t=problem.parameters.finish_time,
                                  k=k,
                                  degree=2)
        return errornorm(analytic_sol, state)
    def j_and_dj(self, problem, farm, m, forward_only=None):
        adj_reset()

        # Update the farm parameters.
        # Change the control variables to the farm parameters
        farm._parameters["friction"] = m[:len(farm._parameters["friction"])]

        mp = m[len(farm._parameters["friction"]):]
        farm._parameters["position"] = numpy.reshape(mp, (-1, 2))

        # Set up the turbine friction field using the provided control variable
        turbines = TurbineFunction(farm,
                                   farm._turbine_function_space,
                                   farm.turbine_specification)

        tf = turbines()
        # The functional of interest is simply the l2 norm of the turbine field
        v = tf.vector()
        j = v.inner(v)

        if not forward_only:
            dj = []
            # Compute the derivatives with respect to the turbine friction
            for n in xrange(len(farm._parameters["friction"])):
                tfd = turbines(derivative_index=n,
                               derivative_var="turbine_friction")
                dj.append(2 * v.inner(tfd.vector()))

            # Compute the derivatives with respect to the turbine position
            for n in xrange(len(farm._parameters["position"])):
                for var in ("turbine_pos_x", "turbine_pos_y"):
                    tfd = turbines(derivative_index=n,
                                   derivative_var=var)
                    dj.append(2 * v.inner(tfd.vector()))
            dj = numpy.array(dj)

            return j, dj
        else:
            return j, None
        def _run(cell):
            if dolfin_adjoint:
                from dolfin_adjoint import adj_reset
                adj_reset()

            solver = BasicSingleCellSolver(cell, Constant(0.0))

            # Setup initial condition
            (vs_, vs) = solver.solution_fields()
            vs_.vector()[0] = 30.  # Non-resting state
            vs_.vector()[1] = 0.

            T = 2
            solutions = solver.solve((0, T), 0.25)
            times = []
            v_values = []
            s_values = []
            for ((t0, t1), vs) in solutions:
                times += [0.5 * (t0 + t1)]
                v_values.append(vs.vector()[0])
                s_values.append(vs.vector()[1])

            return (v_values, s_values, times)
    def j_and_dj(self, problem, farm, m, forward_only=None):
        adj_reset()

        # Update the farm parameters.
        # Change the control variables to the farm parameters
        farm._parameters["friction"] = m[:len(farm._parameters["friction"])]

        mp = m[len(farm._parameters["friction"]):]
        farm._parameters["position"] = numpy.reshape(mp, (-1, 2))

        # Set up the turbine friction field using the provided control variable
        turbines = TurbineFunction(farm, farm._turbine_function_space,
                                   farm.turbine_specification)

        tf = turbines()
        # The functional of interest is simply the l2 norm of the turbine field
        v = tf.vector()
        j = v.inner(v)

        if not forward_only:
            dj = []
            # Compute the derivatives with respect to the turbine friction
            for n in range(len(farm._parameters["friction"])):
                tfd = turbines(derivative_index=n,
                               derivative_var="turbine_friction")
                dj.append(2 * v.inner(tfd.vector()))

            # Compute the derivatives with respect to the turbine position
            for n in range(len(farm._parameters["position"])):
                for var in ("turbine_pos_x", "turbine_pos_y"):
                    tfd = turbines(derivative_index=n, derivative_var=var)
                    dj.append(2 * v.inner(tfd.vector()))
            dj = numpy.array(dj)

            return j, dj
        else:
            return j, None
    def error(self, problem_params, eta0, k):

        # The analytical veclocity of the shallow water equations has been
        # multiplied by depth to account for the change of variable (\tilde u =
        # depth u) in this code.
        u_exact = "eta0*sqrt(g/depth) * cos(k*x[0]-sqrt(g*depth)*k*t)"
        ddu_exact = "(viscosity * eta0*sqrt(g/depth) * \
                     cos(k*x[0]-sqrt(g*depth)*k*t) * k*k)"
        eta_exact = "eta0*cos(k*x[0]-sqrt(g*depth)*k*t)"

        # The source term
        source = Expression((ddu_exact,
                            "0.0"),
                            eta0=eta0, g=problem_params.g,
                            depth=problem_params.depth,
                            t=problem_params.start_time,
                            k=k, viscosity=problem_params.viscosity, degree=2)
        problem_params.f_u = source
        problem = SWProblem(problem_params)

        adj_reset()
        parameters = CoupledSWSolver.default_parameters()
        parameters.dump_period = -1
        solver = CoupledSWSolver(problem, parameters)
        for sol in solver.solve(annotate=False):
            pass
        state = sol["state"]

        analytic_sol = Expression((u_exact,
                                  "0",
                                  eta_exact),
                                  eta0=eta0, g=problem.parameters.g,
                                  depth=problem.parameters.depth,
                                  t=problem.parameters.finish_time,
                                  k=k, degree=2)
        return errornorm(analytic_sol, state)
Example #39
0
    target_pressure = 1.0
    plv = [p.traction for p in problem.bcs.neumann if p.name == 'lv']
    pressure = plv[0]

    with pytest.raises(ValueError):
        iterate(problem, (pressure, gamma), (target_pressure, target_gamma))


if __name__ == "__main__":

    prob = problem()
    test_iterate_pressure(prob)
    # test_iterate_gamma(prob)
    # test_iterate_gamma_regional()
    # test_iterate_gamma_cg1(True)
    # test_iterate_gamma_pressure(prob)
    # test_iterate_regional_gamma_pressure()
    exit()

    for c, a in cases:
        print("Continuation = {}, annotate = {}".format(c, a))
        prob = problem()
        test_iterate_pressure(prob, continuation=c, annotate=a)
        if has_dolfin_adjoint:
            dolfin_adjoint.adj_reset()

        prob = problem()
        test_iterate_gamma(prob, continuation=c, annotate=a)
        if has_dolfin_adjoint:
            dolfin_adjoint.adj_reset()
    def test_fitzhugh_nagumo_manual(self):
        """Test that the manually written FitzHugh-Nagumo model gives
        comparable results to a given reference from Sundnes et al,
        2006."""
        class Stimulus(Expression):
            def __init__(self, **kwargs):
                self.t = kwargs["t"]

            def eval(self, value, x):
                if float(self.t) >= 50 and float(self.t) < 60:
                    v_amp = 125
                    value[0] = 0.05 * v_amp
                else:
                    value[0] = 0.0

        if dolfin_adjoint:
            from dolfin_adjoint import adj_reset
            adj_reset()

        cell = FitzHughNagumoManual()
        time = Constant(0.0)
        cell.stimulus = Stimulus(t=time, degree=0)
        solver = BasicSingleCellSolver(cell, time)

        # Setup initial condition
        (vs_, vs) = solver.solution_fields()
        ic = cell.initial_conditions()
        vs_.assign(ic)

        # Initial set-up
        interval = (0, 400)
        dt = 1.0

        times = []
        v_values = []
        s_values = []

        # Solve
        solutions = solver.solve(interval, dt=dt)
        for (timestep, vs) in solutions:
            (t0, t1) = timestep
            times += [(t0 + t1) / 2]

            v_values += [vs.vector()[0]]
            s_values += [vs.vector()[1]]

        # Regression test
        v_max_reference = 2.6883308148064152e+01
        s_max_reference = 6.8660144687023219e+01
        tolerance = 1.e-14
        print "max(v_values) %.16e" % max(v_values)
        print "max(s_values) %.16e" % max(s_values)
        msg = "Maximal %s value does not match reference: diff is %.16e"

        v_diff = abs(max(v_values) - v_max_reference)
        s_diff = abs(max(s_values) - s_max_reference)
        assert (v_diff < tolerance), msg % ("v", v_diff)
        assert (s_diff < tolerance), msg % ("s", s_diff)

        # Correctness test
        import os
        if int(os.environ.get("DOLFIN_NOPLOT", 0)) != 1:
            import pylab
            pylab.plot(times, v_values, 'b*')
            pylab.plot(times, s_values, 'r-')