Пример #1
0
        def __call__(self, value):

            try:
                print "\n* * * Adjoint and optimiser time taken = {}".format(toc())
                list_timings(True)
            except:
                pass

            #### initial condition dump hack ####
            phi_ic = value[0].vector().array()
            phi = phi_ic.copy()
            for i in range(len(model.mesh.cells())):
                j = i*2
                phi[j] = phi_ic[-(j+2)]
                phi[j+1] = phi_ic[-(j+1)]
            phi_ic = phi
            sw_io.write_array_to_file('phi_ic_adj{}_latest.json'.format(job),phi_ic,'w')
            sw_io.write_array_to_file('phi_ic_adj{}.json'.format(job),phi_ic,'a')

            try:
                h_ic = value[1].vector().array()
                sw_io.write_array_to_file('h_ic_adj{}_latest.json'.format(job),h_ic,'w')
                sw_io.write_array_to_file('h_ic_adj{}.json'.format(job),h_ic,'a')
            except:
                pass

            try:
                q_a_ = value[2]((0,0)); q_pa_ = value[3]((0,0)); q_pb_ = value[4]((0,0))
                sw_io.write_q_vals_to_file('q_ic_adj{}_latest.json'.format(job),q_a_,q_pa_,q_pb_,'w')
                sw_io.write_q_vals_to_file('q_ic_adj{}.json'.format(job),q_a_,q_pa_,q_pb_,'a')
            except:
                pass

            tic()

            print "\n* * * Computing forward model"

            func_value = (super(MyReducedFunctional, self)).__call__(value)
            # model.setup(h_ic = value[1], phi_ic = value[0], q_a = value[2], q_pa = value[3], q_pb = value[4])
            # model.solve(T = options.T)

            # func_value = adjointer.evaluate_functional(self.functional, 0)

            print "* * * Forward model: time taken = {}".format(toc())

            list_timings(True)

            # sys.exit()

            j = self.scale * func_value
            j_log.append(j)
            sw_io.write_array_to_file('j_log{}.json'.format(job), j_log, 'w')

            (fwd_var, output) = adjointer.get_forward_solution(adjointer.equation_count - 1)
            var = adjointer.get_variable_value(fwd_var)
            y, q, h, phi, phi_d, x_N, u_N = sw_io.map_to_arrays(var.data, model.y, model.mesh) 
            sw_io.write_array_to_file('phi_d_adj{}_latest.json'.format(job),phi_d,'w')
            sw_io.write_array_to_file('phi_d_adj{}.json'.format(job),phi_d,'a')

            # from IPython import embed; embed()  
            
            plotter.update_plot(phi_ic, phi_d, y, x_N, j)

            print "* * * J = {}".format(j)

            tic()

            return func_value                
    def __call__(self, value):
        """ Evaluates the reduced functional for the given control value.

	Args:
	    value: The point in control space where to perform the Taylor test. Must be of the same type as the Control (e.g. Function, Constant or lists of latter).

	Returns:
	    float: The functional value.
        """

        # Make sure we do not annotate

        # Reset any cached data in dolfin-adjoint
        adj_reset_cache()

        #: The control values at which the reduced functional is to be evaluated.
        value = enlist(value)

        # Call callback
        self.eval_cb_pre(delist(value, list_type=self.controls))

        # Update the control values on the tape
        ListControl(self.controls).update(value)

        # Check if the result is already cached
        if self.cache:
            hash = value_hash(value)
            if hash in self._cache["functional_cache"]:
                # Found a cache
                info_green("Got a functional cache hit")
                return self._cache["functional_cache"][hash]

        # Replay the annotation and evaluate the functional
        func_value = 0.
        for i in range(adjointer.equation_count):
            (fwd_var, output) = adjointer.get_forward_solution(i)
            if isinstance(output.data, Function):
                output.data.rename(str(fwd_var),
                                   "a Function from dolfin-adjoint")

            # Call callback
            self.replay_cb(fwd_var, output.data,
                           delist(value, list_type=self.controls))

            # Check if we checkpointing is active and if yes
            # record the exact same checkpoint variables as
            # in the initial forward run
            if adjointer.get_checkpoint_strategy() != None:
                if str(fwd_var) in mem_checkpoints:
                    storage = libadjoint.MemoryStorage(output, cs=True)
                    storage.set_overwrite(True)
                    adjointer.record_variable(fwd_var, storage)
                if str(fwd_var) in disk_checkpoints:
                    storage = libadjoint.MemoryStorage(output)
                    adjointer.record_variable(fwd_var, storage)
                    storage = libadjoint.DiskStorage(output, cs=True)
                    storage.set_overwrite(True)
                    adjointer.record_variable(fwd_var, storage)
                if not str(fwd_var) in mem_checkpoints and not str(
                        fwd_var) in disk_checkpoints:
                    storage = libadjoint.MemoryStorage(output)
                    storage.set_overwrite(True)
                    adjointer.record_variable(fwd_var, storage)

            # No checkpointing, so we record everything
            else:
                storage = libadjoint.MemoryStorage(output)
                storage.set_overwrite(True)
                adjointer.record_variable(fwd_var, storage)

            if i == adjointer.timestep_end_equation(fwd_var.timestep):
                func_value += adjointer.evaluate_functional(
                    self.functional, fwd_var.timestep)
                if adjointer.get_checkpoint_strategy() != None:
                    adjointer.forget_forward_equation(i)

        self.current_func_value = func_value

        # Call callback
        self.eval_cb_post(self.scale * func_value,
                          delist(value, list_type=self.controls))

        if self.cache:
            # Add result to cache
            info_red("Got a functional cache miss")
            self._cache["functional_cache"][hash] = self.scale * func_value

        return self.scale * func_value
    def __call__(self, value):
        """ Evaluates the reduced functional for the given control value.

	Args:
	    value: The point in control space where to perform the Taylor test. Must be of the same type as the Control (e.g. Function, Constant or lists of latter).

	Returns:
	    float: The functional value.
        """

        # Make sure we do not annotate

        # Reset any cached data in dolfin-adjoint
        adj_reset_cache()

        #: The control values at which the reduced functional is to be evaluated.
        value = enlist(value)

        # Call callback
        self.eval_cb_pre(delist(value, list_type=self.controls))

        # Update the control values on the tape
        ListControl(self.controls).update(value)

        # Check if the result is already cached
        if self.cache:
            hash = value_hash(value)
            if hash in self._cache["functional_cache"]:
                # Found a cache
                info_green("Got a functional cache hit")
                return self._cache["functional_cache"][hash]

        # Replay the annotation and evaluate the functional
        func_value = 0.
        for i in range(adjointer.equation_count):
            (fwd_var, output) = adjointer.get_forward_solution(i)
            if isinstance(output.data, Function):
                output.data.rename(str(fwd_var), "a Function from dolfin-adjoint")

            # Call callback
            self.replay_cb(fwd_var, output.data, delist(value, list_type=self.controls))

            # Check if we checkpointing is active and if yes
            # record the exact same checkpoint variables as
            # in the initial forward run
            if adjointer.get_checkpoint_strategy() != None:
                if str(fwd_var) in mem_checkpoints:
                    storage = libadjoint.MemoryStorage(output, cs = True)
                    storage.set_overwrite(True)
                    adjointer.record_variable(fwd_var, storage)
                if str(fwd_var) in disk_checkpoints:
                    storage = libadjoint.MemoryStorage(output)
                    adjointer.record_variable(fwd_var, storage)
                    storage = libadjoint.DiskStorage(output, cs = True)
                    storage.set_overwrite(True)
                    adjointer.record_variable(fwd_var, storage)
                if not str(fwd_var) in mem_checkpoints and not str(fwd_var) in disk_checkpoints:
                    storage = libadjoint.MemoryStorage(output)
                    storage.set_overwrite(True)
                    adjointer.record_variable(fwd_var, storage)

            # No checkpointing, so we record everything
            else:
                storage = libadjoint.MemoryStorage(output)
                storage.set_overwrite(True)
                adjointer.record_variable(fwd_var, storage)

            if i == adjointer.timestep_end_equation(fwd_var.timestep):
                func_value += adjointer.evaluate_functional(self.functional, fwd_var.timestep)
                if adjointer.get_checkpoint_strategy() != None:
                    adjointer.forget_forward_equation(i)

        self.current_func_value = func_value

        # Call callback
        self.eval_cb_post(self.scale * func_value, delist(value,
            list_type=self.controls))

        if self.cache:
            # Add result to cache
            info_red("Got a functional cache miss")
            self._cache["functional_cache"][hash] = self.scale*func_value

        return self.scale*func_value