
    J-jTB                         d Z ddlmZmZmZ ddlZddlmZ [[[ G d de      Z	 G d d	e      Z
 G d
 de      Z G d de      Zy#  dZY 6xY w)z2Very few interface defining base class definitions    )absolute_importdivisionprint_functionN   )EvalParallel2c                   *    e Zd ZdZd ZddZd Zd Zy)EvalParallelz7allow construct ``with EvalParallel(fun) as eval_all:``c                     || _         y Nfun)selfr   argskwargss       \/Users/jameslopez/projects/TradingBot25/.venv/lib/python3.12/site-packages/cma/interfaces.py__init__zEvalParallel.__init__
   s	        c                 N    |D cg c]  } | j                   |g|  c}S c c}w r   r   )r   Xr   xs       r   __call__zEvalParallel.__call__   s*    ,-.Aq"T"A...s   "c                     | S r    r   s    r   	__enter__zEvalParallel.__enter__   s    r   c                      y r   r   r   r   r   s      r   __exit__zEvalParallel.__exit__   s    r   N)r   )__name__
__module____qualname____doc__r   r   r   r   r   r   r   r	   r	      s    A/$-r   r	   c                   d    e Zd ZdZd Zd Zd Zd Zd ZddZ	e
d	        Z	 	 	 	 	 dd
Zd Zd Zy)OOOptimizera  abstract base class for an Object Oriented Optimizer interface.

    Relevant methods are `__init__`, `ask`, `tell`, `optimize` and `stop`,
    and property `result`. Only `optimize` is fully implemented in this
    base class.

    Examples
    --------
    All examples minimize the function `elli`, the output is not shown.
    (A preferred environment to execute all examples is ``ipython``.)

    First we need::

        # CMAEvolutionStrategy derives from the OOOptimizer class
        from cma import CMAEvolutionStrategy
        from cma.fitness_functions import elli

    The shortest example uses the inherited method
    `OOOptimizer.optimize`::

        es = CMAEvolutionStrategy(8 * [0.1], 0.5).optimize(elli)

    The input parameters to `CMAEvolutionStrategy` are specific to this
    inherited class. The remaining functionality is based on interface
    defined by `OOOptimizer`. We might have a look at the result::

        print(es.result[0])  # best solution and
        print(es.result[1])  # its function value

    Virtually the same example can be written with an explicit loop
    instead of using `optimize`. This gives the necessary insight into
    the `OOOptimizer` class interface and entire control over the
    iteration loop::

        # a new CMAEvolutionStrategy instance
        optim = CMAEvolutionStrategy(9 * [0.5], 0.3)

        # this loop resembles optimize()
        while not optim.stop():  # iterate
            X = optim.ask()      # get candidate solutions
            f = [elli(x) for x in X]  # evaluate solutions
            #  in case do something else that needs to be done
            optim.tell(X, f)     # do all the real "update" work
            optim.disp(20)       # display info every 20th iteration
            optim.logger.add()   # log another "data line", non-standard

        # final output
        print('termination by', optim.stop())
        print('best f-value =', optim.result[1])
        print('best solution =', optim.result[0])
        optim.logger.plot()  # if matplotlib is available

    Details
    -------
    Most of the work is done in the methods `tell` or `ask`. The property
    `result` provides more useful output.

c                 N    || _         || _        || _        | j                          y)z"``xstart`` is a mandatory argumentN)xstartmore_mandatory_argsoptional_kwargs
initialize)r   r&   r'   r(   s       r   r   zOOOptimizer.__init__L   s#    #6 .r   c                     t        d      )z(re-)set to the initial statez8method initialize() must be implemented in derived class)NotImplementedError	countiterr&   xcurrent)r   xis     r   r)   zOOOptimizer.initializeR   s    !"\]]r   c                     t        d      )z|abstract method, AKA "get" or "sample_distribution", deliver
        new candidate solution(s), a list of "vectors"
        z1method ask() must be implemented in derived classr+   )r   r(   s     r   askzOOOptimizer.askW   s     ""UVVr   c                 B    | xj                   dz  c_         t        d      )z\abstract method, AKA "update", pass f-values and prepare for
        next iteration
        r   z2method tell() must be implemented in derived class)r,   r+   )r   	solutionsfunction_valuess      r   tellzOOOptimizer.tell\   s     	!!"VWWr   c                     t        d      )aS  abstract method, return satisfied termination conditions in a
        dictionary like ``{'termination reason': value, ...}`` or ``{}``.

        For example ``{'tolfun': 1e-12}``, or the empty dictionary ``{}``.

        TODO: this should rather be a property!? Unfortunately, a change
        would break backwards compatibility.
        z method stop() is not implementedr0   r   s    r   stopzOOOptimizer.stopb   s     ""DEEr   Nc                      y)zabstract method, display some iteration info when
        ``self.iteration_counter % modulo < 1``, using a reasonable
        default for `modulo` if ``modulo is None``.
        Nr   )r   modulos     r   dispzOOOptimizer.displ   s    r   c                     t        d      )zoabstract property, contain ``(x, f(x), ...)``, that is, the
        minimizer, its function value, ...
        z"result property is not implemented)r+   r-   r   s    r   resultzOOOptimizer.resultq   s    
 ""FGGr   c	                 <   |	r7dt        |	      dkD  rdnddt        |	      d}
