
    bi,E                    4   d Z ddlmZ ddlZddlmZ ddlm	Z
 ddlmZmZmZmZmZmZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZmZm Z  dd
l!m"Z"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0  G d d      Z1 G d de      Z2 G d de"      Z3y)a,  
Copyright 2013 Steven Diamond

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
    )annotationsN)	PSDSOCEqualityExpCone
InequalityNonNegNonPos	PowCone3DZero)canonInterface)Variable)Minimize)	ParamProb)InverseDataSolutioncvx_attr2constr)MatrixStuffingextract_lower_boundsextract_mip_idxextract_upper_bounds)get_canon_backend)
ReducedMatare_args_affinegroup_constraintslower_equalitylower_ineq_to_nonnegnonpos2nonneg)CoeffExtractorc                      e Zd ZdZej
                  Zej                  Zej                  Zej                  Zej                  Z	dZ
ddZd	dZd	dZd Zy)
ConeDimsap  Summary of cone dimensions present in constraints.

    Constraints must be formatted as dictionary that maps from
    constraint type to a list of constraints of that type.

    Attributes
    ----------
    zero : int
        The dimension of the zero cone.
    nonneg : int
        The dimension of the non-negative cone.
    exp : int
        The number of 3-dimensional exponential cones.
    soc : list of int
        A list of the second-order cone dimensions.
    psd : list of int
        A list of the positive semidefinite cone dimensions, where the
        dimension of the PSD cone of k by k matrices is k.
    p3c                   t        t        d |t           D                    | _        t        t        d |t           D                    | _        t        t        d |t           D                    | _        |t           D cg c]"  }|j                         D ]  }t        |       $ c}}| _
        |t           D cg c]  }t        |j                  d          c}| _        g }|t           rLt        j                   |t           D cg c]  }|j"                  j$                   c}      j'                         }|| _        y c c}}w c c}w c c}w )Nc              3  4   K   | ]  }|j                     y wNsize.0cs     i/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/cvxpy/reductions/dcp2cone/cone_matrix_stuffing.py	<genexpr>z$ConeDims.__init__.<locals>.<genexpr>U   s     =qAFF=   c              3  4   K   | ]  }|j                     y wr%   r&   r(   s     r+   r,   z$ConeDims.__init__.<locals>.<genexpr>V   s     AaffAr-   c              3  <   K   | ]  }|j                           y wr%   )	num_conesr(   s     r+   r,   z$ConeDims.__init__.<locals>.<genexpr>W   s     FQ1;;=Fs   r   )intsumr   zeror	   nonnegr   expr   
