def tlm_adj_setup_initial_conditions(self, cell_model, Scheme):
        mesh = UnitIntervalMesh(3)
        Model = cell_model.__class__

        # Initiate solver, with model and Scheme
        params = Model.default_parameters()
        model = Model(params=params)

        solver = self._setup_solver(model, Scheme, mesh)
        ics = project(model.initial_conditions(), solver.VS).copy(deepcopy=True, name="ics")

        info_green("Running forward %s with %s (setup)" % (model, Scheme))
        self._run(solver, ics)

        # Define functional
        (vs_, vs) = solver.solution_fields()
        form = lambda w: inner(w, w)*dx
        J = Functional(form(vs)*dt[FINISH_TIME])

        # Compute value of functional with current ics
        Jics = assemble(form(vs))

        # Set-up runner
        def Jhat(ics):
            self._run(solver, ics)
            (vs_, vs) = solver.solution_fields()
            return assemble(form(vs))

        # Stop annotating
        parameters["adjoint"]["stop_annotating"] = True

        m = Control(vs)
        return J, Jhat, m, Jics
Ejemplo n.º 2
0
    def test_compute_gradient(self):
        "Test that we can compute the gradient for some given functional"
        set_dolfin_parameters()
        model = Model()

        params = BasicSingleCellSolver.default_parameters()
        params["theta"] = theta
        time = Constant(0.0)
        solver = BasicSingleCellSolver(model, time, params=params)

        # Get initial conditions (Projection of expressions
        # don't get annotated, which is fine, because there is
        # no need.)
        ics = project(model.initial_conditions(), solver.VS)

        # Run forward model
        info_green("Running forward %s with theta %g" % (model, theta))
        self._run(solver, model, ics)

        # Define functional
        (vs_, vs) = solver.solution_fields()
        J = Functional(inner(vs, vs) * dx * dt[FINISH_TIME])

        # Compute gradient with respect to vs_. Highly unclear
        # why with respect to ics and vs fail.
        info_green("Computing gradient")
        dJdics = compute_gradient(J, Control(vs_))
        assert (dJdics is not None), "Gradient is None (#fail)."
        print(dJdics.vector().array())
    def test_adjoint_cell_model_parameter(self, cell_model, Scheme):
        """ Test that the gradient computed with the adjoint model is correct. """

        if isinstance(cell_model, fails_with_RK4) and Scheme == "RK4":
            pytest.xfail(
                "RK4 is unstable for some models with this timestep (0.01)")

        if isinstance(cell_model,
                      fails_with_forward_euler) and Scheme == "ForwardEuler":
            pytest.xfail(
                "ForwardEuler is unstable for some models with this timestep (0.01)"
            )

        J, Jhat, m, Jics = self.tlm_adj_setup_cellmodel_parameters(
            cell_model, Scheme)

        # Seed for taylor test
        seed = seed_collection_adm.get(cell_model.__class__)

        # Compute gradient with respect to vs.
        info_green("Computing gradient")
        dJdics = compute_gradient(J, m, forget=False)
        assert (dJdics is not None), "Gradient is None (#fail)."
        conv_rate = taylor_test(Jhat, m, Jics, dJdics, seed=seed)

        # Check that minimal rate is greater than some given number
        assert_greater(conv_rate, 1.9)