t        j                  |
       |!||kD  rt        j                  d||fz         |}| j	                  |      }d	\  }}t        xs t        ||d
k(  rdn|      5 }| j                         r||k  r|r||k\  s|r||k\  r| cddd       S |dz  }| j                         } |||      }|t        |      z  }| j                  ||       |D ]
  } ||         | j                  |       | j                         s||k  rddd       | j                          ||dkD  r%	 | j                  d   dkD  r| j                          | S | S # 1 sw Y   GxY w# t        $ r |r| j                  d       t        d| j                                	 t        d| j                   d          t        d| j                   d          Y | S # t"        t$        t&        t(        t        f$ r Y Y | S w xY wY | S w xY w)a	  find minimizer of ``objective_fct``.

        CAVEAT: the return value for `optimize` has changed to ``self``,
        allowing for a call like::

            solver = OOOptimizer(x0).optimize(f)

        and investigate the state of the solver.

        Arguments
        ---------

        ``objective_fct``: f(x: array_like) -> float
            function be to minimized
        ``maxfun``: number
            maximal number of function evaluations
        ``iterations``: number
            number of (maximal) iterations, while ``not self.stop()``,
            it can be useful to conduct only one iteration at a time.
        ``min_iterations``: number
            minimal number of iterations, even if ``not self.stop()``
        ``args``: sequence_like
            arguments passed to ``objective_fct``
        ``verb_disp``: number
            print to screen every ``verb_disp`` iteration, if `None`
            the value from ``self.logger`` is "inherited", if
            available.
        ``callback``: callable or list of callables
            callback function called like ``callback(self)`` or
            a list of call back functions called in the same way. If
            available, ``self.logger.add`` is added to this list.
            TODO: currently there is no way to prevent this other than
            changing the code of `_prepare_callback_list`.
        ``n_jobs=0``: number of processes to be acquired for
            multiprocessing to parallelize calls to `objective_fct`.
            Must be >1 to expect any speed-up or `None` or `-1`, which
            both default to the number of available CPUs. The default
            ``n_jobs=0`` avoids the use of multiprocessing altogether.

        ``return self``, that is, the `OOOptimizer` instance.

        Example
        -------
        >>> import cma
        >>> es = cma.CMAEvolutionStrategy(7 * [0.1], 0.1
        ...              ).optimize(cma.ff.rosen, verb_disp=100)
        ...                   #doctest: +ELLIPSIS
        (4_w,9)-aCMA-ES (mu_w=2.8,w_1=49%) in dimension 7 (seed=...)
        Iterat #Fevals   function value  axis ratio  sigma ...
            1      9 ...
            2     18 ...
            3     27 ...
          100    900 ...
        >>> cma.s.Mh.vequals_approximately(es.result[0], 7 * [1], 1e-5)
        True

    zignoring unkown argumentr   s  z in OOOptimizer.optimizeNz+doing min_iterations = %d > %d = iterations)r   r   )r   r   	verb_dispztermination byzbest f-value =z
solution =)lenstrwarningswarn_prepare_callback_listr   r	   r7   r1   r5   r:   _force_final_loggingoptsresult_pretty	Exceptionprintr<   AttributeError	TypeError
IndexErrorKeyError)r   objective_fctmaxfun
iterationsmin_iterationsr   rB   callbackn_jobsr   messagecitercevalseval_allr   fitvalsfs                    r   optimizezOOOptimizer.optimizey   s"   @ 6{QB.F=GMM !nz&AMMG#Z01 2'J..x8v+|]$*bLDf>AIiikU^%;v/5J#6> > 
HHJ"140#g,&		!W%!AdG "		)$ iikU^%;>$ 	!!#	A99[)A-&&( tC> >0  IIaL*DIIK8.A?lDKKN;  +Iz8YW   sI   %E9=A/E9-E9"F 9F6H<2G11HHHHHc                 .   |g }t        |      r|g}	 t        |      | j                  j                  gz   }	 |D ]$  }t        |      rt        dt        |      z         	 |S # t        $ r Y 8w xY w# t        $ r t        dt        |      z        w xY w)zreturn a list of callbacks including ``self.logger.add``.

        ``callback`` can be a `callable` or a `list` (or iterable) of
        callables. Otherwise a `ValueError` exception is raised.
        z<callback argument %s is not
                        callablezcallback argument must be a `callable` or
                an iterable (e.g. a list) of callables, after some
                processing it was %s)callablelistloggeraddrM   
