
    M/Phn3                     ^    d Z ddlZ G d d          Z G d d          Zd Z	 d
dZdd	ZdS )zM
Created on Thu May 15 16:36:05 2014

Author: Josef Perktold
License: BSD-3

    Nc                   @    e Zd ZdZd Zd Zd Zd Zed             Z	dS )LinearConstraintsa  Class to hold linear constraints information

    Affine constraints are defined as ``R b = q` where `R` is the constraints
    matrix and `q` are the constraints values and `b` are the parameters.

    This is in analogy to patsy's LinearConstraints class but can be pickled.

    Parameters
    ----------
    constraint_matrix : ndarray
        R matrix, 2-dim with number of columns equal to the number of
        parameters. Each row defines one constraint.
    constraint_values : ndarray
        1-dim array of constant values
    variable_names : list of strings
        parameter names, used only for display
    kwds : keyword arguments
        keywords are attached to the instance.

    c                     || _         || _        || _        || _        || _        | j                            |           | j         | j        f| _        d S N)constraint_matrixconstraint_valuesvariable_namescoefs	constants__dict__updatetuple)selfr   r   r	   kwdss        ]/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/base/_constraints.py__init__zLinearConstraints.__init__"   sX     "3!2, '
*T""",d.DE


    c              #   $   K   | j         E d {V  d S r   r   )r   s    r   __iter__zLinearConstraints.__iter__0   s&      :r   c                     | j         |         S r   r   )r   idxs     r   __getitem__zLinearConstraints.__getitem__3   s    z#r   c           	         d }g }t          |  D ]\  }}g }t          || j                  D ]d\  }}|dk    r|g k    r| |||          z  }!|dk    r|d |||          z   z  }:|dk     r$|d |t          j        |          |          z   z  }e|dt	          |                                          z   z  }|                    d                    |                     d                    |          S )Nc                 j    t          j        |           } | dk    rt          |           dz   |z   }n|}|S )N   z * )npabsstr)vnamesss      r   prod_stringz.LinearConstraints.__str__.<locals>.prod_string7   s8    q		AAvvVVe^d*Ir   r   z + z - z =  
)zipr	   r   r   r   itemappendjoin)r   r#   constraints_stringsrqr"   r    r!   s           r   __str__zLinearConstraints.__str__6   s"   	 	 	 !J 
	4 
	4DAqBq$"566 ? ?466bBhh++a...BBUU%++a"6"666BBUU%++bfQii">">>>B%#affhh--''B&&rwwr{{3333yy,---r   c                 :     | |j         |j        |j                  S )aL  class method to create instance from patsy instance

        Parameters
        ----------
        lc : instance
            instance of patsy LinearConstraint, or other instances that have
            attributes ``lc.coefs, lc.constants, lc.variable_names``

        Returns
        -------
        instance of this class

        )r
   r   r	   )clslcs     r   
from_patsyzLinearConstraints.from_patsyN   s     s28R\2+<===r   N)
__name__
__module____qualname____doc__r   r   r   r-   classmethodr1    r   r   r   r      sx         *F F F    . . .0 > > [> > >r   r   c                   &    e Zd ZdZddZd Zd ZdS )TransformRestrictiona  Transformation for linear constraints `R params = q`

    Note, the transformation from the reduced to the full parameters is an
    affine and not a linear transformation if q is not zero.


    Parameters
    ----------
    R : array_like
        Linear restriction matrix
    q : arraylike or None
        values of the linear restrictions


    Notes
    -----
    The reduced parameters are not sorted with respect to constraints.

    TODO: error checking, eg. inconsistent constraints, how?

    Inconsistent constraints will raise an exception in the calculation of
    the constant or offset. However, homogeneous constraints, where q=0, will
    can have a solution where the relevant parameters are constraint to be
    zero, as in the following example::

        b1 + b2 = 0 and b1 + 2*b2 = 0, implies that b2 = 0.

    The transformation applied from full to reduced parameter space does not
    raise and exception if the constraint does not hold.
    TODO: maybe change this, what's the behavior in this case?


    The `reduce` transform is applied to the array of explanatory variables,
    `exog`, when transforming a linear model to impose the constraints.
    Nc                 @   t          j        |          x}| _        |t          j        |          x}| _        |j        \  }}||c| _        | _        ||z
  | _        t          j	        |          |j
                            t           j                            |          j
                  z
  }t           j                            |          \  }}|| _        || _        |d d d |f         x}| _        |d d |d f         | _        |	 |j
                            t           j                            |j
                            |j
                  |j
                            | _        d S # t           j        j        $ r}	t-          d|	          d }	~	ww xY wd| _        d S )Nz6possibly inconsistent constraints. error generated by
r   )r   
atleast_2dRasarrayr,   shapek_constrk_vars
k_unconstreyeTdotlinalgpinveighevalsevecsL
transf_matsolveconstantLinAlgError
ValueError)
r   r<   r,   r?   r@   mrH   rI   rJ   es
             r   r   zTransformRestriction.__init__   sz    ]1%%%DF=A&A7&%-v"t{ 8+F6NNQSWWRY^^A%6%6%8999y~~a((u 

111ixi<((DF899-== !	ac(J(J K K9( = = = j78q"< = = == DMMMs   AE) )F=FFc                     t          j        |          }| j                            |j                  j        | j        z   S )a  transform from the reduced to the full parameter space

        Parameters
        ----------
        params_reduced : array_like
            parameters in the transformed space

        Returns
        -------
        params : array_like
            parameters in the original space

        Notes
        -----
        If the restriction is not homogeneous, i.e. q is not equal to zero,
        then this is an affine transform.
        )r   r=   rK   rD   rC   rM   )r   params_reduceds     r   expandzTransformRestriction.expand   s6    $ N33"">#3446FFr   c                 ^    t          j        |          }|                    | j                  S )a  transform from the full to the reduced parameter space

        Parameters
        ----------
        params : array_like
            parameters or data in the original space

        Returns
        -------
        params_reduced : array_like
            parameters in the transformed space

        This transform can be applied to the original parameters as well
        as to the data. If params is 2-d, then each row is transformed.
        )r   r=   rD   rK   )r   paramss     r   reducezTransformRestriction.reduce   s'      F##zz$/***r   r   )r2   r3   r4   r5   r   rT   rW   r7   r   r   r9   r9   `   sU        " "H# # # #JG G G*+ + + + +r   r9   c                 (   |                     |                               |j                  }|                     |j                                       t          j                            ||                     |           |z
                      }| |z
  S )a  find the parameters that statisfy linear constraint from unconstrained

    The linear constraint R params = q is imposed.

    Parameters
    ----------
    params : array_like
        unconstrained parameters
    Sinv : ndarray, 2d, symmetric
        covariance matrix of the parameter estimate
    R : ndarray, 2d
        constraint matrix
    q : ndarray, 1d
        values of the constraint

    Returns
    -------
    params_constraint : ndarray
        parameters of the same length as params satisfying the constraint

    Notes
    -----
    This is the exact formula for OLS and other linear models. It will be
    a local approximation for nonlinear models.

    TODO: Is Sinv always the covariance matrix?
    In the linear case it can be (X'X)^{-1} or sigmahat^2 (X'X)^{-1}.

    My guess is that this is the point in the subspace that satisfies
    the constraint that has minimum Mahalanobis distance. Proof ?
    )rD   rC   r   rE   rL   )rV   Sinvr<   r,   rsr	reductions         r   transform_params_constraintr\      sk    B %%++//!#