Ejemplo n.º 4
0
    def test_compute_adjoint(self):
        "Test that we can compute the adjoint for some given functional"
        set_dolfin_parameters()
        model = Model()

        params = BasicSingleCellSolver.default_parameters()
        params["theta"] = theta
        time = Constant(0.0)
        solver = BasicSingleCellSolver(model, time, params=params)

        # Get initial conditions (Projection of expressions
        # don't get annotated, which is fine, because there is
        # no need.)
        ics = project(model.initial_conditions(), solver.VS)

        # Run forward model
        info_green("Running forward %s with theta %g" % (model, theta))
        self._run(solver, model, ics)

        (vs_, vs) = solver.solution_fields()

        # Define functional and compute gradient etc
        J = Functional(inner(vs_, vs_) * dx * dt[FINISH_TIME])

        # Compute adjoint
        info_green("Computing adjoint")
        z = compute_adjoint(J)

        # Check that no vs_ adjoint is None (== 0.0!)
        for (value, var) in z:
            if var.name == "vs_":
                msg = "Adjoint solution for vs_ is None (#fail)."
                assert (value is not None), msg
    def test_tlm_cell_model_parameter(self, cell_model, Scheme):
        if Scheme == "ForwardEuler":
            pytest.xfail(
                "Forward Euler is unstable for some models with this timestep (0.01)"
            )

        if isinstance(cell_model, fails_with_RK4) and Scheme == "RK4":
            pytest.xfail(
                "RK4 is unstable for some models with this timestep (0.01)")

        J, Jhat, m, Jics = self.tlm_adj_setup_cellmodel_parameters(
            cell_model, Scheme)

        # Seed for taylor test
        seed = seed_collection_tlm.get(cell_model.__class__)

        # Stop annotating
        parameters["adjoint"]["stop_annotating"] = True

        # Check TLM correctness
        info_green("Computing gradient")
        dJdics = compute_gradient_tlm(J, m, forget=False)
        assert (dJdics is not None), "Gradient is None (#fail)."
        conv_rate_tlm = taylor_test(Jhat, m, Jics, dJdics, seed=seed)

        assert_greater(conv_rate_tlm, 1.8)
    def test_tlm_initial(self, cell_model, Scheme):
        "Test that we can compute the gradient for some given functional"

        if Scheme == "ForwardEuler":
            pytest.xfail(
                "Forward Euler is unstable for some models with this timestep (0.01)"
            )

        if isinstance(cell_model, fails_with_RK4) and Scheme == "RK4":
            pytest.xfail(
                "RK4 is unstable for some models with this timestep (0.01)")

        J, Jhat, m, Jics = self.tlm_adj_setup_initial_conditions(
            cell_model, Scheme)

        # Seed for taylor test
        seed = seed_collection_tlm.get(cell_model.__class__)

        # Check TLM correctness
        info_green("Computing gradient")
        dJdics = compute_gradient_tlm(J, m, forget=False)
        assert (dJdics is not None), "Gradient is None (#fail)."
        conv_rate_tlm = taylor_test(Jhat, m, Jics, dJdics, seed=seed)

        assert_greater(conv_rate_tlm, 1.8)
        return
    def test_replay(self, Solver, solver_type, tol):
        "Test that replay of basic bidomain solver reports success."

        self._setup_solver(Solver, solver_type)
        self._solve()

        # Check replay
        info_green("Running replay basic (%s)" % solver_type)
        success = replay_dolfin(stop=True, tol=tol)
        assert_equal(success, True)
    def test_adjoint(self, Solver, solver_type):
        """Test that adjoint model of basic bidomain solver converges at 2nd order."""
        info_green("Running adjoint basic (%s)" % solver_type)

        J, Jhat, m, Jics = self.tlm_adj_setup(Solver, solver_type)

        # Check adjoint correctness
        dJdics = compute_gradient(J, m, forget=False)
        assert (dJdics is not None), "Gradient is None (#fail)."
        conv_rate = taylor_test(Jhat, m, Jics, dJdics, seed=1e-3)

        # Check that minimal convergence rate is greater than some given number
        assert_greater(conv_rate, 1.9)
    def test_taylor_remainder(self):
        "Run Taylor remainder tests for selection of models and solvers."
        set_dolfin_parameters()
        model = Model()

        params = BasicSingleCellSolver.default_parameters()
        params["theta"] = theta
        time = Constant(0.0)
        solver = BasicSingleCellSolver(model, time, params=params)

        # Get initial conditions (Projection of expressions
        # don't get annotated, which is fine, because there is
        # no need.)
        ics = project(model.initial_conditions(), solver.VS)

        # Run forward model
        info_green("Running forward %s with theta %g" % (model, theta))
        self._run(solver, model, ics)

        # Define functional
        (vs_, vs) = solver.solution_fields()
        form = lambda w: inner(w, w)*dx
        J = Functional(form(vs)*dt[FINISH_TIME])

        # Compute value of functional with current ics
        Jics = assemble(form(vs))

        # Compute gradient with respect to vs_ (ics?)
        dJdics = compute_gradient(J, Control(vs_),
                                  forget=False)

        # Stop annotating
        parameters["adjoint"]["stop_annotating"] = True

        # Set-up runner
        def Jhat(ics):
            self._run(solver, model, ics)
            (vs_, vs) = solver.solution_fields()
            return assemble(form(vs))

        # Run taylor test
        if isinstance(model, Tentusscher_2004_mcell):
            seed=1.e-5
        else:
            seed=None

        conv_rate = taylor_test(Jhat, Control(vs_),
                                Jics, dJdics, seed=seed)

        # Check that minimal rate is greater than some given number
        assert_greater(conv_rate, 1.8)
    def test_replay(self):
        "Test that replay reports success for basic single cell solver"
        set_dolfin_parameters()
        model = Model()

        # Initialize solver
        params = BasicSingleCellSolver.default_parameters()
        params["theta"] = theta
        time = Constant(0.0)
        solver = BasicSingleCellSolver(model, time, params=params)

        info_green("Running %s with theta %g" % (model, theta))

        ics = project(model.initial_conditions(), solver.VS).copy(deepcopy=True, name="ics")
        self._run(solver, model, ics)

        info_green("Replaying")
        success = replay_dolfin(tol=0.0, stop=True)
        assert_true(success)
    def tlm_adj_setup_cellmodel_parameters(self, cell_model, Scheme):
        mesh = UnitIntervalMesh(3)
        Model = cell_model.__class__

        # Initiate solver, with model and Scheme
        cell_params = Model.default_parameters()
        param_name = cellmodel_parameters_seeds[Model][0]
        cell_params[param_name] = Constant(cell_params[param_name],
                                           name=param_name)
        model = Model(params=cell_params)

        solver = self._setup_solver(model, Scheme, mesh)

        info_green("Running forward %s with %s (setup)" % (model, Scheme))
        ics = Function(project(model.initial_conditions(), solver.VS),
                       name="ics")
        self._run(solver, ics)

        # Define functional
        (vs_, vs) = solver.solution_fields()
        form = lambda w: inner(w, w) * dx
        J = Functional(form(vs) * dt[FINISH_TIME])

        # Compute value of functional with current ics
        Jics = assemble(form(vs))

        # Set-up runner
        def Jhat(val):
            cell_params[param_name].assign(val)
            ics = Function(project(model.initial_conditions(), solver.VS),
                           name="ics")
            self._run(solver, ics)
            (vs_, vs) = solver.solution_fields()
            return assemble(form(vs))

        # Stop annotating
        solver.parameters["enable_adjoint"] = False

        m = ConstantControl(cell_params[param_name])
        return J, Jhat, m, Jics
    def test_replay(self, cell_model, Scheme):
        mesh = UnitIntervalMesh(3)
        Model = cell_model.__class__

        if isinstance(cell_model, fails_with_RK4) and Scheme == "RK4":
            pytest.xfail("RK4 is unstable for some models with this timestep (0.01)")

        # Initiate solver, with model and Scheme
        params = Model.default_parameters()
        model = Model(params=params)

        solver = self._setup_solver(model, Scheme, mesh)
        ics = project(model.initial_conditions(), solver.VS)

        info_green("Running forward %s with %s (replay)" % (model, Scheme))
        self._run(solver, ics)

        print solver.solution_fields()[0].vector().array()

        info_green("Replaying")
        success = replay_dolfin(tol=0, stop=True)
        assert_true(success)