cone_sizessocr   shapepsdr   npconcatenatealphavaluetolistp3d)self
constr_mapr*   dimr?   s        r+   __init__zConeDims.__init__T   s    =Jt,<==>	#Aj.@AABsF*W2EFFG&0oPP#CHPHP-7_=C
O=i ..I9N!OA!''--!OPWWYC Q= "Ps   'E=E		Ec                    dj                  | j                  | j                  | j                  | j                  | j
                  | j                        S )Nz@(zero: {0}, nonneg: {1}, exp: {2}, soc: {3}, psd: {4}, p3d: {5}))formatr3   r4   r5   r7   r9   r?   r@   s    r+   __repr__zConeDims.__repr___   s<    QXXIIt{{DHHdhh$((L 	L    c                    d| j                   | j                  | j                  | j                  | j                  | j
                  fz  S )zString representation.
        zt%i equalities, %i inequalities, %i exponential cones, 
SOC constraints: %s, PSD constraints: %s,
 3d power cones %s.)r3   r4   r5   r7   r9   r?   rF   s    r+   __str__zConeDims.__str__c   s@    &*.))*.++*.((*.((*.((*.((*44 	4rH   c                \   || j                   k(  r| j                  S || j                  k(  r| j                  S || j                  k(  r| j
                  S || j                  k(  r| j                  S || j                  k(  r| j                  S || j                  k(  r| j                  S t        |      r%   )EQ_DIMr3   LEQ_DIMr4   EXP_DIMr5   SOC_DIMr7   PSD_DIMr9   P3D_DIMr?   KeyError)r@   keys     r+   __getitem__zConeDims.__getitem__o   s    $++99DLL ;;DLL 88ODLL 88ODLL 88ODLL 88O3-rH   N)returnNone)rU   str)__name__
__module____qualname____doc__srL   rM   rN   rO   rP   rQ   rC   rG   rJ   rT    rH   r+   r!   r!   8   sP    ( XXFiiGiiGiiGiiGG	L
4 rH   r!   c                  d    e Zd ZdZ	 	 	 	 d		 	 	 	 	 	 	 d
dZddZ	 	 d	 	 	 ddZddZddZddZ	y)ParamConeProga  Represents a parameterized cone program

    minimize   q'x  + d + [(1/2)x'Px]
    subject to cone_constr1(A_1*x + b_1, ...)
               ...
               cone_constrK(A_i*x + b_i, ...)


    The constant offsets d and b are the last column of c and A.
    Nc                   || _         || _        |	| _        || _        || _        || _        t        | j                  | j                  j                        | _        t        | j                  | j                  j                  d      | _	        || _
        t        |D cg c]  }|j                   c}      | _        t        |      | _        t        | j                        | _        || _        || _        | j"                  D ci c]  }|j&                  | c}| _        | j"                  D ci c]  }|j&                  |j                   c}| _        t        | j"                  D cg c]  }|j                   c}      | _        || _        || _        | j.                  D ci c]  }|j&                  | c}| _        |
| _        y c c}w c c}w c c}w c c}w c c}w )NT)	quad_form)qAPxlower_boundsupper_boundsr   r'   	reduced_A	reduced_Pconstraintsr2   constr_sizer   rA   r!   	cone_dims
parametersparam_id_to_colidid_to_paramparam_id_to_sizetotal_param_size	variablesvar_id_to_col	id_to_var	formatted)r@   rb   re   rc   rs   rt   rj   rm   rn   rd   rv   rf   rg   r*   pvs                   r+   rC   zParamConeProg.__init__   sf    (( $DFFDFFKK8#DFFDFFKK4H&<1<=+K8!$//2$.-1__=ADD!G=7; G!qvv G #T__$EQVV$E F #*+/>>:a!$$': #  =
 > G$E
 ;s   G G*G#GGc                j    | j                   j                  d   xs | j                   j                  d   S )zIs the problem mixed-integer?booleaninteger)re   
attributesrF   s    r+   is_mixed_integerzParamConeProg.is_mixed_integer   s0    vv  + )FFi(	)rH   c                     j                   j                  |        fd}t        j                   j                   j
                   j                  ||      }t        j                   j                  | j                  j                  d      \  }}|j                         j                         } j                   j                  |d      \  }	}
|rU j                  j                  |        j                  j                  |d      \  }}||||	t        j                  |
      fS |||	t        j                  |
      fS )a  Returns A, b after applying parameters (and reshaping).

        Args:
          id_to_param_value: (optional) dict mapping parameter ids to values.
          zero_offset: (optional) if True, zero out the constant offset in the
                       parameter vector.
          keep_zeros: (optional) if True, store explicit zeros in A where
                        parameters are affected.
          quad_obj: (optional) if True, include quadratic objective term.
        c                l    	 ,t        j                  j                  |    j                        S |    S r%   )r:   arrayrp   r=   )idxid_to_param_valuer@   s    r+   param_valuez3ParamConeProg.apply_parameters.<locals>.param_value   s<    =N>BHHT--c2889 9!23!79rH   )zero_offsetT)with_offsetF)rh   cacher   get_parameter_vectorrr   rn   rq   get_matrix_from_tensorrb   re   r'   toarrayflattenri   r:   
atleast_1d)r@   r   r   
keep_zerosquad_objr   	param_vecrb   drc   brd   _s   ``           r+   apply_parameterszParamConeProg.apply_parameters   s    	Z(	9 #77!!  !!#%	 44FFItvv{{>1IIK!~~44YD4Q1NN  ,>>88PU8VDAqaAr}}Q///aBMM!,,,rH   c                   | j                   t        d      |#| j                  D ch c]  }|j                   }}|| j                  dd z  }|j                  t        j                  |j                        dfd      }t        j                  |t        j                  |dddf         g      }d}	|j                  d   |	k  rJ|t        j                  | j                  j                  j                  |j!                                     z  }n=|t        j                  |j                  | j                  z  j!                               z  }t        j                  |      }i }
| j"                  j%                         D ]P  \  }}||v s| j&                  |   }||||j(                  z    }t        j
                  ||j                  d      |
|<   R |
S c c}w )	zMultiplies by Jacobian of parameter mapping.

        Assumes delA is sparse.

        Returns:
            A dictionary param.id -> dparam
        Nz0Can't apply Jacobian with a quadratic objective.   Forderi@Ysr   )rd   
