L itdZddlZddlZddlZddlZddlmZm Z dgZ ejdejjejdejjfZ eje ZGd d ZGd d ZGd dZGddZGddZGddZe ddd dddddZy)z> basinhopping: The basinhopping global optimization algorithm N)check_random_state_transition_to_rng basinhoppingres_new)kindres_old) parametersc(eZdZdZdZdZdZdZy)Storagez9 Class used to store the lowest energy structure c&|j|yN)_addselfminress b/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/optimize/_basinhopping.py__init__zStorage.__init__s &cn||_tj|j|j_yr )rnpcopyxrs rrz Storage._adds! ) rc|jrK|j|jjks|jjs|j|yy)NTF)successfunrrrs rupdatezStorage.updates; >>vzzDKKOO;&*kk&9&9 IIf rc|jSr )r)rs r get_lowestzStorage.get_lowest%s {{rN)__name__ __module__ __qualname____doc__rrrrrrr r s*rr c*eZdZdZddZdZdZdZy)BasinHoppingRunnera;This class implements the core of the basinhopping algorithm. x0 : ndarray The starting coordinates. minimizer : callable The local minimizer, with signature ``result = minimizer(x)``. The return value is an `optimize.OptimizeResult` object. step_taking : callable This function displaces the coordinates randomly. Signature should be ``x_new = step_taking(x)``. Note that `x` may be modified in-place. accept_tests : list of callables Each test is passed the kwargs `f_new`, `x_new`, `f_old` and `x_old`. These tests will be used to judge whether or not to accept the step. The acceptable return values are True, False, or ``"force accept"``. If any of the tests return False then the step is rejected. If ``"force accept"``, then this will override any other tests in order to accept the step. This can be used, for example, to forcefully escape from a local minimum that ``basinhopping`` is trapped in. disp : bool, optional Display status messages. cvtj||_||_||_||_||_d|_tjj|_ d|j_ ||j}|js6|jxjdz c_ |j r tdtj|j|_|j|_||_|j r&td|jd|j dt%||_t)|dr|j*|j_t)|dr|j,|j_t)|d r|j.|j_yy) Nr1warning: basinhopping: local minimization failurebasinhopping step : f gnfevnjevnhev)rrr minimizer step_taking accept_testsdispnstepscipyoptimizeOptimizeResultresminimization_failuresrprintrenergyincumbent_minresr storagehasattrr,r-r.)rx0r/r0r1r2rs rrzBasinHoppingRunner.__init__@s?"&(  >>002)*&466"~~ HH * *a / *yyIJ"jj & 99 &tzzl$t{{1oF Gv 66 ""KKDHHM 66 ""KKDHHM 66 ""KKDHHM #rctj|j}|j|}|j |}|j}|j }|j s6|jxjdz c_|jr tdt|dr)|jxj|jz c_ t|dr)|jxj|jz c_ t|dr)|jxj|jz c_d}|jD]n}t!j"|t$k(r|||j&}n ||||j(|j}|d k(rd}n| t+d |rmd }pt|jd r4|jj-||||j(|j||fS) zDo one Monte Carlo iteration Randomly displace the coordinates, minimize, and decide whether or not to accept the new coordinates. r'r(r,r-r.T)rr)f_newx_newf_oldx_oldz force acceptz7accept_tests must return True, False, or 'force accept'Freport)rrrr0r/rrr7r8r2r9r=r,r-r.r1inspect signature_new_accept_test_signaturer;r: ValueErrorrD)r x_after_steprx_after_quenchenergy_after_quenchaccepttesttestress r_monte_carlo_stepz$BasinHoppingRunner._monte_carlo_stepcswwtvv '' 5  -$jj~~ HH * *a / *yyIJ 66 " HHMMV[[ (M 66 " HHMMV[[ (M 66 " HHMMV[[ (M%% D  &*DDvt7L7LM%8%)[[@.( "233 $ 4##X .    # #F2E*8 *.&& $ 2v~rc|xjdz c_d}|j\}}|rW|j|_t j |j |_||_|jj|}|jrD|j|j||r&td|jd|jd|j |_ |j|_||_|S)z3Do one cycle of the basinhopping algorithm r'Fz!found new global minimum on step z with function value r+)r3rOrr:rrrr;r<rr2 print_reportr9xtrial energy_trialrL)rnew_global_minrLrs r one_cyclezBasinHoppingRunner.one_cycles a //1  **DKWWVXX&DF$*D !!\\008N 99   fjj& 17 |D&&*kk!_6 hh "JJ rc |jj}td|jd|jdd|dd|d|j d y)zprint a status updater)r*r+z trial_f z accepted z lowest_f N)r<rr9r3r:r)rrSrLrs rrQzBasinHoppingRunner.print_reports\((*   DQ@#A&j9 1~ ' rN)F)rr r!r"rrOrUrQr#rrr%r%)s,!(F7r< rr%c4eZdZdZ ddZdZdZdZdZy) AdaptiveStepsizea Class to implement adaptive stepsize. This class wraps the step taking class and modifies the stepsize to ensure the true acceptance rate is as close as possible to the target. Parameters ---------- takestep : callable The step taking routine. Must contain modifiable attribute takestep.stepsize accept_rate : float, optional The target step acceptance rate interval : int, optional Interval for how often to update the stepsize factor : float, optional The step size is multiplied or divided by this factor upon each update. verbose : bool, optional Print information about each update ct||_||_||_||_||_d|_d|_d|_y)Nr)takesteptarget_accept_rateintervalfactorverboser3 nstep_totnaccept)rrZ accept_rater\r]r^s rrzAdaptiveStepsize.__init__s;  "-      rc$|j|Sr ) take_steprrs r__call__zAdaptiveStepsize.__call__s~~a  rc |jj}t|j|jz }||j kDr*|jxj|j zc_n)|jxj|j zc_|jr:td|dd|j dd|jjdd|dyy)Nz#adaptive stepsize: acceptance rate fz target z new stepsize r+z old stepsize ) rZstepsizefloatr`r3r[r]r^r9)r old_stepsizeras r_adjust_step_sizez"AdaptiveStepsize._adjust_step_sizes}}-- DLL)DJJ6 00 0 MM " "dkk 1 " MM " "dkk 1 " << 7 Ah,,Q/~]]++A.n\!s rrezMinimizerWrapper.__call__&sF 99 !4>>"4 4 4!4>>$))R?4;;? ?rr ryr#rrr{r{s @rr{c$eZdZdZddZdZdZy) MetropolisaMetropolis acceptance criterion. Parameters ---------- T : float The "temperature" parameter for the accept or reject criterion. rng : {None, int, `numpy.random.Generator`}, optional Random number generator used for acceptance test. NcX|dk7rd|z n td|_t||_y)Nr?inf)ribetarru)rTrus rrzMetropolis.__init__9s' !AvC!G5< %c*rc\tjd5|j|jz |jz}t j t d|}ddd|jj}|k\xr|jxs |j S#1swYExYw)a  Assuming the local search underlying res_new was successful: If new energy is lower than old, it will always be accepted. If new is higher than old, there is a chance it will be accepted, less likely for larger differences. ignore)invalidrN) rerrstaterrmathexpminrurwr)rrrprodwrands r accept_rejectzMetropolis.accept_reject@s[[ * '[[7;;./$));DQ&A 'xx!DyEgooDW__1DE ' 's AB""B+c8t|j||S)z9 f_new and f_old are mandatory in kwargs )boolr)rrrs rrezMetropolis.__call__VsD&&w899rr )rr r!r"rrrer#rrrr-s +F,:rrseed T) position_num replace_docrorq)r[stepwise_factorc | dks| dk\r td|dks|dk\r tdtj|}t| } | t }t t jj|fi|}|6t|s tdt|drt|| | || }n |}nt|| }t|| | || }g}|t|s td |g}t|| }|j|| |d z} t!||||| }t|rF||j"j$j&|j"j$j(d d\}}dg}t+|D]b}|j-}t|r1||j.|j0|j2}||rdg}n|dz }|rd}Y|| kDs_dg}n|j4}|j"j7|_tj:|j8j&|_|j8j(|_||_|dz|_|j8j@|_ |S)a6Find the global minimum of a function using the basin-hopping algorithm. Basin-hopping is a two-phase method that combines a global stepping algorithm with local minimization at each step. Designed to mimic the natural process of energy minimization of clusters of atoms, it works well for similar problems with "funnel-like, but rugged" energy landscapes [5]_. As the step-taking, step acceptance, and minimization methods are all customizable, this function can also be used to implement other two-phase methods. Parameters ---------- func : callable ``f(x, *args)`` Function to be optimized. ``args`` can be passed as an optional item in the dict `minimizer_kwargs` x0 : array_like Initial guess. niter : integer, optional The number of basin-hopping iterations. There will be a total of ``niter + 1`` runs of the local minimizer. T : float, optional The "temperature" parameter for the acceptance or rejection criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float, optional Maximum step size for use in the random displacement. minimizer_kwargs : dict, optional Extra keyword arguments to be passed to the local minimizer `scipy.optimize.minimize` Some important options could be: method : str The minimization method (e.g. ``"L-BFGS-B"``) args : tuple Extra arguments passed to the objective function (`func`) and its derivatives (Jacobian, Hessian). take_step : callable ``take_step(x)``, optional Replace the default step-taking routine with this routine. The default step-taking routine is a random displacement of the coordinates, but other step-taking algorithms may be better for some systems. `take_step` can optionally have the attribute ``take_step.stepsize``. If this attribute exists, then `basinhopping` will adjust ``take_step.stepsize`` in order to try to optimize the global minimum search. accept_test : callable, ``accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old)``, optional Define a test which will be used to judge whether to accept the step. This will be used in addition to the Metropolis test based on "temperature" `T`. The acceptable return values are True, False, or ``"force accept"``. If any of the tests return False then the step is rejected. If the latter, then this will override any other tests in order to accept the step. This can be used, for example, to forcefully escape from a local minimum that `basinhopping` is trapped in. callback : callable, ``callback(x, f, accept)``, optional A callback function which will be called for all minima found. ``x`` and ``f`` are the coordinates and function value of the trial minimum, and ``accept`` is whether that minimum was accepted. This can be used, for example, to save the lowest N minima found. Also, `callback` can be used to specify a user defined stop criterion by optionally returning True to stop the `basinhopping` routine. interval : integer, optional interval for how often to update the `stepsize` disp : bool, optional Set to True to print status messages niter_success : integer, optional Stop the run if the global minimum candidate remains the same for this number of iterations. rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. The random numbers generated only affect the default Metropolis `accept_test` and the default `take_step`. If you supply your own `take_step` and `accept_test`, and these functions use random number generation, then those functions are responsible for the state of their random number generator. target_accept_rate : float, optional The target acceptance rate that is used to adjust the `stepsize`. If the current acceptance rate is greater than the target, then the `stepsize` is increased. Otherwise, it is decreased. Range is (0, 1). Default is 0.5. .. versionadded:: 1.8.0 stepwise_factor : float, optional The `stepsize` is multiplied or divided by this stepwise factor upon each update. Range is (0, 1). Default is 0.9. .. versionadded:: 1.8.0 Returns ------- res : OptimizeResult The optimization result represented as a `OptimizeResult` object. Important attributes are: ``x`` the solution array, ``fun`` the value of the function at the solution, and ``message`` which describes the cause of the termination. The ``OptimizeResult`` object returned by the selected minimizer at the lowest minimum is also contained within this object and can be accessed through the ``lowest_optimization_result`` attribute. ``lowest_optimization_result`` will only be updated if a local minimization was successful. See `OptimizeResult` for a description of other attributes. See Also -------- minimize : The local minimization function called once for each basinhopping step. `minimizer_kwargs` is passed to this routine. Notes ----- Basin-hopping is a stochastic algorithm which attempts to find the global minimum of a smooth scalar function of one or more variables [1]_ [2]_ [3]_ [4]_. The algorithm in its current form was described by David Wales and Jonathan Doye [2]_ http://www-wales.ch.cam.ac.uk/. The algorithm is iterative with each cycle composed of the following features 1) random perturbation of the coordinates 2) local minimization 3) accept or reject the new coordinates based on the minimized function value The acceptance test used here is the Metropolis criterion of standard Monte Carlo algorithms, although there are many other possibilities [3]_. This global minimization method has been shown to be extremely efficient for a wide variety of problems in physics and chemistry. It is particularly useful when the function has many minima separated by large barriers. See the `Cambridge Cluster Database `_ for databases of molecular systems that have been optimized primarily using basin-hopping. This database includes minimization problems exceeding 300 degrees of freedom. See the free software program `GMIN `_ for a Fortran implementation of basin-hopping. This implementation has many variations of the procedure described above, including more advanced step taking algorithms and alternate acceptance criterion. For stochastic global optimization there is no way to determine if the true global minimum has actually been found. Instead, as a consistency check, the algorithm can be run from a number of different random starting points to ensure the lowest minimum found in each example has converged to the global minimum. For this reason, `basinhopping` will by default simply run for the number of iterations `niter` and return the lowest minimum found. It is left to the user to ensure that this is in fact the global minimum. Choosing `stepsize`: This is a crucial parameter in `basinhopping` and depends on the problem being solved. The step is chosen uniformly in the region from x0-stepsize to x0+stepsize, in each dimension. Ideally, it should be comparable to the typical separation (in argument values) between local minima of the function being optimized. `basinhopping` will, by default, adjust `stepsize` to find an optimal value, but this may take many iterations. You will get quicker results if you set a sensible initial value for ``stepsize``. Choosing `T`: The parameter `T` is the "temperature" used in the Metropolis criterion. Basinhopping steps are always accepted if ``func(xnew) < func(xold)``. Otherwise, they are accepted with probability:: exp( -(func(xnew) - func(xold)) / T ) So, for best results, `T` should to be comparable to the typical difference (in function values) between local minima. (The height of "walls" between local minima is irrelevant.) If `T` is 0, the algorithm becomes Monotonic Basin-Hopping, in which all steps that increase energy are rejected. .. versionadded:: 0.12.0 References ---------- .. [1] Wales, David J. 2003, Energy Landscapes, Cambridge University Press, Cambridge, UK. .. [2] Wales, D J, and Doye J P K, Global Optimization by Basin-Hopping and the Lowest Energy Structures of Lennard-Jones Clusters Containing up to 110 Atoms. Journal of Physical Chemistry A, 1997, 101, 5111. .. [3] Li, Z. and Scheraga, H. A., Monte Carlo-minimization approach to the multiple-minima problem in protein folding, Proc. Natl. Acad. Sci. USA, 1987, 84, 6611. .. [4] Wales, D. J. and Scheraga, H. A., Global optimization of clusters, crystals, and biomolecules, Science, 1999, 285, 1368. .. [5] Olson, B., Hashmi, I., Molloy, K., and Shehu1, A., Basin Hopping as a General and Versatile Optimization Framework for the Characterization of Biological Macromolecules, Advances in Artificial Intelligence, Volume 2012 (2012), Article ID 674832, :doi:`10.1155/2012/674832` Examples -------- The following example is a 1-D minimization problem, with many local minima superimposed on a parabola. >>> import numpy as np >>> from scipy.optimize import basinhopping >>> func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x >>> x0 = [1.] Basinhopping, internally, uses a local minimization algorithm. We will use the parameter `minimizer_kwargs` to tell basinhopping which algorithm to use and how to set up that minimizer. This parameter will be passed to `scipy.optimize.minimize`. >>> minimizer_kwargs = {"method": "BFGS"} >>> ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs, ... niter=200) >>> # the global minimum is: >>> ret.x, ret.fun -0.1951, -1.0009 Next consider a 2-D minimization problem. Also, this time, we will use gradient information to significantly speed up the search. >>> def func2d(x): ... f = np.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + ... 0.2) * x[0] ... df = np.zeros(2) ... df[0] = -14.5 * np.sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2 ... df[1] = 2. * x[1] + 0.2 ... return f, df We'll also use a different local minimization algorithm. Also, we must tell the minimizer that our function returns both energy and gradient (Jacobian). >>> minimizer_kwargs = {"method":"L-BFGS-B", "jac":True} >>> x0 = [1.0, 1.0] >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs, ... niter=200) >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0], ... ret.x[1], ... ret.fun)) global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109 Here is an example using a custom step-taking routine. Imagine you want the first coordinate to take larger steps than the rest of the coordinates. This can be implemented like so: >>> class MyTakeStep: ... def __init__(self, stepsize=0.5): ... self.stepsize = stepsize ... self.rng = np.random.default_rng() ... def __call__(self, x): ... s = self.stepsize ... x[0] += self.rng.uniform(-2.*s, 2.*s) ... x[1:] += self.rng.uniform(-s, s, x[1:].shape) ... return x Since ``MyTakeStep.stepsize`` exists basinhopping will adjust the magnitude of `stepsize` to optimize the search. We'll use the same 2-D function as before >>> mytakestep = MyTakeStep() >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs, ... niter=200, take_step=mytakestep) >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0], ... ret.x[1], ... ret.fun)) global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109 Now, let's do an example using a custom callback function which prints the value of every minimum found >>> def print_fun(x, f, accepted): ... print("at minimum %.4f accepted %d" % (f, int(accepted))) We'll run it for only 10 basinhopping steps this time. >>> rng = np.random.default_rng() >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs, ... niter=10, callback=print_fun, rng=rng) at minimum 0.4159 accepted 1 at minimum -0.4317 accepted 1 at minimum -1.0109 accepted 1 at minimum -0.9073 accepted 1 at minimum -0.4317 accepted 0 at minimum -0.1021 accepted 1 at minimum -0.7425 accepted 1 at minimum -0.9073 accepted 1 at minimum -0.4317 accepted 0 at minimum -0.7425 accepted 1 at minimum -0.9073 accepted 1 The minimum at -1.0109 is actually the global minimum, found already on the 8th iteration. grz,target_accept_rate has to be in range (0, 1)z)stepwise_factor has to be in range (0, 1)ztake_step must be callablerh)r\rar]r^)rhruzaccept_test must be callable)ru)r2T)rrzBrequested number of basinhopping iterations completed successfullyz7callback function requested stop early byreturning Truer'rzsuccess condition satisfied)!rHrarrayrdictr{r4r5minimizecallable TypeErrorr=rXrsrappendr%r<rrrrangerUrRrSrLr7rlowest_optimization_resultrmessagenitr)r}r>niterrrhminimizer_kwargsrc accept_testcallbackr\r2 niter_successrur[rwrapped_minimizertake_step_wrappeddisplacer1 metropolisbhcountirrTvalr7s rrr]sZ R#5#;GHH"2 5DEE "B S !C6()@)@$=+;= "89 9 9j ) 0H.& !  !* &xSA,X9K4C59; L $:; ;#} A3'J # B 13D(t 5B ""$$bjj&7&7&;&;TBHE1 G 5\ H 299booryyAC 01G   E ] "45G #( &&C%'ZZ%:%:%rs C   7  YW->->-K-K L 7  YW->->-K-K L N.W..'B.X X v??D. @ @ -:-:`F>69DHGKG25cG?Gr