def main(argv=None):
    """to install and/or test from the command line use::

        python cma.py [options | func dim sig0 [optkey optval][optkey optval]...]

    with options being

    ``--test`` (or ``-t``) to run the doctest, ``--test -v`` to get (much) verbosity.

    ``install`` to install cma.py (uses setup from distutils.core).

    ``--doc`` for more infos.

    Or start Python or (even better) ``ipython`` and::

        import cma
        cma.main('--test')
        help(cma)
        help(cma.fmin)
        res = fmin(cma.fcts.rosen, 10 * [0], 1)
        cma.plot()

    Examples
    ========
    Testing with the local python distribution from a command line
    in a folder where ``cma.py`` can be found::

        python cma.py --test

    And a single run on the Rosenbrock function::

        python cma.py rosen 10 1  # dimension initial_sigma
        python cma.py plot

    In the python shell::

        import cma
        cma.main('--test')

    """
    if argv is None:
        argv = sys.argv  # should have better been sys.argv[1:]
    else:
        if isinstance(argv, list):
            argv = ['python'] + argv  # see above
        else:
            argv = ['python'] + [argv]

    # uncomment for unit test
    # _test()
    # handle input arguments, getopt might be helpful ;-)
    if len(argv) >= 1:  # function and help
        if len(argv) == 1 or argv[1].startswith('-h') or argv[1].startswith('--help'):
            print(main.__doc__)
            fun = None
        elif argv[1].startswith('-t') or argv[1].startswith('--test'):
            import doctest
            if len(argv) > 2 and (argv[2].startswith('--v') or argv[2].startswith('-v')):  # verbose
                print('doctest for cma.py: due to different platforms and python versions')
                print('and in some cases due to a missing unique random seed')
                print('many examples will "fail". This is OK, if they give a similar')
                print('to the expected result and if no exception occurs. ')
                # if argv[1][2] == 'v':
                doctest.testmod(sys.modules[__name__], report=True)  # this is quite cool!
            else:  # was: if len(argv) > 2 and (argv[2].startswith('--qu') or argv[2].startswith('-q')):
                print('doctest for cma.py: launching...') # not anymore: (it might be necessary to close the pop up window to finish)
                fn = '_cma_doctest_.txt'
                stdout = sys.stdout
                try:
                    with open(fn, 'w') as f:
                        sys.stdout = f
                        clock = ElapsedTime()
                        doctest.testmod(sys.modules[__name__], report=True)  # this is quite cool!
                        t_elapsed = clock()
                finally:
                    sys.stdout = stdout
                process_doctest_output(fn)
                # clean up
                try:
                    import os
                    for name in os.listdir('.'):
                        if (name.startswith('bound_method_FitnessFunctions.rosen_of_cma.FitnessFunctions_object_at_')
                            and name.endswith('.pkl')):
                            os.remove(name)
                except:
                    pass
                print('doctest for cma.py: finished (no other output should be seen after launching, more in file _cma_doctest_.txt)')
                print('  elapsed time [s]:', t_elapsed)
            return
        elif argv[1] == '--doc':
            print(__doc__)
            print(CMAEvolutionStrategy.__doc__)
            print(fmin.__doc__)
            fun = None
        elif argv[1] == '--fcts':
            print('List of valid function names:')
            print([d for d in dir(fcts) if not d.startswith('_')])
            fun = None
        elif argv[1] in ('install', '--install'):
            from distutils.core import setup
            setup(name="cma",
                  long_description=__doc__,
                  version=__version__.split()[0],
                  description="CMA-ES, Covariance Matrix Adaptation Evolution Strategy for non-linear numerical optimization in Python",
                  author="Nikolaus Hansen",
                  author_email="hansen at lri.fr",
                  maintainer="Nikolaus Hansen",
                  maintainer_email="hansen at lri.fr",
                  url="https://www.lri.fr/~hansen/cmaes_inmatlab.html#python",
                  license="BSD",
                  classifiers = [
                    "Intended Audience :: Science/Research",
                    "Intended Audience :: Education",
                    "Intended Audience :: Other Audience",
                    "Topic :: Scientific/Engineering",
                    "Topic :: Scientific/Engineering :: Mathematics",
                    "Topic :: Scientific/Engineering :: Artificial Intelligence",
                    "Operating System :: OS Independent",
                    "Programming Language :: Python :: 2.6",
                    "Programming Language :: Python :: 2.7",
                    "Programming Language :: Python :: 3",
                    "Development Status :: 4 - Beta",
                    "Environment :: Console",
                    "License :: OSI Approved :: BSD License",
                    # "License :: OSI Approved :: MIT License",
                  ],
                  keywords=["optimization", "CMA-ES", "cmaes"],
                  py_modules=["cma"],
                  requires=["numpy"],
            )
            fun = None
        elif argv[1] in ('plot',):
            plot(name=argv[2] if len(argv) > 2 else None)
            raw_input('press return')
            fun = None
        elif len(argv) > 3:
            fun = eval('fcts.' + argv[1])
        else:
            print('try -h option')
            fun = None

    if fun is not None:

        if len(argv) > 2:  # dimension
            x0 = np.ones(eval(argv[2]))
        if len(argv) > 3:  # sigma
            sig0 = eval(argv[3])

        opts = {}
        for i in xrange(5, len(argv), 2):
            opts[argv[i - 1]] = eval(argv[i])

        # run fmin
        if fun is not None:
            tic = time.time()
            fmin(fun, x0, sig0, opts)  # ftarget=1e-9, tolfacupx=1e9, verb_log=10)
            # plot()
            # print ' best function value ', res[2]['es'].best[1]
            print('elapsed time [s]: + %.2f', round(time.time() - tic, 2))

    elif not len(argv):
        fmin(fcts.elli, np.ones(6) * 0.1, 0.1, {'ftarget':1e-9})