ValueErrorrm   ro   rb   reshaper:   prodr8   spvstack	csc_arraysqueezerc   Tdotr   rn   itemsrp   r'   )r@   delcdelAdelbactive_paramsrw   del_param_vecflatdelAdelAbone_gig_of_doublesparam_id_to_delta_paramparam_idcolparamdeltas                  r+   apply_param_jaczParamConeProg.apply_param_jac   s    66OPP +/??;aQTT;M;tvvcr{*<<!4a 8<D		8R\\$q$w-%@AB&;;q>.. RZZU]]_(EFFM
 RZZ466)9(B(B(DEEM

=1"$!11779 	3MHc=(((2%c#

*:;46JJ5;;c53'1		3 '&5 <s   Gc                   |#| j                   D cg c]  }|j                   }}i }| j                  j                         D ]  \  }}||v s| j                  |   }|||j
                  |z    }|j                         rX|j                         }	t        j                  |	|d      }t        j                  ||	j                  d      ||	j                  <   t        j                  ||j                  d      ||<    |S c c}w )z7Splits the solution into individual variables.
        F)projectr   r   )rs   ro   rt   r   ru   r'   attributes_were_loweredvariable_of_provenancer   recover_value_for_variabler:   r   r8   )
r@   sltnactive_varsrx   	sltn_dictvar_idr   varr=   orig_vars
             r+   split_solutionzParamConeProg.split_solution	  s     )-8A1448K8	--335 	5KFC$nnV,S#...0"99;H+FF %8E-/ZZx~~S.:Ihkk* )+

syy)5If%	5 ! 9s   C?c                .   t        j                  | j                  j                        }|j	                         D ]  \  }}| j
                  |   }| j                  |   }|j                         r|j                         }t        j                  |gt        j                        r8||j                  z   t        j                  t        j                  |            z
  }t        j                  ||      }|j                  d      ||||j                  z     |S )z#Adjoint of split_solution.
        r   r   )r:   zerosre   r'   r   ru   rt   r   r   r   attributes_presentSYMMETRIC_ATTRIBUTESr   diaglower_valuer   )r@   del_varsvar_vecr   r   r   r   r   s           r+   split_adjointzParamConeProg.split_adjoint  s     ((466;;'%^^- 		CMFE..(C$$V,C**,557"55!
O$H$HJ!EGGObggbggen.EEE'33HeD*/--c-*BGCchh'		C rH   )NFNN)rv   boolrf   np.ndarray | Nonerg   r   rU   rV   )rU   r   )NFFF)r   r   r   r   r   r   r%   )
rX   rY   rZ   r[   rC   r}   r   r   r   r   r]   rH   r+   r_   r_      sx    	  #(3737+# !+#  1+#  1+# +#Z)
 LQDI!-%)!-=A!-F&'P,rH   r_   c                  6    e Zd ZdZdZd	d
dZd Zd Zd Zd Z	y)ConeMatrixStuffingzConstruct matrices for linear cone problems.

    Linear cone problems are assumed to have a linear objective and cone
    constraints which may have zero or more arguments, all of which must be
    affine.
    ordered_constraintsNc                     || _         || _        y r%   )r   canon_backend)r@   r   r   s      r+   rC   zConeMatrixStuffing.__init__9  s     *rH   c                   | j                   xr$ |j                  j                  j                         xs$ |j                  j                  j	                         }t        |j                        t        k(  xrQ |xrM t        j                  |j                                xr' t        |j                        xr |j                         S r%   )r   	objectiveexpris_quadratic	is_affinetyper   r   convex_attributesrs   r   rj   is_dpp)r@   problemvalid_obj_curvs      r+   acceptszConeMatrixStuffing.accepts>  s    --QG,=,=,B,B,O,O,Q /"",,. 	W&&'83 %"%'99':K:K:MNN% $G$7$78% NN$		&rH   c                V   t        |j                               \  }}t        |j                  ||      }| j                  r>|j
                  j                  j                         }|j                  |      \  }}d|z  }n'|j                  |j
                  j                        }d }|||fS )N)rz   r{      )