ValueErrorrD   rN   )r   rU   cs      r   rG   z"OOOptimizer._prepare_callback_list   s     HH zH	H~(99H	9{$ &$&)!f&- . .    		  	9 (*-h-8 9 9	9s"   #A$ A3 	A3 $	A0/A03!Bc                    	 | j                   sy	 	 t        | j                   j                        }	 | j                   j	                  | |       y# t        $ r Y yw xY w# t        $ r d}Y ;w xY w# t        $ r Y yt
        $ rM 	 | j                   j	                  |        Y y# t        $ r"}t        dt        |      z         Y d}~Y yd}~ww xY ww xY w)ztry force the logger to log NOWNT)r9   zp  The final call of the logger in OOOptimizer._force_final_logging from OOOptimizer.optimize did not succeed: %s)	ra   rM   boolr9   rb   rN   rK   rL   rD   )r   r9   es      r   rH   z OOOptimizer._force_final_logging  s    	;; 
	$++,,-F	 KKOODO0  		
  	F	  	 	  %   B A     	 sW   A A A/ 	AAA,+A,/	C:CB  	C)C CCCr   )NNr   r   NNr   )r   r    r!   r"   r   r)   r1   r5   r7   r:   propertyr<   r]   rG   rH   r   r   r   r$   r$      s`    9t3
