Ë
    £�Dj¡%  ã                   ó–  — d Z ddlZddlmZ ddlmZ  G d„ d«      Z G d„ de«      Z G d	„ d
e«      Z	e
dk(  �rd„ Zd„ Zd„ Zd„ Z ej                  ddd«      Z ej"                  g d¢«      Z eee«      Zedej(                  j+                   ee«      ¬«      z  z   Z ej0                  eeeefd¬«      Z e	ee«      Zej7                  d¬«      Z ej:                  eee«      \  ZZ ej@                   ejB                  e«      «      Z" e#ed   «        e#e«        e#ej$                  «        e#e"«        e#ejH                  «       yy)zVNon-linear least squares



Author: Josef Perktold based on scipy.optimize.curve_fit

é    N)Úoptimize)ÚModelc                   ó   — e Zd ZdZy)ÚResultsz^just a dummy placeholder for now
    most results from RegressionResults can be used here
    N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__© ó    úcC:\Crop_Prediction\Backend\crop-ai-system\venv\Lib\site-packages\statsmodels/miscmodels/nonlinls.pyr   r      s   „ ñð 	r   r   c                   óZ   — e Zd ZdZ	 	 dd„Zdd„Zd„ Zd„ Zdd„Zd„ Z	dd	„Z
d
„ Zdd„Zd„ Zy)ÚNonlinearLSaP  Base class for estimation of a non-linear model with least squares

    This class is supposed to be subclassed, and the subclass has to provide a method
    `_predict` that defines the non-linear function `f(params) that is predicting the endogenous
    variable. The model is assumed to be

    :math: y = f(params) + error

    and the estimator minimizes the sum of squares of the estimated error.

    :math: min_parmas \sum (y - f(params))**2

    f has to return the prediction for each observation. Exogenous or explanatory variables
    should be accessed as attributes of the class instance, and can be given as arguments
    when the instance is created.

    Warning:
    Weights are not correctly handled yet in the results statistics,
    but included when estimating the parameters.

    similar to scipy.optimize.curve_fit
    API difference: params are array_like not split up, need n_params information

    includes now weights similar to curve_fit
    no general sigma yet (OLS and WLS, but no GLS)

    This is currently holding on to intermediate results that are not necessary
    but useful for testing.

    Fit returns and instance of RegressionResult, in contrast to the linear
    model, results in this case are based on a local approximation, essentially
    y = f(X, params) is replaced by y = grad * params where grad is the Gradient
    or Jacobian with the shape (nobs, nparams). See for example Greene

    Examples
    --------

    class Myfunc(NonlinearLS):

        def _predict(self, params):
            x = self.exog
            a, b, c = params
            return a*np.exp(-b*x) + c

    Ff we have data (y, x), we can create an instance and fit it with

    mymod = Myfunc(y, x)
    myres = mymod.fit(nparams=3)

    and use the non-linear regression results, for example

    myres.params
    myres.bse
    myres.tvalues


    Nc                 ó´   — || _         || _        |�At        j                  |«      }|j                  dk  r|| _        d|z  | _        y t        d«      ‚d | _        y )Né   g      ð?z%correlated errors are not handled yet)ÚendogÚexogÚnpÚasarrayÚndimÚsigmaÚweightsÚ
ValueError)Úselfr   r   r   r   Úmissings         r   Ú__init__zNonlinearLS.__init__q   sT   € àˆŒ
ØˆŒ	ØÐÜ—J‘J˜uÓ%ˆEØ�z‰z˜AŠ~Ø"�”
Ø! %™x�•ä Ð!HÓIÐIàˆD�Lr   c                 ó$   — | j                  |«      S ©N)Ú_predict)r   r   Úparamss      r   ÚpredictzNonlinearLS.predict   s   € à�}‰}˜VÓ$Ð$r   c                  ó   — y r   r   ©r   r    s     r   r   zNonlinearLS._predict„   s   € Ør   c                  ó   — y r   r   )r   s    r   Ústart_valuezNonlinearLS.start_value‡   s   € Ør   c                 ó´   — |€6| j                   €| j                  | j                  |«      z
  S | j                   }|| j                  | j                  |«      z
  z  S r   )r   r   r   )r   r    r   s      r   Ú	geterrorszNonlinearLS.geterrorsŠ   sO   € Øˆ?Ø�|‰|Ð#Ø—z‘z D§M¡M°&Ó$9Ñ9Ð9àŸ,™,�Ø˜$Ÿ*™* t§}¡}°VÓ'<Ñ<Ñ=Ð=r   c                 óF   — | j                  |«      dz  j                  «       S ©Nr   )r'   Úsumr#   s     r   ÚerrorsumsquareszNonlinearLS.errorsumsquares’   s   € Ø—‘˜vÓ&¨Ñ)×.Ñ.Ó0Ð0r   c                 óª  — |�|}n9| j                  «       }|�n&|�dt        j                  |«      z  }nt        d«      ‚| j                  }t        j                  ||fddi|¤Ž}|\  }}}	}
}|dvrd|
z   }t        |«      ‚|	d   }| j                  }t        |«      t        |«      kD  r3|�1|dz  j                  «       t        |«      t        |«      z
  z  }||z  }nd }t        |«      t        |«      z
  | _        t        |«      | _        t        «       }||_        ||_        ||_        | j                  | _        | j%                  |«      | _        t        j(                  j+                  | j&                  «      }t        j,                  |t        j.                  |«      «      | _        d	d
lm} |}|} || || j0                  ¬«      }||_        || _        |S )Ngš™™™™™¹?z3need information about start values foroptimizationÚfull_outputé   )r.   r   é   é   zOptimal parameters not found: Úfvecr   r   )ÚRegressionResults)Únormalized_cov_params)r%   r   Úonesr   r'   r   ÚleastsqÚRuntimeErrorr   Úlenr*   Údf_residÚdf_modelr   r    ÚpcovÚrawresÚwendogÚjac_predictÚwexogÚlinalgÚpinvÚdotÚ	transposer3   Ústatsmodels.regressionr2   ÚfitresÚ_results)r   r%   ÚnparamsÚkwÚp0ÚfuncÚresÚpoptr:   ÚinfodictÚerrmsgÚierÚmsgÚerrÚydataÚs_sqrD   Ú
pinv_wexogr2   ÚresultsÚbetaÚlfits                         r   ÚfitzNonlinearLS.fit–   sÉ  € ð
 Ð"Ø‰Bð ×!Ñ!Ó#ˆBØˆ~ØØÐ$Øœ2Ÿ7™7 7Ó+Ñ+‘ä ð ",ó -ð -ð �~‰~ˆÜ×Ñ˜t RÑ=°QÐ=¸"Ñ=ˆØ.1Ñ+ˆˆt�X˜v sà�iÑØ2°VÑ;ˆCÜ˜sÓ#Ð#à�vÑˆà—
‘
ˆÜ�‹Jœ˜R›Ò  dÐ&6ð ˜‘F—<‘<“>¤3 u£:¬c°"«gÑ#5Ñ6ˆDØ˜$‘;‰DàˆDä˜E›
¤3 r£7Ñ*ˆŒÜ˜B›ˆŒÜ“ˆØˆŒØˆŒØˆŒØ—j‘jˆŒØ×%Ñ% dÓ+ˆŒ
Ü—Y‘Y—^‘^ D§J¡JÓ/ˆ
Ü%'§V¡V¨JÜ)+¯©°jÓ)Aó&CˆÔ"õ 	=Ø#ˆàˆÙ   tØ-1×-GÑ-GôIˆð ˆŒØˆŒØˆr   c                 óP   — | j                   }t        j                  ||fddi|¤Ž}|S )z*minimal fitting with no extra calculationsr-   r   )r'   r   r5   )r   r%   ÚkwargsrI   rJ   s        r   Úfit_minimalzNonlinearLS.fit_minimalÙ   s,   € à�~‰~ˆÜ×Ñ˜t [ÑJ¸aÐJÀ6ÑJˆØˆ
r   c           	      ó  — |€| j                   }|€%t        j                  j                  dd||f¬«      }n |||f¬«      }t        j                  |D �cg c]&  }t        j
                  | j                  |«      |f   ‘Œ( c}«      }|S c c}w )z^fit with random starting values

        this could be replaced with a global fitter

        iöÿÿÿé
   )ÚlowÚhighÚsize©r_   )rF   r   ÚrandomÚuniformÚarrayÚr_rZ   )r   ÚntriesÚrvs_generatorrF   ÚrvsÚrvrT   s          r   Ú
fit_randomzNonlinearLS.fit_randomß   s†   € ð ˆ?Ø—l‘lˆGØÐ Ü—)‘)×#Ñ#¨°"¸FÀGÐ;LÐ#ÓM‰Cá f¨gÐ%6Ô7ˆCä—(‘(ÀsÖKÀœBŸE™E $×"2Ñ"2°2Ó"6¸Ð";Ó<ÒKÓLˆð ˆùò Ls   Á+Bc                 ó8   — ddl m}  ||| j                  «      }|S )z·jacobian of prediction function using complex step derivative

        This assumes that the predict function does not use complex variable
        but is designed to do so.

        r   )Úapprox_fprime_cs)Ústatsmodels.tools.numdiffrk   r   )r   r    rk   Ú	jaccs_errs       r   r=   zNonlinearLS.jac_predictò   s   € õ 	?á$ V¨T¯]©]Ó;ˆ	ØÐr   )NNNNÚnoner   )NN)r\   NN)r   r   r	   r
   r   r!   r   r%   r'   r+   rW   rZ   ri   r=   r   r   r   r   r   6   sF   „ ñ8ðt CGØó ó%ò
òó>ò1óAòFóó&
r   r   c                   ó   — e Zd Zd„ Zy)ÚMyfuncc                 ód   — | j                   }|\  }}}|t        j                  | |z  «      z  |z   S r   )r   r   Úexp)r   r    ÚxÚaÚbÚcs         r   r   zMyfunc._predict
  s3   € Ø�I‰IˆØ‰ˆˆ1ˆaØ”—‘˜˜˜1™“‰~ Ñ!Ð!r   N)r   r   r	   r   r   r   r   rp   rp   ÿ   s   „ ó"r   rp   Ú__main__c                 ó@   — |t        j                  | | z  «      z  |z   S r   ©r   rr   )rs   rt   ru   rv   s       r   Úfunc0rz     s   € Ø”—‘˜˜˜1™“‰~ Ñ!Ð!r   c                 óL   — | \  }}}|t        j                  | |z  «      z  |z   S r   ry   )r    rs   rt   ru   rv   s        r   rI   rI     s*   € Ø‰ˆˆ1ˆaØ”—‘˜˜˜1™“‰~ Ñ!Ð!r   c                 ó    — |t        | |«      z
  S r   ©rI   ©r    rs   Úys      r   Úerrorr€     s   € Ø”4˜ “?Ñ"Ð"r   c                 ó&   — |t        | |«      z
  dz  S r)   r}   r~   s      r   Úerror2r‚     s   € Ø”D˜ “OÑ# aÑ'Ð'r   r0   é2   )g      @gÍÌÌÌÌÌô?g      à?gš™™™™™É?r`   T)Úargsr-   r/   )rF   )%r
   Únumpyr   Úscipyr   Ústatsmodels.base.modelr   r   r   rp   r   rz   rI   r€   r‚   Úlinspacers   rc   r    Úy0ra   Únormalr7   r   r5   rJ   ÚmodrW   ÚresmyÚ	curve_fitÚ	cf_paramsÚcf_pcovÚsqrtÚdiagÚcf_bseÚprintÚbser   r   r   ú<module>r•      sV  ðñó Ý å (÷	ñ 	ôPF�%ô FôR"ˆ[ô "ð( ˆzÓò"ò"ò#ò(ð 	ˆ�‰�A�a˜Ó€AØˆR�X‰X’oÓ&€FÙ	ˆf�a‹€BØ
ˆS�—‘×!Ñ!¡s¨1£vÐ!Ó.Ñ.Ñ.€Aà
ˆ(×
Ñ
˜5 &°°1¨vÀ4Ô
H€Cñ ��A‹,€CØ�G‰G˜AˆGÓ€Eà+˜×+Ñ+¨E°1°aÓ8Ñ€IˆwØˆR�W‰W�W�R—W‘W˜WÓ%Ó&€FÙ	ˆ#ˆa‰&„MÙ	ˆ)ÔÙ	ˆ%�,‰,ÔÙ	ˆ&„MÙ	ˆ%�)‰)ÕðE r   