C!!")//#quuV}}q7H"I"IJJIIr   c                    | }|i }||}}|j         |j        }	}t          ||          }
|
                    |	          }|	                    |
j                                                  }t          |d          r
||j        z  }||
                    |          }ddl	}|	                    |
                                          }d|v r|d=  |j        ||fd|i|} |j        dd|i|}|
                    |j                                                  }|
j                            |                                                              |
j        j                  }|||fS )a4  fit model subject to linear equality constraints

    The constraints are of the form   `R params = q`
    where R is the constraint_matrix and q is the vector of constraint_values.

    The estimation creates a new model with transformed design matrix,
    exog, and converts the results back to the original parameterization.


    Parameters
    ----------
    model: model instance
        An instance of a model, see limitations in Notes section
    constraint_matrix : array_like, 2D
        This is R in the linear equality constraint `R params = q`.
        The number of columns needs to be the same as the number of columns
        in exog.
    constraint_values :
        This is `q` in the linear equality constraint `R params = q`
        If it is a tuple, then the constraint needs to be given by two
        arrays (constraint_matrix, constraint_value), i.e. (R, q).
        Otherwise, the constraints can be given as strings or list of
        strings.
        see t_test for details
    start_params : None or array_like
        starting values for the optimization. `start_params` needs to be
        given in the original parameter space and are internally
        transformed.
    **fit_kwds : keyword arguments
        fit_kwds are used in the optimization of the transformed model.

    Returns
    -------
    params : ndarray ?
        estimated parameters (in the original parameterization
    cov_params : ndarray
        covariance matrix of the parameter estimates. This is a reverse
        transformation of the covariance matrix of the transformed model given
        by `cov_params()`
        Note: `fit_kwds` can affect the choice of covariance, e.g. by
        specifying `cov_type`, which will be reflected in the returned
        covariance.
    res_constr : results instance
        This is the results instance for the created transformed model.


    Notes
    -----
    Limitations:

    Models where the number of parameters is different from the number of
    columns of exog are not yet supported.

    Requires a model that implement an offset option.
    Noffsetr   start_paramsr7   )endogexogr9   rW   rD   rM   squeezehasattrr^   copy_get_init_kwds	__class__fitrT   rV   rK   