W
X	F
   ?@n`2 r   r$   c                       e Zd ZdZd ZddZd ZddZd Ze	d        Z
e	d	        Ze	d
        Zd Zd ZddZddZd Zd Zy),StatisticalModelSamplerWithZeroMeanBaseClasszWyet versatile base class to replace a sampler namely in
    `CMAEvolutionStrategy`
    c                 ^    	 t        |      }t        # t        $ r |}|dgz  }Y t        w xY w)zpass the vector of initial standard deviations or dimension of
        the underlying sample space.

        Ideally catch the case when `std_vec` is a scalar and then
        interpreted as dimension.
        r   )rC   rN   r+   )r   std_vecr   	dimensions       r   r   z5StatisticalModelSamplerWithZeroMeanBaseClass.__init__  s?    	&GI "!  	&I1#oG!!	&s    ,,Nc                     t         )zreturn list of i.i.d. samples.

        :param number: is the number of samples.
        :param update: controls a possibly lazy update of the sampler.
        r0   )r   numberupdates      r   samplez3StatisticalModelSamplerWithZeroMeanBaseClass.sample-  s
     "!r   c                     t         )zd``vectors`` is a list of samples, ``weights`` a corrsponding
        list of learning rates
        r0   )r   vectorsweightss      r   rp   z3StatisticalModelSamplerWithZeroMeanBaseClass.update5  
     "!r   c           
         t        | d      r:t        | d      r.|| j                  k(  s||| j                  k(  s|| j                  S || _        d}||}|| _        t	        d||z  f      dz  | j
                  dz   dz  |z   z  }d}t        |t	        d|z
  |d|z   dz
  d|z  z   z  | j
                  dz   dz  ||z  dz  z   z  f      	      | _        | j                  S )
zireturn `dict` with (default) parameters, e.g., `c1` and `cmu`.

        :See also: `RecombinationWeights`_mueff_lam   r      g?g       @g      ?)c1cmu)hasattrrw   rx   _parametersminrm   dict)r   muefflam	lower_lamr{   alphas         r   
parametersz7StatisticalModelSamplerWithZeroMeanBaseClass.parameters;  s    D(#f(=dkk!U]DII###	;C	 !S9_%&*t~~/Cc.IE.QRQV dUlQ.U:;~~)A-0AACD E
 r   c                 B    t        | j                  |      dz        dz  S )z;return Mahalanobis norm of `x` w.r.t. the statistical modelrz   g      ?)sumtransform_inverser   r   s     r   normz1StatisticalModelSamplerWithZeroMeanBaseClass.normV  s"    4))!,a/0#55r   c                     t         r   r0   r   s    r   condition_numberz=StatisticalModelSamplerWithZeroMeanBaseClass.condition_numberY      !!r   c                     t         r   r0   r   s    r   covariance_matrixz>StatisticalModelSamplerWithZeroMeanBaseClass.covariance_matrix\  r   r   c                     t         )z.vector of coordinate-wise (marginal) variancesr0   r   s    r   	variancesz6StatisticalModelSamplerWithZeroMeanBaseClass.variances_  s
     "!r   c                     t         )z;transform ``x`` as implied from the distribution parametersr0   r   s     r   	transformz6StatisticalModelSamplerWithZeroMeanBaseClass.transformd  r   r   c                     t         r   r0   r   s     r   r   z>StatisticalModelSamplerWithZeroMeanBaseClass.transform_inverseh      !!r   c                     t         )z2return inverse of associated linear transformationr0   r   resets     r    to_linear_transformation_inversezMStatisticalModelSamplerWithZeroMeanBaseClass.to_linear_transformation_inversek  r   r   c                     t         )z'return associated linear transformationr0   r   s     r   to_linear_transformationzEStatisticalModelSamplerWithZeroMeanBaseClass.to_linear_transformationo  r   r   c                     t         )zreturn scalar correction ``alpha`` such that ``X`` and ``f``
        fit to ``f(x) = (x-mean) (alpha * C)**-1 (x-mean)``
        r0   )r   meanr   r\   s       r   !inverse_hessian_scalar_correctionzNStatisticalModelSamplerWithZeroMeanBaseClass.inverse_hessian_scalar_corrections  ru   r   c                     t         r   r0   )r   factors     r   __imul__z5StatisticalModelSamplerWithZeroMeanBaseClass.__imul__y  r   r   r   NN)F)r   r    r!   r"   r   rq   rp   r   r   rh   r   r   r   r   r   r   r   r   r   r   r   r   rj   rj     sv    """ 66 " "" "" """""""r   rj   c                   P    e Zd ZdZd Zd ZddZd Zd ZddZ	dd	Z
ed
        Zy)BaseDataLoggerzabstract base class for a data logger that can be used with an
    `OOOptimizer`.

    Details: attribute `modulo` is used in `OOOptimizer.optimize`.
    c                 2    d | _         	 d | _        	 d| _        y )Nz_BaseDataLogger_datadict.py)optim_datafilenamer   s    r   r   zBaseDataLogger.__init__  s     
5
#5Er   c                     || _         | S )z~register an optimizer ``optim``, only needed if method `add` is
        called without passing the ``optim`` argument
        )r   )r   r   r   r   s       r   registerzBaseDataLogger.register  s     
r   Nc                     t         )zabstract method, add a "data point" from the state of ``optim``
        into the logger.

        The argument ``optim`` can be omitted if ``optim`` was
        ``register`` ()-ed before, acts like an event handler
        r0   )r   r   	more_datar   s       r   rb   zBaseDataLogger.add  s
     "!r   c                 D    t        dt        t        |             z          y)z(abstract method, display some data tracezEmethod BaseDataLogger.disp() not implemented, to be done in subclass NrL   rD   typer   s      r   r:   zBaseDataLogger.disp  s    UX[\`ae\fXgghr   c                 D    t        dt        t        |             z          y)zabstract method, plot datazHmethod BaseDataLogger.plot() is not implemented, to be done in subclass Nr   r   s      r   plotzBaseDataLogger.plot  s    X[^_cdh_i[jjkr   c                     t        |xs | j                  d      5 }|j                  t        | j                               ddd       y# 1 sw Y   yxY w)z+save data to file `name` or `self.filename`wN)openr   writereprr   )r   namer\   s      r   savezBaseDataLogger.save  s8    $'$---GGD$% .--s   %A		Ac                     ddl m} t        |xs | j                  d      5 } ||j	                               | _        ddd       | S # 1 sw Y   | S xY w)z-load data from file `name` or `self.filename`r   )literal_evalrN)astr   r   r   readr   )r   r   r   r\   s       r   loadzBaseDataLogger.load  sA    $$'$---%affh/DJ . .s   AAc                     | j                   S )zlogged data in a dictionary)r   r   s    r   datazBaseDataLogger.data  s     zzr   r   r   )r   r    r!   r"   r   r   rb   r:   r   r   r   rh   r   r   r   r   r   r   |  sA    F"il&
  r   r   )r"   
__future__r   r   r   rE   optimization_toolsr   objectr	   r$   rj   r   r   r   r   <module>r      s]    8 @ @ 2X~.6 .H & H T_"6 _"B5V 5o s   A A