def main ( argv = None ) : if argv is None : argv = sys . argv else : if isinstance ( argv , list ) : argv = [ 'python' ] + argv else : argv = [ 'python' ] + [ argv ] if len ( argv ) >= 1 : if len ( argv ) == 1 or argv [ 1 ] . startswith ( '-h' ) or argv [ 1 ] . startswith ( '--help' ) : print ( main . __doc__ ) fun = None elif argv [ 1 ] . startswith ( '-t' ) or argv [ 1 ] . startswith ( '--test' ) : import doctest if len ( argv ) > 2 and ( argv [ 2 ] . startswith ( '--v' ) or argv [ 2 ] . startswith ( '-v' ) ) : print ( 'doctest for cma.py: due to different platforms and python versions' ) print ( 'and in some cases due to a missing unique random seed' ) print ( 'many examples will "fail". This is OK, if they give a similar' ) print ( 'to the expected result and if no exception occurs. ' ) doctest . testmod ( sys . modules [ __name__ ] , report = True ) else : print ( 'doctest for cma.py: launching...' ) fn = '_cma_doctest_.txt' stdout = sys . stdout try : with open ( fn , 'w' ) as f : sys . stdout = f clock = ElapsedTime ( ) doctest . testmod ( sys . modules [ __name__ ] , report = True ) t_elapsed = clock ( ) finally : sys . stdout = stdout process_doctest_output ( fn ) try : import os for name in os . listdir ( '.' ) : if ( name . startswith ( 'bound_method_FitnessFunctions.rosen_of_cma.FitnessFunctions_object_at_' ) and name . endswith ( '.pkl' ) ) : os . remove ( name ) except : pass print ( 'doctest for cma.py: finished (no other output should be seen after launching, more in file _cma_doctest_.txt)' ) print ( '  elapsed time [s]:' , t_elapsed ) return elif argv [ 1 ] == '--doc' : print ( __doc__ ) print ( CMAEvolutionStrategy . __doc__ ) print ( fmin . __doc__ ) fun = None elif argv [ 1 ] == '--fcts' : print ( 'List of valid function names:' ) print ( [ d for d in dir ( fcts ) if not d . startswith ( '_' ) ] ) fun = None elif argv [ 1 ] in ( 'install' , '--install' ) : from distutils . core import setup setup ( name = "cma" , long_description = __doc__ , version = __version__ . split ( ) [ 0 ] , description = "CMA-ES, Covariance Matrix Adaptation Evolution Strategy for non-linear numerical optimization in Python" , author = "Nikolaus Hansen" , author_email = "hansen at lri.fr" , maintainer = "Nikolaus Hansen" , maintainer_email = "hansen at lri.fr" , url = "https://www.lri.fr/~hansen/cmaes_inmatlab.html#python" , license = "BSD" , classifiers = [ "Intended Audience :: Science/Research" , "Intended Audience :: Education" , "Intended Audience :: Other Audience" , "Topic :: Scientific/Engineering" , "Topic :: Scientific/Engineering :: Mathematics" , "Topic :: Scientific/Engineering :: Artificial Intelligence" , "Operating System :: OS Independent" , "Programming Language :: Python :: 2.6" , "Programming Language :: Python :: 2.7" , "Programming Language :: Python :: 3" , "Development Status :: 4 - Beta" , "Environment :: Console" , "License :: OSI Approved :: BSD License" , ] , keywords = [ "optimization" , "CMA-ES" , "cmaes" ] , py_modules = [ "cma" ] , requires = [ "numpy" ] , ) fun = None elif argv [ 1 ] in ( 'plot' , ) : plot ( name = argv [ 2 ] if len ( argv ) > 2 else None ) raw_input ( 'press return' ) fun = None elif len ( argv ) > 3 : fun = eval ( 'fcts.' + argv [ 1 ] ) else : print ( 'try -h option' ) fun = None if fun is not None : if len ( argv ) > 2 : x0 = np . ones ( eval ( argv [ 2 ] ) ) if len ( argv ) > 3 : sig0 = eval ( argv [ 3 ] ) opts = { } for i in xrange ( 5 , len ( argv ) , 2 ) : opts [ argv [ i - 1 ] ] = eval ( argv [ i ] ) if fun is not None : tic = time . time ( ) fmin ( fun , x0 , sig0 , opts ) print ( 'elapsed time [s]: + %.2f' , round ( time . time ( ) - tic , 2 ) ) elif not len ( argv ) : fmin ( fcts . elli , np . ones ( 6 ) * 0.1 , 0.1 , { 'ftarget' : 1e-9 } )
to install and/or test from the command line use::

        python cma.py [options | func dim sig0 [optkey optval][optkey optval]...]

    with options being

    ``--test`` (or ``-t``) to run the doctest, ``--test -v`` to get (much) verbosity.

    ``install`` to install cma.py (uses setup from distutils.core).

    ``--doc`` for more infos.

    Or start Python or (even better) ``ipython`` and::

        import cma
        cma.main('--test')
        help(cma)
        help(cma.fmin)
        res = fmin(cma.fcts.rosen, 10 * [0], 1)
        cma.plot()

    Examples
    ========
    Testing with the local python distribution from a command line
    in a folder where ``cma.py`` can be found::

        python cma.py --test

    And a single run on the Rosenbrock function::

        python cma.py rosen 10 1  # dimension initial_sigma
        python cma.py plot

    In the python shell::

        import cma
        cma.main('--test')