
    M/Phl$                        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                             ee                    z  z   Z ej        eeeefd          Z e	ee          Ze                    d          Z ej        eee          \  ZZ ej          ej!        e                    Z" e#ed                     e#e            e#ej                    e#e"            e#ej$                   dS dS )zVNon-linear least squares



Author: Josef Perktold based on scipy.optimize.curve_fit

    N)optimize)Modelc                       e Zd ZdZdS )Resultsz^just a dummy placeholder for now
    most results from RegressionResults can be used here
    N)__name__
__module____qualname____doc__     _/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/miscmodels/nonlinls.pyr   r      s          	Dr   r   c                   \    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dS )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


    Nnonec                     || _         || _        |At          j        |          }|j        dk     r|| _        d|z  | _        d S t          d          d | _        d S )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   s`    
	Ju%%EzA~~"
!%x !HIIIDLLLr   c                 ,    |                      |          S N)_predict)r   r   paramss      r   predictzNonlinearLS.predict   s    }}V$$$r   c                     d S r   r   r   r!   s     r   r    zNonlinearLS._predict   s    r   c                     d S r   r   )r   s    r   start_valuezNonlinearLS.start_value   s    tr   c                     |+| j         | j        |                     |          z
  S | j         }|| j        |                     |          z
  z  S r   )r   r   r    )r   r!   r   s      r   	geterrorszNonlinearLS.geterrors   sM    ?|#zDMM&$9$999,$*t}}V'<'<<==r   c                 V    |                      |          dz                                  S Nr   )r(   sumr$   s     r   errorsumsquareszNonlinearLS.errorsumsquares   s%    v&&)..000r   c                    ||}n@|                                  }|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          |          k    r?|=|dz  
                                t          |          t          |          z
  z  }||z  }nd }t          |          t          |          z
  | _        t          |          | _        t                      }||_        ||_        ||_        | j        | _        |                     |          | _        t          j                            | j                  }t          j        |t          j        |                    | _        d	d
lm} |}|} || || j                  }||_        || _        |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	transposer4   statsmodels.regressionr3   fitres_results)r   r&   nparamskwp0funcrespoptr;   infodicterrmsgiermsgerrydatas_sqrE   
pinv_wexogr3   resultsbetalfits                         r   fitzNonlinearLS.fit   s   
 "BB !!##B~$277+++  ", - - - ~tR==Q="==.1+tXvsi2V;Cs###v
JJR  d&6 F<<>>3u::c"gg#56D$;DDDE

3r77*Bj%%d++
Y^^DJ//
%'VJ)+j)A)A&C &C" 	=<<<<<#  t-1-GI I I r   c                 >    | j         }t          j        ||fddi|}|S )z*minimal fitting with no extra calculationsr.   r   )r(   r   r6   )r   r&   kwargsrJ   rK   s        r   fit_minimalzNonlinearLS.fit_minimal   s-    ~t[JJaJ6JJ
r   
   c                      | j         }|%t          j                            dd||f          }n |||f          }t          j         fd|D                       }|S )z^fit with random starting values

        this could be replaced with a global fitter

        Nir\   )lowhighsizer`   c                 ^    g | ])}t           j                            |          |f         *S r   )r   r_r[   ).0rvr   s     r   
<listcomp>z*NonlinearLS.fit_random.<locals>.<listcomp>   s3    KKKBE$"2"22"6"6";<KKKr   )rG   r   randomuniformarray)r   ntriesrvs_generatorrG   rvsrU   s   `     r   
fit_randomzNonlinearLS.fit_random   s|     ?lG )##"FG;L#MMCC-fg%6777C(KKKKsKKKLL r   c                 4    ddl m}  ||| j                  }|S )zjacobian 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.numdiffro   r    )r   r!   ro   	jaccs_errs       r   r>   zNonlinearLS.jac_predict   s0     	?>>>>>$$VT];;	r   )NNNNr   r   )NN)r\   NN)r   r   r	   r
   r   r"   r    r&   r(   r,   rX   r[   rm   r>   r   r   r   r   r   6   s        8 8t CG       % % % %
    > > > >1 1 1A A A AF     &
 
 
 
 
r   r   c                       e Zd Zd ZdS )Myfuncc                 X    | j         }|\  }}}|t          j        | |z            z  |z   S r   )r   r   exp)r   r!   xabcs         r   r    zMyfunc._predict
  s1    I1a1~!!r   N)r   r   r	   r    r   r   r   rs   rs      s#        " " " " "r   rs   __main__c                 >    |t          j        | | z            z  |z   S r   r   ru   )rv   rw   rx   ry   s       r   func0r}     s    1~!!r   c                 J    | \  }}}|t          j        | |z            z  |z   S r   r|   )r!   rv   rw   rx   ry   s        r   rJ   rJ     s*    1a1~!!r   c                 (    |t          | |          z
  S r   rJ   r!   rv   ys      r   errorr     s    4??""r   c                 .    |t          | |          z
  dz  S r*   r   r   s      r   error2r     s    DOO#a''r   r1   2   )g      @g?g      ?g?ra   T)argsr.   r0   )rG   )%r
   numpyr   scipyr   statsmodels.base.modelr   r   r   rs   r   r}   rJ   r   r   linspacerv   ri   r!   y0rg   normalr8   r   r6   rK   modrX   resmy	curve_fit	cf_paramscf_pcovsqrtdiagcf_bseprintbser   r   r   <module>r      sQ              ( ( ( ( ( (	 	 	 	 	 	 	 	PF F F F F% F F FR" " " " "[ " " "( z" " "" " "# # #( ( ( 	AaARXooo&&F	faB
S!!ss1vv!....A
(
5&1v4
H
H
HC &A,,CGGAGE++E1a88IwRWWRWW%%&&F	E#a&MMM	E)	E%,	E&MMM	E%)E r   