Mentions légales du service

Skip to content
Snippets Groups Projects

Wrapper for a file-communicating objective function

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Nikolaus Hansen
    Edited
    fitness_with_files_wrapper.py 1.90 KiB
    """Code to optimize an objective function that can be called in the
    system shell and communicates via files.
    """
    
    import subprocess
    import cma  # pip install cma
    
    def _tf_write(x):
        """transformation before to write parameters"""
        return repr(list(x))
    
    class FitnessViaFilesWrapper:
        """wrap an objective function that uses files to read the input variables
        and write the output value
        """
        def __init__(self, fun, filename_params, filename_res,
                     tf_write=_tf_write, tf_read=float):
            """`fun` reads from `filename_params` and writes to `filename_res`"""
            self.fun = fun
            self.filename_params = filename_params
            self.filename_res = filename_res
            self.tf_write = tf_write
            self.tf_read = tf_read
        def __call__(self, x):
            """objective function call.
    
            Write ``tf_write(x)`` to file and call `self.fun` and
            return content of `self.filename_res` transformed by
            `tf_read`.
            """
            with open(self.filename_params, 'wt') as f:
                f.write(self.tf_write(x))
            self.fun()  # writes into file self.filename_res
            with open(self.filename_res, 'rt') as f:
                res = self.tf_read(f.read())
            return res
    
    def call_matlab():
        """objective function that uses the files '_in' and '_out'"""
        # subprocess.call('matlab -nodisplay -nodesktop -nojvm -nosplash < simulink-script _in _traject ...', shell=True)
        # here we may want to compute the deviation of _traject from the desired trajectory
        # and write the error to be minimized to _out
    
        # testing example:
        import ast
        with open('_in', 'rt') as f:
            x = ast.literal_eval(f.read())
        fun_val = cma.ff.elli(x)
        with open('_out', 'wt') as f:
            f.write(repr(fun_val))
    
    f = FitnessViaFilesWrapper(call_matlab, '_in', '_out')
    # f = cma.ff.elli
    
    # testing the code, try to find minimizer of f
    x, es = cma.fmin2(f, 3 * [1], 1);
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Please register or to comment