cov_paramsrC   )modelr   r   r_   fit_kwdsr   r<   r,   r`   ra   transfexogp_str^   rd   	init_kwds
mod_constr
res_constrparams_origrh   s                      r   fit_constrainedrq      s~   t D/qA*di4E!!Q''F}}T""HXXfo--//00FtX $+l33 KKK		$--//00I 9h  xLLL)LLJFF\FXFFJ--
 122::<<K"&&z'<'<'>'>??CCFDUDWXXJ
J..r   c                 l   | }ddl m}  ||j                                      |          }|j        |j        }}t          |||||          \  }	}
}|                    |	dd          }|	|j        _	        |
|j        _
        |                    dd          }|dk    r|
|j        z  |j        _        nd|j        _        t          |          }|j        xj        |z  c_        |j        xj        |z  c_        t"                              |          |j        _        ||j        _        ||j        _        |S )	a  fit_constraint that returns a results instance

    This is a development version for fit_constrained methods or
    fit_constrained as standalone function.

    It will not work correctly for all models because creating a new
    results instance is not standardized for use outside the `fit` methods,
    and might need adjustements for this.

    This is the prototype for the fit_constrained method that has been added
    to Poisson and GLM.
    r   )
DesignInfo)r_   rj   F)r_   maxiterwarn_convergencecov_type	nonrobustN)patsyrs   
exog_nameslinear_constraintr
   r   rq   rg   _resultsrV   cov_params_defaultgetscalenormalized_cov_paramslendf_residdf_modelr   r1   constraintsr?   results_constrained)ri   r   r_   rj   r   rs   r0   r<   r,   rV   covro   resrv   r?   s                  r   fit_constrained_wrapr   W  sQ    D !     
 
DO	$	$	6	6{	C	CB8R\qA .dAq;G7?A A AFC (($)  + +C CL&)CL#||J44H;-0:3C-C**-1*1vvHLX%LX%0;;B??CL$CL'1CL$Jr   )NNr   )r5   numpyr   r   r9   r\   rq   r   r7   r   r   <module>r      s        Q> Q> Q> Q> Q> Q> Q> Q>hp+ p+ p+ p+ p+ p+ p+ p+f$ $ $P 15Z/ Z/ Z/ Z/z2 2 2 2 2 2r   