r   rs   r   x_lengthr   r   r   copyra   affine)	r@   r   	extractorrz   r{   re   r   params_to_Pparams_to_cs	            r+   stuffed_objectivez$ConeMatrixStuffing.stuffed_objectiveG  s    *7+<+<+>?Y'''J==$$))..0D'0':':4'@$KK-K $**7+<+<+A+ABKKK**rH   c                d   t        |      }g }|j                  D ]  }t        |t              rt	        |      }nt        |t
              rt        |      }nt        |t              rt        |      }nt        |t              rN|j                  dk(  r?t        |j                  d   |j                  d   j                  d|j                        }n(t        |t              r|j                  d   j                  dkD  rw|j                  \  }}}|j                   }t        |j#                  d      |j#                  d      |j#                  d      |j#                  d      |j                        }nt        |t$              ru|j                  d   j                  dkD  rY|j                  \  }}}t%        |j#                  d      |j#                  d      |j#                  d      |j                        }|j'                  |        |j)                  |j*                  |g      }	t-        |	| j.                        }
t1        ||
      }| j3                  ||      \  }}}t5        |      }|t6           |t8           z   |t           z   |t:           z   |t$           z   |t           z   }|D ci c]  }|j<                  |j<                   c}|_        ||_        |D cg c]  }|j                  D ]  }|  }}}|jA                  |      }tC        |j*                        tD        k(  |_#        |jI                         }tK        ||jL                        }tO        ||jL                        }tQ        |||||jR                  ||jU                         |jV                  |||      }||fS c c}w c c}}w )Nr   r   )axis	constr_idr   r   )r   )rd   rf   rg   ),r   rj   
isinstancer   r   r   r   r
   r   r   r   argsr   r   r   ndimr<   r   r   appendr   r   r   r   r   r   r   r   r	   r   ro   cons_id_mapr   r   r   minimizers   r   r'   r   r_   var_offsetsrm   param_id_map)r@   r   inverse_dataconsconre   yzr<   lowered_con_problemr   r   r   r   flattened_variablerA   ordered_consr*   arg	expr_listparams_to_problem_datars   rf   rg   new_probs                            r+   applyzConeMatrixStuffing.applyW  sB   "7+&& 	C#x($S)C,*3/C(#C(C%#((a-#((1+sxx{}}1$'MM3C+0@0@10D((1a					 4 !			 4 !			 4 %C 8*---	9
 C)chhqk.>.>.B((1aaiici2AIICI4H!))Z])J^(+7KK-	0 &llG,=,=t+DE)*=t?Q?QR"<?	7;7M7MY8 4["4 't,
!$'*V*<<sO(o.0:70CDFPQZF[\>J#KsCFFCFFN#K #/ ".AQ!&&A3SASA	A!*!1!1)!< $W%6%6 78 C%%'	+I7I7N7NO+I7I7N7NO "$$ %%%%
 %%1 $L Bs   .N' N,c                   |j                   }|j                  }|j                  }|j                  t        j
                  vr|j                  s|j                   }i i }}|j                  t        j                  vr#t        |j                  ||||j                        S t        |j                  j                               d   }|j                         D ]P  \  }	}
|j                  |	   }t        j                   |t"              }t        j$                  ||
|
|z    |d      ||	<   R |j&                  |j                         D ]v  \  }}|j(                  |   }|j*                  }|dk(  st-        |t.        t0        f      r|j&                  |   ||<   Ot        j$                  |j&                  |   |d      ||<   x t        |j                  ||||j                        S )z,Retrieves a solution to the original problemr   )dtyper   r   r]   )r   r   opt_valstatusr\   ERRORr   SOLUTION_PRESENTr   attrlistprimal_varsvaluesr   
var_shapesr:   r   r1   r   	dual_varsid2consr8   r   r   r   )r@   solutionr   var_mapcon_mapr   r  r  x_optr   offsetr8   r'   old_connew_concon_objs                   r+   invertzConeMatrixStuffing.invert  s   ****""??!''),2G2G'''G!#RY??!"4"44HOOWk9$MM+ + X))0023A6%mmo 	8NFF ++F3E775,D"$**U6&+-F36#8K	8 )$+MMO  &..w7B;*Wwn"E)1););G)DIg&)+ **73!*Ig& +y ' 	'rH   )FN)r   r   r   z
str | None)
rX   rY   rZ   r[   CONSTRAINTSrC   r   r   r   r  r]   rH   r+   r   r   0  s(     (K+
&+ >&@&'rH   r   )4r[   
__future__r   numpyr:   scipy.sparsesparser   cvxpy.settingssettingsr\   cvxpy.constraintsr   r   r   r   r   r	   r
   r   r   cvxpy.cvxcore.pythonr   cvxpy.expressions.variabler   cvxpy.problems.objectiver   cvxpy.problems.param_probr   cvxpy.reductionsr   r   r    cvxpy.reductions.matrix_stuffingr   r   r   r   ,cvxpy.reductions.solvers.solving_chain_utilsr   cvxpy.reductions.utilitiesr   r   r   r   r   r   cvxpy.utilities.coeff_extractorr   r!   r_   r   r]   rH   r+   <module>r      s    #   
 
 
 0 / - / C C  K  ;E  E RlI l^M' M'rH   