
    !gn3                     P    d Z ddlZ G d d      Z G d d      Zd Z	 d
dZdd	Zy)zM
Created on Thu May 15 16:36:05 2014

Author: Josef Perktold
License: BSD-3

    Nc                   8    e Zd ZdZd Zd Zd Zd Zed        Z	y)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                   | j                  f| _        y N)constraint_matrixconstraint_valuesvariable_namescoefs	constants__dict__updatetuple)selfr   r   r	   kwdss        Z/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/base/_constraints.py__init__zLinearConstraints.__init__"   sV     "3!2, '
*T",,d.D.DE
    c              #   8   K   | j                   E d {    y 7 wr   r   )r   s    r   __iter__zLinearConstraints.__iter__0   s     ::s   c                      | j                   |   S r   r   )r   idxs     r   __getitem__zLinearConstraints.__getitem__3   s    zz#r   c           	         d }g }t        |  D ]  \  }}g }t        || j                        D ]Y  \  }}|dk7  r|g k(  r| |||      z  }|dkD  r|d |||      z   z  }2|dk  s8|d |t        j                  |      |      z   z  }[ |dt	        |j                               z   z  }|j                  dj                  |              dj                  |      S )Nc                 d    t        j                  |       } | dk7  rt        |       dz   |z   }|S |}|S )N   z * )npabsstr)vnamesss      r   prod_stringz.LinearConstraints.__str__.<locals>.prod_string7   s;    q	AAvVe^d* I 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 
	4DAqBq$"5"56 ?46bBh+a..BU%+a"666BU%+bffQi">>>B? %#affh-''B&&rwwr{3
	4 yy,--r   c                 R     | |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!     288R\\2+<+<==r   N)
__name__
__module____qualname____doc__r   r   r   r-   classmethodr1    r   r   r   r      s0    *F.0 > >r   r   c                   $    e Zd ZdZddZd Zd Zy)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                 n   t        j                  |      x}| _        |t        j                  |      x}| _        |j
                  \  }}||c| _        | _        ||z
  | _        t        j                  |      |j                  j                  t         j                  j                  |      j                        z
  }t         j                  j                  |      \  }}|| _        || _        |d d d |f   x}| _        |d d |d f   | _        |m	 |j                  j                  t         j                  j'                  |j                  j                  |j                        |j                              | _        y d| _        y # t         j                  j*                  $ r}	t-        d|	      d }	~	ww xY w)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77&%-v"t{ 8+FF6NQSSWWRYY^^A%6%8%899yy~~a(u 

1ixi<((DF89-== !		acc(J K
 DM	 99(( = 78"< = ==s   A+F F4!F//F4c                     t        j                  |      }| 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   s<    $ N3"">#3#3466FFr   c                 b    t        j                  |      }|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   `   s    "H#JG*+r   r9   c                    |j                  |      j                  |j                        }|j                  |j                        j                  t        j                  j	                  ||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\      sb    B %%+//!##
C!!"))//#quuV}q7H"IJIIr   c                    | }|i }||}}|j                   |j                  }	}t        ||      }
|
j                  |	      }|	j	                  |
j
                  j                               }t        |d      r||j                  z  }||
j                  |      }ddl	}|j                  |j                               }d|v r|d=  |j                  ||fd|i|} |j                  dd|i|}|
j                  |j                        j                         }|
j                  j	                  |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      sU   t D/qA**dii4E!!Q'F}}T"HXXfoo--/0FtX$++l3 		$--/0I 9h  xLL)LJF\FXFJ--
 1 12::<K""&&z'<'<'>?CCFDUDUDWDWXJ
J..r   c                    | }ddl m}  ||j                        j                  |      }|j                  |j
                  }}t        |||||      \  }	}
}|j                  |	dd      }|	|j                  _	        |
|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                  _        ||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  s0    D !
 
DOO	$	6	6{	CB88R\\qA .dAq;G7?AFC (($)  +C CLL&)CLL#||J4H;-0:3C3C-C*-1*1vHLLX%LLX%0;;B?CLL$CLL'1CLL$Jr   )NNr   )r5   numpyr   r   r9   r\   rq   r   r7   r   r   <module>r      s@    Q> Q>hp+ p+f$P 15Z/z2r   