
    bi\                   &   d Z ddlmZ ddl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 ddlZddlmZ ddlmc mZ ddlmZmZ ddlmZ dd	lmZ dd
l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, ddl-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl>m@ZA ddlBmCZC ddlDmEZEmFZF ddlGmHZH ddlImJZJ ddlKmLZLmMZM ddlNmOZO dd lmPZP dd!lQmRZR dd"lSmTZT  ed#g d$      ZUd%ZVd&eVz  d'z   d(j                  eV      z   d'z   d) e(j                         z   j                  eV      z   d'z   d&eVz  z   ZYd*eVz  d'z   d+j                  eV      z   d'z   d*eVz  z   ZZd*eVz  d'z   d,j                  eV      z   d'z   d*eVz  z   Z[d*eVz  d'z   d-j                  eV      z   d'z   d*eVz  z   Z\d*eVz  d'z   d.j                  eV      z   d'z   d*eVz  z   Z] G d/ d0      Z^d1 Z_ G d2 d3ej                        Zae G d4 d5             Zb G d6 d7      Zcy)8aA  
Copyright 2013 Steven Diamond, 2017 Akshay Agrawal

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)
namedtuple)	dataclass)DictListOptionalUnion)Constanterror)settings)Atom)Equality
InequalityNonNegNonPosZero)
Constraint)DPPError)cvxtypes)Variable)scalar_value)MaximizeMinimize)InverseData)Chain)Dgp2Dcp)dqcp2dcp)
EvalParams)FlipObjective)INF_OR_UNB_MESSAGE)	bisection)defines)ConicSolver)SOLVER_MAP_CONICSOLVER_MAP_QP)QpSolver)Solver)SolvingChainconstruct_solving_chain)SOLVERS)debug_tools)CITATION_DICT)unique_listSolveResult)	opt_valuestatusprimal_valuesdual_valuesO   =
CVXPYv-CompilationzNumerical solver	CitationsSummaryc                  (    e Zd ZddZddZd Zd Zy)Cachec                <    d | _         d | _        d | _        d | _        y Nkeysolving_chain
param_proginverse_dataselfs    Q/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/cvxpy/problems/problem.py__init__zCache.__init__k   s     5937    c                <    d | _         d | _        d | _        d | _        y r?   r@   rE   s    rG   
invalidatezCache.invalidateq   s     ! rI   c                    ||||fS r?    )rF   solvergp
ignore_dppuse_quad_objs        rG   make_keyzCache.make_keyw   s    J55rI   c                @    | j                   d uxr | j                   d   S )N   rA   rE   s    rG   rO   zCache.gpz   s    xxt#33rI   NreturnNone)__name__
__module____qualname__rH   rK   rR   rO   rM   rI   rG   r=   r=   j   s    8!64rI   r=   c                    t        | t              r| S t        | t              r0| rt        d      t        d      k  S t        d      t        d      k  S t	        dt        |       z        )Nr   rT   z,Problem has an invalid constraint of type %s)
isinstancer   boolr
   
ValueErrortype)
constraints    rG   _validate_constraintrb   ~   sg    *j)	J	%.8x{* 	,x{*	, Gj)* + 	+rI   c                     e Zd ZdZi Z	 d4	 	 	 	 	 d5dZej                  d6d       Ze	d        Z
e	d7d       Ze	d        Ze	d8d       Ze	d9d	       Ze	d
        Ze	d:d       Zej                  d;d<d       Zej                  d=d       Zej                  d>d       Zej                  d;d<d       Zej                  d>d       Zej                  d?d@d       Zej                  d>d       Zej                  d>d       Zej                  dAd       Zej                  d        Zej                  dBd       ZdCdZe	dDd       Ze	dEd       Ze	dFd       ZdGdZ d Z!e"dHd       Z#	 	 	 	 	 	 dI	 	 	 	 	 	 	 	 	 	 	 dJdZ$	 	 dK	 dLdZ%dMd Z&	 	 	 	 	 	 dN	 	 	 	 	 	 	 	 	 	 	 	 	 dOd!Z'e(dPd"       Z)dPd#Z*	 	 	 	 	 	 	 	 	 	 dQ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dRd$Z+dPd%Z,dPd&Z-dPd'Z.dPd(Z/dSd)Z0d7d*Z1d7d+Z2dTd,Z3dTd-Z4dTd.Z5dTd/Z6dTd0Z7dTd1Z8e8Z9dTd2Z:d>d3Z;e:Z<y)UProblema^  A convex optimization problem.

    Problems are immutable, save for modification through the specification
    of :class:`~cvxpy.expressions.constants.parameters.Parameter`

    Arguments
    ---------
    objective : Minimize or Maximize
        The problem's objective.
    constraints : list
        The constraints on the problem variables.
    Nc                   |g }t        |t        t        f      st        j                  d      || _        t        j                  | j
                        t        j                  k\  rt        j                  d       |D cg c]  }t        |       c}| _        t        | j                        D ]E  \  }}t        j                  |      t        j                  k\  s-t        j                  d| d       G d | _        d | _        d | _        t#               | _        i | _        d | _        d | _        d | _        d | _        | j
                  | j                  g| _        d| _        y c c}w )Nz/Problem objective must be Minimize or Maximize.ziObjective contains too many subexpressions. Consider vectorizing your CVXPY code to speed up compilation.zConstraint #z` contains too many subexpressions. Consider vectorizing your CVXPY code to speed up compilation.r   )r]   r   r   r   DCPError
_objectiver+   
node_count	MAX_NODESwarningswarnrb   _constraints	enumerate_value_status	_solutionr=   _cache_solver_cache_size_metrics_solver_stats_compilation_time_solve_timeargsndim)rF   	objectiveconstraintscira   s         rG   rH   zProblem.__init__   sA    K)h%9:..!RSS#!!$//2k6K6KKMM Z [>IJ1!4J&t'8'89 	_MAz%%j1[5J5JJQC 0^ ^ _	_
 &*g6:6:26,0__d&7&78		) Ks    E#c                    | j                   }| j                         }| j                  g| j                  z   D ]0  }t	        ||j                               }|xr |j                         }2 ||d}|S )z
        Aggregates and caches metrics for expression trees in self.args. So far
        metrics include the maximum dimensionality ('max_ndim') and whether
        all sub-expressions support C++ ('all_support_cpp').

        )max_ndimall_support_cpp)rx   _supports_cpprg   rl   max	_max_ndim_all_support_cpp)rF   r~   cpp_supportargmetricss        rG   _aggregate_metricszProblem._aggregate_metrics   sy     99((*OO$t'8'88 	AC8S]]_5H%@#*>*>*@K	A
 !*
 rI   c                F    | j                   yt        | j                         S )zpfloat : The value from the last time the problem was solved
                   (or None if not solved).
        N)rn   r   rE   s    rG   valuezProblem.value   s     
 ;;,,rI   c                    | j                   S )zstr : The status from the last time the problem was solved; one
                 of optimal, infeasible, or unbounded (with or without
                 suffix inaccurate).
        )ro   rE   s    rG   r0   zProblem.status   s     ||rI   c                    | j                   S )zKSolution : The solution from the last time the problem was solved.
        )rp   rE   s    rG   solutionzProblem.solution   s     ~~rI   c                    | j                   S )zMinimize or Maximize : The problem's objective.

        Note that the objective cannot be reassigned after creation,
        and modifying the objective after creation will result in
        undefined behavior.
        )rg   rE   s    rG   ry   zProblem.objective   s     rI   c                     | j                   dd S )zA shallow copy of the problem's constraints.

        Note that constraints cannot be reassigned, appended to, or otherwise
        modified after creation, except through parameters.
        N)rl   rE   s    rG   rz   zProblem.constraints   s       ##rI   c                f    | j                         D ci c]  }|j                         | c}S c c}w )z7
        Expose all parameters as a dictionary
        )
parametersname)rF   r   s     rG   
param_dictzProblem.param_dict   s-    
 AE@QR*
!:-RRR   .c                f    | j                         D ci c]  }|j                         | c}S c c}w )z6
        Expose all variables as a dictionary
        )	variablesr   )rF   variables     rG   var_dictzProblem.var_dict  s*    
 ;?..:JKh)KKKr   c                \    t        fd| j                  | j                  gz   D              S )a  Does the problem satisfy DCP rules?

        Arguments
        ---------
        dpp : bool, optional
            If True, enforce the disciplined parametrized programming (DPP)
            ruleset; only relevant when the problem involves Parameters.
            DPP is a mild restriction of DCP. When a problem involving
            Parameters is DPP, subsequent solves can be much faster than
            the first one. For more information, consult the documentation at

            https://www.cvxpy.org/tutorial/advanced/index.html#disciplined-parametrized-programming

        Returns
        -------
        bool
            True if the Expression is DCP, False otherwise.
        c              3  @   K   | ]  }|j                          y wr?   )is_dcp.0exprdpps     rG   	<genexpr>z!Problem.is_dcp.<locals>.<genexpr>!  !      L#$++c
L   allrz   ry   rF   r   s    `rG   r   zProblem.is_dcp  5    (  L'+'7'74>>:J'JL L 	LrI   c                j    t        d | j                  | j                  j                  gz   D              S )zZ
        Returns the maximum number of dimensions of any argument in the problem.
        c              3  <   K   | ]  }|j                           y wr?   )r   r   r   s     rG   r   z$Problem._max_ndim.<locals>.<genexpr>)  s     Y4>>#Y   )r   rz   ry   r   rE   s    rG   r   zProblem._max_ndim$  s-    
 Y0@0@DNNDWDWCX0XYYYrI   c                j    t        d | j                  | j                  j                  gz   D              S )zW
        Returns True if all the arguments in the problem support cpp backend.
        c              3  <   K   | ]  }|j                           y wr?   )r   r   s     rG   r   z(Problem._supports_cpp.<locals>.<genexpr>0  s     `t4((*`r   )r   rz   ry   r   rE   s    rG   r   zProblem._supports_cpp+  s-    
 `t7G7G4>>K^K^J_7_```rI   c                \    t        fd| j                  | j                  gz   D              S )a  Does the problem satisfy DGP rules?

        Arguments
        ---------
        dpp : bool, optional
            If True, enforce the disciplined parametrized programming (DPP)
            ruleset; only relevant when the problem involves Parameters.
            DPP is a mild restriction of DGP. When a problem involving
            Parameters is DPP, subsequent solves can be much faster than
            the first one. For more information, consult the documentation at

            https://www.cvxpy.org/tutorial/advanced/index.html#disciplined-parametrized-programming

        Returns
        -------
        bool
            True if the Expression is DGP, False otherwise.
        c              3  @   K   | ]  }|j                          y wr?   )is_dgpr   s     rG   r   z!Problem.is_dgp.<locals>.<genexpr>F  r   r   r   r   s    `rG   r   zProblem.is_dgp2  r   rI   c                V    t        d | j                  | j                  gz   D              S )z1Does the problem satisfy the DQCP rules?
        c              3  <   K   | ]  }|j                           y wr?   )is_dqcpr   s     rG   r   z"Problem.is_dqcp.<locals>.<genexpr>M  s      J!$,,.Jr   r   rE   s    rG   r   zProblem.is_dqcpI  s4      J%)%5%58H%HJ J 	JrI   c                    |j                         dk(  r| j                  d      S |j                         dk(  r| j                  d      S t        d|      )a>  Does the problem satisfy DPP rules?

        DPP is a mild restriction of DGP. When a problem involving
        Parameters is DPP, subsequent solves can be much faster than
        the first one. For more information, consult the documentation at

        https://www.cvxpy.org/tutorial/advanced/index.html#disciplined-parametrized-programming

        Arguments
        ---------
        context : str
            Whether to check DPP-compliance for DCP or DGP; ``context`` should
            be either ``'dcp'`` or ``'dgp'``. Calling ``problem.is_dpp('dcp')``
            is equivalent to ``problem.is_dcp(dpp=True)``, and
            `problem.is_dpp('dgp')`` is equivalent to
            `problem.is_dgp(dpp=True)`.

        Returns
        -------
        bool
            Whether the problem satisfies the DPP rules.
        dcpT)r   dgpzUnsupported context )lowerr   r   r_   )rF   contexts     rG   is_dppzProblem.is_dppP  sP    0 ==?e#;;4;((]]_%;;4;((3W==rI   c                p   | j                   D ]8  }t        |t        t        f      r|j                  d   j                         r8 y | j                         D ]$  }|j                         s|j                         s$ y | j                         xr' | j                  j                  d   j                         S )z(Is problem a quadratic program?
        r   F)rz   r]   r   r   rw   is_pwlr   is_psdis_nsdr   ry   is_qpwa)rF   r{   vars      rG   is_qpzProblem.is_qpo  s     !! 	Aq8T"23qvvay7G7G7I	 >># 	Czz|szz|	 B$.."5"5a"8"@"@"BCrI   c                B    t        d | j                         D              S )Nc              3  \   K   | ]$  }|j                   d    xs |j                   d    & yw)booleanintegerN)
attributesr   r7   s     rG   r   z+Problem.is_mixed_integer.<locals>.<genexpr>}  s2      . <<	*Eall9.EE .s   *,)anyr   rE   s    rG   is_mixed_integerzProblem.is_mixed_integer{  s#     . NN,. . 	.rI   c                    | j                   j                         }| j                  D ]  }||j                         z  } t        |      S )zAccessor method for variables.

        Returns
        -------
        list of :class:`~cvxpy.expressions.variable.Variable`
            A list of the variables in the problem.
        )ry   r   rz   r-   )rF   vars_constrs      rG   r   zProblem.variables  sI     ((*&& 	(FV%%''E	(5!!rI   c                    | j                   j                         }| j                  D ]  }||j                         z  } t        |      S )zAccessor method for parameters.

        Returns
        -------
        list of :class:`~cvxpy.expressions.constants.parameter.Parameter`
            A list of the parameters in the problem.
        )ry   r   rz   r-   )rF   paramsr   s      rG   r   zProblem.parameters  sI     **,&& 	*Ff''))F	*6""rI   c                    i }| j                   j                         }| j                  D ]  }||j                         z  } |D ci c]  }t        |      | }}t	        |j                               S c c}w )zAccessor method for constants.

        Returns
        -------
        list of :class:`~cvxpy.expressions.constants.constant.Constant`
            A list of the constants in the problem.
        )ry   	constantsrz   idlistvalues)rF   
const_dict
constants_r   constants        rG   r   zProblem.constants  s|     
^^--/
&& 	-F&**,,J	- >HHblH,H
HJ%%'(( Is   A3c                    | j                   j                         }| j                  D ]  }||j                         z  } t        |      S )zAccessor method for atoms.

        Returns
        -------
        list of :class:`~cvxpy.atoms.Atom`
            A list of the atom types in the problem; note that this list
            contains classes, not instances.
        )ry   atomsrz   r-   )rF   r   r   s      rG   r   zProblem.atoms  sF     $$&&& 	$FV\\^#E	$5!!rI   c                R    | j                   t        |       | _         | j                   S )z]:class:`~cvxpy.problems.problem.SizeMetrics` : Information about the problem's size.
        )rs   SizeMetricsrE   s    rG   size_metricszProblem.size_metrics  s)     %!,T!2D!!!rI   c                    | j                   S )z[:class:`~cvxpy.problems.problem.SolverStats` : Information returned by the solver.
        )rt   rE   s    rG   solver_statszProblem.solver_stats  s     !!!rI   c                    | j                   S )zwfloat : The number of seconds it took to compile the problem the
                   last time it was compiled.
        )ru   rE   s    rG   compilation_timezProblem.compilation_time  s    
 %%%rI   c                v   d}t        |t              st        |      |st        d      |D ]  }	 t        |t              r|} || g|d|i|}njt        |t              rOt        |      dk(  rA|\  }}	t        |t              rt        |	t              st        |       || g|d|i|	|}nt        |      t        j                  j                  d|       |c S  t        j                  d|       # t        j                  $ r,}
t        j                  j                  d|
       Y d}
~
d}
~
ww xY w)	a`  Solve a problem using multiple solvers.

        Arguments
        ---------
        solvers : list of (str, dict) tuples or strings.
            The solvers to use. For example, ['SCS', ('OSQP', {'max_iter':10000})]
        kwargs : keywords, optional
            Additional solver specific arguments.

        Returns
        -------
        solution : Solution
            The solution of the first solver that succeeds.

        Raises
        ------
        SolverError
            If all solvers fail to find a solution.
        ValueError
            If the input solvers format is incorrect.
        zCSolver path entry must be list of str or tuple[str, dict[str, Any]]z-Solver path must contain at least one solver.rN      zSolver %s succeedszSolver %s failed: %sNzAll solvers failed: )r]   r   r_   strtuplelendictsLOGGERinfor   SolverError)rF   
solve_funcsolversrw   kwargsENTRY_ERROR_MSGrN   solver_namer   solver_kwargses              rG   _solve_solver_pathzProblem._solve_solver_path  sO   0 _'4(_--LMM 	FFFfc*"(K)$TTkTVTH.3v;!3C5;2])+s;:m]aCb",_"==#- $X#'$X0;$X?L$XPV$X %_552K@	F" "6wi @AA $$ F4k1EEFs   B,C99D8!D33D8c                   |j                  dd      }|t        j                  |   }nt        j                  }|j                  dd      }|3|j	                  dd      }|t        d      | j                  ||||      S  || g|i |S )a  Compiles and solves the problem using the specified method.

        Populates the :code:`status` and :code:`value` attributes on the
        problem object as a side-effect.

        Arguments
        ---------
        solver : str, optional
            The solver to use. For example, 'CLARABEL', 'SCS', or 'OSQP'.
        solver_path : list of (str, dict) tuples or strings, optional
            The solvers to use with optional arguments.
            The function tries the solvers in the given order and
            returns the first solver's solution that succeeds.
            For example, ['SCS', ('OSQP', {'max_iter':10000})]
        verbose : bool, optional
            Overrides the default of hiding solver output, and prints
            logging information describing CVXPY's compilation process.
        gp : bool, optional
            If True, parses the problem as a disciplined geometric program
            instead of a disciplined convex program.
        qcp : bool, optional
            If True, parses the problem as a disciplined quasiconvex program
            instead of a disciplined convex program.
        requires_grad : bool, optional
            Makes it possible to compute gradients of a solution with respect to
            Parameters by calling ``problem.backward()`` after solving, or to
            compute perturbations to the variables given perturbations to Parameters by
            calling ``problem.derivative()``.

            Gradients are only supported for DCP and DGP problems, not
            quasiconvex problems. When computing gradients (i.e., when
            this argument is True), the problem must satisfy the DPP rules.
        enforce_dpp : bool, optional
            When True, a DPPError will be thrown when trying to solve a non-DPP
            problem (instead of just a warning). Only relevant for problems
            involving Parameters. Defaults to False.
        ignore_dpp : bool, optional
            When True, DPP problems will be treated as non-DPP,
            which may speed up compilation. Defaults to False.
        method : function, optional
            A custom solve method to use.
        kwargs : keywords, optional
            Additional solver specific arguments. See Notes below.

        Notes
        ------
        CVXPY interfaces with a wide range of solvers; the algorithms used by these solvers
        have arguments relating to stopping criteria, and strategies to improve solution quality.

        There is no one choice of arguments which is perfect for every problem. If you are not
        getting satisfactory results from a solver, you can try changing its arguments. The
        exact way this is done depends on the specific solver. Here are some examples:

        ::

            prob.solve(solver='ECOS', abstol=1e-6)
            prob.solve(solver='OSQP', max_iter=10000).
            mydict = {"MSK_DPAR_INTPNT_CO_TOL_NEAR_REL":  10}
            prob.solve(solver='MOSEK', mosek_params=mydict).

        You should refer to CVXPY's web documentation for details on how to pass solver
        solver arguments, available at

        https://www.cvxpy.org/tutorial/advanced/index.html#setting-solver-options

        Returns
        -------
        float
            The optimal value for the problem, or a string indicating
            why the problem could not be solved.

        Raises
        ------
        cvxpy.error.DCPError
            Raised if the problem is not DCP and `gp` is False.
        cvxpy.error.DGPError
            Raised if the problem is not DGP and `gp` is True.
        cvxpy.error.DPPError
            Raised if DPP settings are invalid.
        cvxpy.error.SolverError
            Raised if no suitable solver exists among the installed solvers,
            or if an unanticipated error is encountered.
        methodNsolver_pathrN   zBCannot specify both 'solver' and 'solver_path'. Please choose one.)poprd   REGISTERED_SOLVE_METHODS_solvegetr_   r   )rF   rw   r   	func_namer   r   rN   s          rG   solvezProblem.solve  s    h JJx.	  99)DJ Jjj5"ZZ$/F! XZ Z**:k4PP$0000rI   c                "    || j                   |<   y)a<  Adds a solve method to the Problem class.

        Arguments
        ---------
        name : str
            The keyword for the method.
        func : function
            The function that executes the solve method. This function must
            take as its first argument the problem instance to solve.
        N)r   )clsr   funcs      rG   register_solvezProblem.register_solvec  s     .2$$T*rI   c                   |r|rt        d      t        j                         }t        |t              r|j	                         }|d}	n|j                  dd      }	| j                  j                  ||||	      }
|
| j                  j                  k7  r[| j                  j                          | j                  ||||||      }|
| j                  _        || j                  _        i | _        n| j                  j                  }|rt        t               | j                  j                  :|rt         j"                  j%                  d       |r| j                  j                  j                  t&              }|j(                  j*                  }| j-                         D ].  }||v st/        j0                  |j2                        ||   _        0 |j4                  j7                  | j                  j                        \  }}| j                  j8                  |gz   }t        j                         |z
  | _        |rt         j"                  j%                  d| j:                         n|r|j<                  d   j?                         }djA                  d	 |j<                  D              }t         j"                  j%                  d
|       t         j"                  j%                  d|       |j7                  | |      \  }}t        |tB              xr1 t         jD                  |v xr tG        d |j<                  D               }t        j                         |z
  | _        |r*t         j"                  j%                  d| j:                         |rg|r/| j-                         rt         j"                  j%                  d       |t         jD                     | j                  _        |dd | j                  _        |||fS )a  Returns the problem data used in the call to the solver.

        When a problem is solved, CVXPY creates a chain of reductions enclosed
        in a :class:`~cvxpy.reductions.solvers.solving_chain.SolvingChain`,
        and compiles it to some low-level representation that is
        compatible with the targeted solver. This method returns that low-level
        representation.

        For some solving chains, this low-level representation is a dictionary
        that contains exactly those arguments that were supplied to the solver;
        however, for other solving chains, the data is an intermediate
        representation that is compiled even further by the solver interfaces.

        A solution to the equivalent low-level problem can be obtained via the
        data by invoking the `solve_via_data` method of the returned solving
        chain, a thin wrapper around the code external to CVXPY that further
        processes and solves the problem. Invoke the unpack_results method
        to recover a solution to the original problem.

        For example:

        ::

            objective = ...
            constraints = ...
            problem = cp.Problem(objective, constraints)
            data, chain, inverse_data = problem.get_problem_data(cp.SCS)
            # calls SCS using `data`
            soln = chain.solve_via_data(problem, data)
            # unpacks the solution returned by SCS into `problem`
            problem.unpack_results(soln, chain, inverse_data)

        Alternatively, the `data` dictionary returned by this method
        contains enough information to bypass CVXPY and call the solver
        directly.

        For example:

        ::

            problem = cp.Problem(objective, constraints)
            data, _, _ = problem.get_problem_data(cp.SCS)

            import scs
            probdata = {
              'A': data['A'],
              'b': data['b'],
              'c': data['c'],
            }
            cone_dims = data['dims']
            cones = {
                "f": cone_dims.zero,
                "l": cone_dims.nonneg,
                "q": cone_dims.soc,
                "ep": cone_dims.exp,
                "s": cone_dims.psd,
            }
            soln = scs.solve(data, cones)

        The structure of the data dict that CVXPY returns depends on the
        solver. For details, consult the solver interfaces in
        `cvxpy/reductions/solvers`.

        Arguments
        ---------
        solver : str
            The solver the problem data is for.
        gp : bool, optional
            If True, then parses the problem as a disciplined geometric program
            instead of a disciplined convex program.
        enforce_dpp : bool, optional
            When True, a DPPError will be thrown when trying to parse a non-DPP
            problem (instead of just a warning). Defaults to False.
        ignore_dpp : bool, optional
            When True, DPP problems will be treated as non-DPP,
            which may speed up compilation. Defaults to False.
        canon_backend : str, optional
            'CPP' (default) | 'SCIPY'
            Specifies which backend to use for canonicalization, which can affect
            compilation time. Defaults to None, i.e., selecting the default
            backend.
        verbose : bool, optional
            If True, print verbose output related to problem compilation.
        solver_opts : dict, optional
            A dict of options that will be passed to the specific solver.
            In general, these options will override any default settings
            imposed by cvxpy.

        Returns
        -------
        dict or object
            lowest level representation of problem
        SolvingChain
            The solving chain that created the data.
        list
            The inverse data generated by the chain.

        Raises
        ------
        cvxpy.error.DPPError
            Raised if DPP settings are invalid.
        z4Cannot set enforce_dpp = True and ignore_dpp = True.NrQ   )rN   rO   enforce_dpprP   canon_backendsolver_optszIUsing cached ASA map, for faster compilation (bypassing reduction chain).z1Finished problem compilation (took %.3e seconds).z -> c              3  F   K   | ]  }t        |      j                    y wr?   )r`   rY   )r   rs     rG   r   z+Problem.get_problem_data.<locals>.<genexpr>   s!      2L-.Q((2Ls   !z%Compiling problem (target solver=%s).zReduction chain: %sc              3  <   K   | ]  }t        |t                y wr?   )r]   r   )r   	reductions     rG   r   z+Problem.get_problem_data.<locals>.<genexpr>)  s!      G ) 'y*= Gr   z[(Subsequent compilations of this problem, using the same arguments, should take less time.))$r   timer]   r   upperr   rq   rR   rA   rK   _construct_chainrB   rr   print_COMPILATION_STRrC   r   r   r   r   canon_methods_parametersr   nplogr   rN   applyrD   ru   
reductionsr   joinr   
PARAM_PROBr   )rF   rN   rO   r   rP   verboser   r   startrQ   rA   rB   dgp2dcpold_params_to_new_paramsparamdatasolver_inverse_datarD   r   reduction_chain_strsafe_to_caches                        rG   get_problem_datazProblem.get_problem_dataq  sg   d :QRR		fc"\\^F L&??>4@Lkk""62z<H$++//!KK""$ 11"'%+' 2 )M "DKKO(5DKK%!#D KK55M"#;;!!-78 ++3377@
 ,3+@+@+L+L(!__. )E 88@B!KKA)07=) )6(<(<(B(B&&)(%D%;;337J6KKL%)YY[5%8D"/040F0FH +66r:??A&,kk 2L2?2J2J2L 'L#@+O35HI!.!4!4T7!CD,4& GLLD(G G-:-E-EG G G  &*YY[5%8D"/040F0FH t0HHMMEF *.all);& ,8+<(]L00rI   c                   g g d}t        |t              r| j                  |      S t        |t              r|j	                         }|k|t
        j                  vrt        j                  d|z        |t
        j                  v r|dxx   |gz  cc<   |t
        j                  v r|dxx   |gz  cc<   nt
        j                  D cg c]  }|t
        j                  v r| c}|d<   g |d<   t
        j                  D ]=  }|t
        j                  v s|t        j                  k7  s*|d   j                  |       ? |r6|-|t
        j                  vrt        j                  d|z  dz         |g |d<   | j                         rt
        j                  t        j                  gk(  r*|t        j                  k7  rd}t        j                  |      |d   D cg c]!  }t
        j                   |   j"                  r|# c}|d<   |d   D cg c]!  }t
        j$                  |   j"                  r|# c}|d<   |d   s&|d   s!t        j                  d|d   |d   z   z        |S c c}w c c}w c c}w )	aX  
        Find candidate solvers for the current problem. If solver
        is not None, it checks if the specified solver is compatible
        with the problem passed.

        Arguments
        ---------
        solver : Union[string, Solver, None]
            The name of the solver with which to solve the problem or an
            instance of a custom solver. If no solver is supplied
            (i.e., if solver is None), then the targeted solver may be any
            of those that are installed. If the problem is variable-free,
            then this parameter is ignored.
        gp : bool
            If True, the problem is parsed as a Disciplined Geometric Program
            instead of as a Disciplined Convex Program.

        Returns
        -------
        dict
            A dictionary of compatible solvers divided in `qp_solvers`
            and `conic_solvers`.

        Raises
        ------
        cvxpy.error.SolverError
            Raised if the problem is not DCP and `gp` is False.
        cvxpy.error.DGPError
            Raised if the problem is not DGP and `gp` is True.
        
qp_solversconic_solverszThe solver %s is not installed.r  r  zMWhen `gp=True`, `solver` must be a conic solver (received '%s'); try calling z$ `solve()` with `solver=cvxpy.ECOS`.a  

                    You need a mixed-integer solver for this model. Refer to the documentation
                        https://www.cvxpy.org/tutorial/advanced/index.html#mixed-integer-programs
                    for discussion on this topic.

                    Quick fix 1: if you install the python package CVXOPT (pip install cvxopt),
                    then CVXPY can use the open-source mixed-integer linear programming
                    solver `GLPK`. If your problem is nonlinear then you can install SCIP
                    (pip install pyscipopt).

                    Quick fix 2: you can explicitly specify solver='ECOS_BB'. This may result
                    in incorrect solutions and is not recommended.
                zRProblem is mixed-integer, but candidate QP/Conic solvers (%s) are not MIP-capable.)r]   r'   _add_custom_solver_candidatesr   r  slv_defINSTALLED_SOLVERSr   r   CONIC_SOLVERS
QP_SOLVERSr   ECOS_BBappendr   INSTALLED_MI_SOLVERSr%   MIP_CAPABLEr$   )rF   rN   rO   
candidatesr   slvmsgs          rG   _find_candidate_solverszProblem._find_candidate_solvers<  s   B %'')+
ff%55f==fc"\\^FW666''(IF(RSS...?+x7++++<(VH4(3:3L3L (Da+,0B0B+B )* (DJ|$*,J'00 <'///C1994D/66s;<
 !fG4I4I&I''24:;89 
 +-
<(  "++		{:v?R '',, &l3(9((+77 (9J|$ &o6+<++A.:: +<J' o."<0''A-0123 3 k(DN(9+<s   I#&I(
&I-c                   |j                         t        v rd}t        j                  |      g g d}| j	                         r|j
                  rxt        |t              r-|t        |j                         <   |j                         g|d<   |S t        |t              r+|t        |j                         <   |j                         g|d<   |S )a  
        Returns a list of candidate solvers where custom_solver is the only potential option.

        Arguments
        ---------
        custom_solver : Solver

        Returns
        -------
        dict
            A dictionary of compatible solvers divided in `qp_solvers`
            and `conic_solvers`.

        Raises
        ------
        cvxpy.error.SolverError
            Raised if the name of the custom solver conflicts with the name of some officially
            supported solver
        zLCustom solvers must have a different name than the officially supported onesr  r  r  )r   r*   r   r   r   r(  r]   r&   r%   r#   r$   )rF   custom_solvermessager)  s       rG   r   z%Problem._add_custom_solver_candidates  s    ( 7*dG##G,,$&<
$$&-*C*C-26Cm0023,9,>,>,@+A
<(  M;79F !3!3!56/</A/A/C.D
?+rI   c           
     p    | j                  ||      }| j                  |       t        | |||||||      S )a  
        Construct the chains required to reformulate and solve the problem.

        In particular, this function

        # finds the candidate solvers
        # constructs the solving chain that performs the
           numeric reductions and solves the problem.

        Arguments
        ---------
        solver : str, optional
            The solver to use. Defaults to ECOS.
        gp : bool, optional
            If True, the problem is parsed as a Disciplined Geometric Program
            instead of as a Disciplined Convex Program.
        enforce_dpp : bool, optional
            Whether to error on DPP violations.
        ignore_dpp : bool, optional
            When True, DPP problems will be treated as non-DPP,
            which may speed up compilation. Defaults to False.
        canon_backend : str, optional
            'CPP' (default) | 'SCIPY'
            Specifies which backend to use for canonicalization, which can affect
            compilation time. Defaults to None, i.e., selecting the default
            backend.
        solver_opts: dict, optional
            Additional arguments to pass to the solver.

        Returns
        -------
        A solving chain
        )rN   rO   )rO   r   rP   r   r   specified_solver)r,  _sort_candidate_solversr)   )rF   rN   rO   r   rP   r   r   candidate_solverss           rG   r  zProblem._construct_chain  sO    T !8828N$$%67&t->23>2<5B3>8>@ 	@rI   c                    t        | d         dkD  rt        | d   d       | d<   t        | d         dkD  rt        | d   d       | d<   yy)a   Sorts candidate solvers lists according to slv_def.CONIC_SOLVERS/QP_SOLVERS

        Arguments
        ---------
        candidates : dict
            Dictionary of candidate solvers divided in qp_solvers
            and conic_solvers
        Returns
        -------
        None
        r  rT   c                @    t         j                  j                  |       S r?   )r!  r#  indexr   s    rG   <lambda>z1Problem._sort_candidate_solvers.<locals>.<lambda>  s    8M8M8S8STU8V rI   rU   r  c                @    t         j                  j                  |       S r?   )r!  r$  r6  r7  s    rG   r8  z1Problem._sort_candidate_solvers.<locals>.<lambda>  s    W5G5G5M5Ma5P rI   N)r   sorted)r   s    rG   r2  zProblem._sort_candidate_solvers  sc     w'(1,'-(.V(GO$ w|$%)$*%+P%GL! *rI   c                <    d | _         d | _        d | _        d | _        y r?   )
_cache_key_solving_chain_param_prog_inverse_datarE   s    rG   _invalidate_cachezProblem._invalidate_cache  s!    "!rI   c           	        |rt        t               | j                         D ]4  }|j                  t	        j
                  d|j                         z         |rt        d | j                         D              }t        d | j                  D              }t        d | j                         D              }t        j                  j                  d|||       g }| j                         r|j                  d       | j                         r|j                  d       | j!                         r|j                  d       t        j                  j                  d	d
j#                  |             |dk(  rt        j                  j                  d       t        j                  j                  d       t        j                  j                  d|
t        j$                  n|
       |r|rdnd}|rt'        d      | j)                  |      st	        j*                  d      |0|t        j,                  t        j.                  fvrt'        d|z        t        j.                  t0        j2                  vrt5        d      t        j.                  }n|r|rt'        d      |ru| j                         sd| j!                         st	        j6                  d      |rTt        j                  j                  d       |r3t        t8               t        t:        d          t        t:        d          t=        j>                         g}tA        j@                         }tC        | jD                        tF        k(  rDtI               g|z   }|jK                  d      |jK                  d      }}||dz  |d<   ||dz  |d<   tM        | |      }tO        jP                  |jS                         f||d|}| jU                  |jW                  |             | j                  S | jY                  ||||	||
|      \  }}}|rJt        tZ               t        j                  j                  d|j\                  d   j                                tA        j@                         }|j_                  d|      }|r|st        tZ               |r|r~t        t8               t        t:        d          | j                         rt        t:        d          |rt        t:        d          t        |j\                  d   ja                  |             |jc                  | ||||      }tA        j@                         }||z
  | _2        | jg                  |||       |rt        th               t        j                  j                  d | jj                         | j                  | j                  ntl        jn                  }t        j                  j                  d!|       t        j                  j                  d"| jp                         t        j                  j                  d#| jd                         | j                  S )$ar  Solves a DCP compliant optimization problem.

        Saves the values of primal and dual variables in the variable
        and constraint objects, respectively.

        Arguments
        ---------
        solver : str, optional
            The solver to use. Defaults to ECOS.
        warm_start : bool, optional
            Should the previous solver result be used to warm start?
        verbose : bool, optional
            Overrides the default of hiding solver output.
        bibtex : bool, optional
            Prints bibtex citations for CVXPY, the grammar, and the solver.
        gp : bool, optional
            If True, parses the problem as a disciplined geometric program.
        qcp : bool, optional
            If True, parses the problem as a disciplined quasiconvex program.
        requires_grad : bool, optional
            Makes it possible to compute gradients with respect to
            parameters by calling `backward()` after solving, or to compute
            perturbations to the variables by calling `derivative()`. When
            True, the solver must be SCS, and dqcp must be False.
            A DPPError is thrown when problem is not DPP.
        enforce_dpp : bool, optional
            When True, a DPPError will be thrown when trying to solve a non-DPP
            problem (instead of just a warning). Defaults to False.
        ignore_dpp : bool, optional
            When True, DPP problems will be treated as non-DPP,
            which may speed up compilation. Defaults to False.
        canon_backend : str, optional
            'CPP' (default) | 'SCIPY'
            Specifies which backend to use for canonicalization, which can affect
            compilation time. Defaults to None, i.e., selecting the default
            backend.
        kwargs : dict, optional
            A dict of options that will be passed to the specific solver.
            In general, these options will override any default settings
            imposed by cvxpy.

        Returns
        -------
        float
            The optimal value for the problem, or a string indicating
            why the problem could not be solved.
        zA Parameter (whose name is '%s') does not have a value associated with it; all Parameter objects must have values before solving a problem.c              3     K   | ]G  }|j                   rt        |j                   d          nt        j                  |j                         I yw)r   N)
sparse_idxr   r  prodshaper   s     rG   r   z!Problem._solve.<locals>.<genexpr>Z  sB      J34 78llc!,,q/2 ggagg./ Js   AAc              3  Z   K   | ]#  }t        j                  |j                         % y wr?   r  rD  rE  )r   r{   s     rG   r   z!Problem._solve.<locals>.<genexpr>\  s     KQ 0K   )+c              3  Z   K   | ]#  }t        j                  |j                         % y wr?   rG  )r   ps     rG   r   z!Problem._solve.<locals>.<genexpr>]  s     KArwwqww/KrH  zAYour problem has %d variables, %d constraints, and %d parameters.DCPDGPDQCPz/It is compliant with the following grammars: %s, r   zg(If you need to solve this problem multiple times, but with different data, consider using parameters.)zdCVXPY will first compile your problem; then, it will invoke a numerical solver to obtain a solution.z>Your problem is compiled with the %s canonicalization backend.r   r   z*Cannot compute gradients of DQCP problems.zEProblem is not DPP (when requires_grad is True, problem must be DPP).zKWhen requires_grad is True, the only supported solver is SCS (received %s).zThe Python package diffcp must be installed to differentiate through problems. Please follow the installation instructions at https://github.com/cvxgrp/diffcpz*At most one of `gp` and `qcp` can be True.zThe problem is not DQCP.zOReducing DQCP problem to a one-parameter family of DCP problems, for bisection.r6   lowhighr   )problemr  )rN   r  z)Invoking solver %s  to obtain a solution.solver_verbosezProblem status: %szOptimal value: %.3ezCompilation took %.3e secondsz<Solver (including time spent in interface) took %.3e seconds)9r  _HEADERr   r   r   ParameterErrorr   sumr   rz   r   r   r   r   r&  r   r   r  DEFAULT_CANON_BACKENDr_   r   r   SCSDIFFCPr!  r"  ModuleNotFoundError	DQCPError_CITATION_STRr,   r   Dqcp2Dcpr  r`   ry   r   r   r   r   r!   bisectreduceunpackretriever  _NUM_SOLVER_STRr  r   citesolve_via_datarv   unpack_results_FOOTERr0   r  nanru   )rF   rN   
warm_startr  bibtexrO   qcprequires_gradr   rP   r   r   	parametern_variablesn_constraintsn_parameters
curvaturesdpp_contextr  r  rO  rP  chainsolnr  rB   rD   rR  r   endvals                                  rG   r   zProblem._solve  sF   x 'N* 	KI&**79B9IJK K	K  J8<8HJ JKK$:J:JKKMK9JKKLHHMM<> J{{}!!%({{}!!%(||~!!&)HHMMEIIj)+ q KL HHMMFG HHMMT/</DA++-Y #%%5K !MNN[[-nn &F G G#quuahh6G(G  "24:"; < < !:!::)78 8 c !MNN4;;=||~//*DEEHHMMEF m,mG45mF34&//12
		'83"//!2Z!?J &

5 16::f3EC'(,r	u),rvdzB ''LLNN+17NFLNENN401zz!,0,A,ABZ--
)m\ /"HHMM?!,,R05579 		$4g>7/"v-  -() {{}mE*+mE*+ -**2.33D9: //$
NF<iik;Hm\B'NHHMM.< $

 6$**BFFCHHMM/5HHMM94;Q;QRHHMM#$($4$46 zzrI   c                   t         j                  | j                  vrt        d      | j                  t         j
                  vrt        j                  d      | j                  t         j                     }|d   }t        j                  |d   j                        }i }| j                  j                         }| j                         D ]  }|j                  -t        j                  |j                        ||j                   <   n<t        j"                  |j                  t        j$                        ||j                   <   |s{||j                   xx   |j&                  z  cc<    | j                  j(                  j+                  |      }t-        j,                         } ||||      \  }	}
}t-        j,                         }||z
  |d<   | j                  j(                  j/                  ||	 |
      }|s*| j1                         D ]  }||j                      |_         y| j                  j2                  j5                  t6              }|j8                  j:                  }| j1                         D ]S  }|j                   |vrdn||j                      }||v r'||   }|d	|j&                  z  ||j                      z  z  }||_        U y)
a4  Compute the gradient of a solution with respect to Parameters.

        This method differentiates through the solution map of the problem,
        obtaining the gradient of a solution with respect to the Parameters.
        In other words, it calculates the sensitivities of the Parameters
        with respect to perturbations in the optimal Variable values. This
        can be useful for integrating CVXPY into automatic differentiation
        toolkits.

        ``backward()`` populates the ``gradient`` attribute of each Parameter
        in the problem as a side-effect. It can only be called after calling
        ``solve()`` with ``requires_grad=True``.

        Below is a simple example:

        ::

            import cvxpy as cp
            import numpy as np

            p = cp.Parameter()
            x = cp.Variable()
            quadratic = cp.square(x - 2 * p)
            problem = cp.Problem(cp.Minimize(quadratic), [x >= 0])
            p.value = 3.0
            problem.solve(requires_grad=True, eps=1e-10)
            # backward() populates the gradient attribute of the parameters
            problem.backward()
            # Because x* = 2 * p, dx*/dp = 2
            np.testing.assert_allclose(p.gradient, 2.0)

        In the above example, the gradient could easily be computed by hand.
        The ``backward()`` is useful because for almost all problems, the
        gradient cannot be computed analytically.

        This method can be used to differentiate through any DCP or DGP
        problem, as long as the problem is DPP compliant (i.e.,
        ``problem.is_dcp(dpp=True)`` or ``problem.is_dgp(dpp=True)`` evaluates to
        ``True``).

        This method uses the chain rule to evaluate the gradients of a
        scalar-valued function of the Variables with respect to the Parameters.
        For example, let x be a variable and p a Parameter; x and p might be
        scalars, vectors, or matrices. Let f be a scalar-valued function, with
        z = f(x). Then this method computes dz/dp = (dz/dx) (dx/p). dz/dx
        is chosen as the all-ones vector by default, corresponding to
        choosing f to be the sum function. You can specify a custom value for
        dz/dx by setting the ``gradient`` attribute on your variables. For example,

        ::

            import cvxpy as cp
            import numpy as np


            b = cp.Parameter()
            x = cp.Variable()
            quadratic = cp.square(x - 2 * b)
            problem = cp.Problem(cp.Minimize(quadratic), [x >= 0])
            b.value = 3.
            problem.solve(requires_grad=True, eps=1e-10)
            x.gradient = 4.
            problem.backward()
            # dz/dp = dz/dx dx/dp = 4. * 2. == 8.
            np.testing.assert_allclose(b.gradient, 8.)

        The ``gradient`` attribute on a variable can also be interpreted as a
        perturbation to its optimal value.

        Raises
        ------
            ValueError
                if solve was not called with ``requires_grad=True``
            SolverError
                if the problem is infeasible or unbounded
        zIbackward can only be called after calling solve with `requires_grad=True`zBackpropagating through infeasible/unbounded problems is not yet supported. Please file an issue on Github if you need this feature.DTr   NdtypeDT_TIMEg              ?)r   rX  rr   r_   r0   SOLUTION_PRESENTr   r   r  zerosrE  rq   rO   r   gradientonesr   asarrayfloat64r   rC   split_adjointr  apply_param_jacr   rB   r   r   r
  r  )rF   backward_cacherv  r|  del_varsrO   r   dxr  dAdbdcrs  dparamsr  r  r  grad	new_params                      rG   backwardzProblem.backward  s`   Z 884--- ? @ @[[ 2 22## %G H H ++AHH5D!,223[[^^( 		8H  ((*(?%(*

83D3D9;)E% %7%		8 [[##11(;		E5)
Biik$'%Ky!++((88bS"E* 3!(!23 kk//33G<G'.'<'<'H'H$* & $hhg5s7588;L44 8 ?IS5;;.'),,2GGGD!%!&rI   c                   t         j                  | j                  vrt        d      | j                  t         j
                  vrt        d      | j                  t         j                     }| j                  j                  }|d   }i }| j                  j                         }|r)| j                  j                  j                  t              }| j                         s:| j                         D ]&  }t        j                  |j                         |_        ( y| j                         D ];  }|j"                  |j"                  nt        j                  |j                         }	|r|j$                  j&                  v r$|j$                  j&                  |   j(                  }
n|j(                  }
d|j*                  z  t        j,                  |	t        j.                        z  ||
<   |j(                  |j0                  v st        j,                  |	t        j.                        ||j(                  <   
t        j,                  |	t        j.                        ||j(                  <   > |j3                  |d      \  }}}}t5        j4                         } || ||      \  }}}t5        j4                         }||z
  |d	<   |j7                  || j                         D cg c]  }|j(                   c}      }| j                         D ]8  }||j(                     |_        |s|xj"                  |j*                  z  c_        : yc c}w )
a  Apply the derivative of the solution map to perturbations in the Parameters

        This method applies the derivative of the solution map to perturbations
        in the Parameters to obtain perturbations in the optimal values of the
        Variables. In other words, it tells you how the optimal values of the
        Variables would be changed by small changes to the Parameters.

        You can specify perturbations in a Parameter by setting its ``delta``
        attribute (if unspecified, the perturbation defaults to 0).

        This method populates the ``delta`` attribute of the Variables as a
        side-effect.

        This method can only be called after calling ``solve()`` with
        ``requires_grad=True``. It is compatible with both DCP and DGP
        problems (that are also DPP-compliant).

        Below is a simple example:

        ::

            import cvxpy as cp
            import numpy as np

            p = cp.Parameter()
            x = cp.Variable()
            quadratic = cp.square(x - 2 * p)
            problem = cp.Problem(cp.Minimize(quadratic), [x >= 0])
            p.value = 3.0
            problem.solve(requires_grad=True, eps=1e-10)
            # derivative() populates the delta attribute of the variables
            p.delta = 1e-3
            problem.derivative()
            # Because x* = 2 * p, dx*/dp = 2, so (dx*/dp)(p.delta) == 2e-3
            np.testing.assert_allclose(x.delta, 2e-3)

        Raises
        ------
            ValueError
                if solve was not called with ``requires_grad=True``
            SolverError
                if the problem is infeasible or unbounded
        zKderivative can only be called after calling solve with `requires_grad=True`zDifferentiating through infeasible/unbounded problems is not yet supported. Please file an issue on Github if you need this feature.DNrz  rw  T)zero_offsetD_TIME)r   rX  rr   r_   r0   r{  rq   rC   rO   rB   r   r   r   r   r  r|  rE  deltar
  r  r   r   r  r  param_id_to_colapply_parametersr  split_solution)rF   r  rC   r  param_deltasrO   r  r   r  r  new_param_idr  _r  r  r  r  rs  r7   dvarss                       rG   
derivativezProblem.derivativeY  s   X 884--- ? @ @[[ 2 22 I J J ++AHH5[[++
3[[^^kk//33G<G  NN, :!#(..!9:__& 	ME#(;;#:EKK@UEG11===#*#8#8#D#DU#K#N#NL#(88LObjjbjj&II \*88z999 .0ZZ>@jj.JL* *,E)LUXX&!	M" #33L@D 4 FAr2		bS"b>Aqiik#&;x ))t~~/0!02( 	1H"8;;/HN (..0	1 1s   M
c                    | j                         D ]  }|j                  d         | j                  D ]$  }|j                  D ]  }|j                  d         & d | _        d | _        d | _        y r?   )r   
save_valuerz   dual_variablesrn   ro   rp   )rF   r7   r{   dvs       rG   _clear_solutionzProblem._clear_solution  sq    ! 	ALL	!! 	$A&& $d#$	$ rI   c                   |j                   t        j                  v r| j                         D ]*  }|j	                  |j
                  |j                            , | j                  D ]C  }|j                  |j                  v s|j                  |j                  |j                            E | j                  j                  | _        n|j                   t        j                  v rk| j                         D ]  }|j	                  d        | j                  D ]$  }|j                  D ]  }|j	                  d        & |j                  | _        nt!        d|z        |j                   | _        || _        y)a  Updates the problem state given a Solution.

        Updates problem.status, problem.value and value of primal and dual
        variables. If solution.status is in cvxpy.settins.ERROR, this method
        is a no-op.

        Arguments
        _________
        solution : cvxpy.Solution
            A Solution object.

        Raises
        ------
        ValueError
            If the solution object has an invalid status
        Nz"Cannot unpack invalid solution: %s)r0   r   r{  r   r  primal_varsr   rz   	dual_varssave_dual_valuery   r   rn   
INF_OR_UNBr  opt_valr_   ro   rp   )rF   r   r7   r{   r   r  s         rG   r_  zProblem.unpack  s:   " ??a000^^% 9X11!$$789%% @448---%%h&8&8&>?@ ....DK__,^^% #T"#** ( // (BMM$'(( #**DKAHLMM!rI   c                D   |j                  ||      }|j                  t        j                  v rt	        j
                  d       |j                  t        j                  k(  rt	        j
                  t               |j                  t        j                  v r3t        j                  d|j                  j                         z  dz         | j                  |       t        j                  | j                   j"                  |j                  j                               | _        y)a  Updates the problem state given the solver results.

        Updates problem.status, problem.value and value of
        primal and dual variables.

        Arguments
        _________
        solution : object
            The solution returned by applying the chain to the problem
            and invoking the solver on the resulting data.
        chain : SolvingChain
            A solving chain that was used to solve the problem.
        inverse_data : list
            The inverse data returned by applying the chain to the problem.

        Raises
        ------
        cvxpy.error.SolverError
            If the solver failed
        zSolution may be inaccurate. Try another solver, adjusting the solver settings, or solve with verbose=True for more information.zSolver '%s' failed. zDTry another solver, or solve with verbose=True for more information.N)invertr0   r   
INACCURATErj   rk   INFEASIBLE_OR_UNBOUNDEDr    ERRORr   r   rN   r   r_  SolverStats	from_dictrp   attrrt   )rF   r   rq  rD   s       rG   rd  zProblem.unpack_results  s    , <<,7??all*MM5
 ??a777MM,-??agg%##*U\\->->-@@##$ $
 	H(224>>3F3F).):):)<>rI   c                F   t        | j                        dk(  rt        | j                        S d}t        | j                        |t        | j                  d         z   g}| j                  dd  D ]   }|t        |      dz  t        |      z   gz  }" dj	                  |      S )Nr   zsubject to rT    r5   )r   rz   r   ry   r  )rF   
subject_tolinesr   s       rG   __str__zProblem.__str__  s    t A%t~~&&&J(#d&6&6q&9"::<E**12. ?#j/C/#f+=>>?99U##rI   c                `    dt        | j                        dt        | j                        dS )NzProblem(rN  ))reprry   rz   rE   s    rG   __repr__zProblem.__repr__  s&    $($8$()9)9$:< 	<rI   c                D    t        | j                   | j                        S r?   )rd   ry   rz   rE   s    rG   __neg__zProblem.__neg__#  s    (8(899rI   c                    |dk(  r| S t        |t              s
t               t        | j                  |j                  z   t	        | j
                  |j
                  z               S Nr   r]   rd   NotImplementedErrorry   r-   rz   rF   others     rG   __add__zProblem.__add__&  sX    A:KE7+%''t~~7"4#3#3e6G6G#GHJ 	JrI   c                $    |dk(  r| S t               r  r  r  s     rG   __radd__zProblem.__radd__.  s    A:K%''rI   c                    t        |t              s
t               t        | j                  |j                  z
  t	        | j
                  |j
                  z               S r?   r  r  s     rG   __sub__zProblem.__sub__4  sL    %)%''t~~7"4#3#3e6G6G#GHJ 	JrI   c                &    |dk(  r|  S t               r  r  r  s     rG   __rsub__zProblem.__rsub__:  s    A:5L%''rI   c                    t        |t        t        f      s
t               t	        | j
                  |z  | j                        S r?   r]   intfloatr  rd   ry   rz   r  s     rG   __mul__zProblem.__mul__@  s5    %#u.%''t~~-t/?/?@@rI   c                    t        |t        t        f      s
t               t	        | j
                  d|z  z  | j                        S )Nrz  r  r  s     rG   __div__zProblem.__div__G  s9    %#u.%''t~~u5t7G7GHHrI   c                     yNFrM   rE   s    rG   is_constantzProblem.is_constantL  s    rI   r?   )ry   Union[Minimize, Maximize]rz   zOptional[List[Constraint]]rW   rX   )rW   r   )rW   r   )rW   r  )rW   zList[Constraint])rW   zDict[str, Variable])F)r   r^   rW   r^   )rW   r  )rW   r^   )r   )r   r   rW   r^   )rW   zList[Variable])rW   zList[Constant])rW   z
List[Atom])rW   z'SizeMetrics')rW   'SolverStats')rW   zfloat | None)r   zList[tuple[str, Dict] | str])r   r   rW   rX   )FFFFNN)rO   r^   r   r^   rP   r^   r  r^   r   
str | Noner   Optional[dict]r  )rO   r^   )r.  r'   )NFFFNN)rN   zOptional[str]rO   r^   r   r^   rP   r^   r   r  r   r  rW   r(   rV   )
NTFFFFFFFN)rN   r   rg  r^   r  r^   rh  r^   rO   r^   ri  r^   rj  r^   r   r^   rP   r^   r   r  )rq  r(   rW   rX   )rW   z	'Problem')=rY   rZ   r[   __doc__r   rH   perfcompute_oncer   propertyr   r0   r   ry   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   classmethodr   r  r,  r   r  staticmethodr2  r@  r   r  r  r  r_  rd  r  r  r  r  r  r  r  r  __rmul__r  r  __truediv__rM   rI   rG   rd   rd      sW     " _c"2"A["	"H 
 ( - -    
   $ $ S S L L 
L L, 
Z Z 
a a 
L L, 
J J 
> >< 
	D 	D 
. . 
" " 
# # 
) )"" " " " "
 & &.B``1D 2 2 ! $(&*I1I1 I1 	I1
 I1 "I1 $I1X (,+0e$(eN H %) %$(,*.1@!1@ 1@ 	1@
 1@ &1@ (1@ 
1@f  *" ""&$# %*#("'+/||| | 	|
 | | #| !|  | )||E&N`1D$"L'>R	$<:J(J(A
 HI
 KrI   rd   c                  f    e Zd ZU dZded<   dZded<   dZded<   dZded	<   dZd
ed<   e	dd       Z
y)r  a  Reports some of the miscellaneous information that is returned
    by the solver after solving but that is not captured directly by
    the Problem instance.

    Attributes
    ----------
    solver_name : str
        The name of the solver.
    solve_time : double
        The time (in seconds) it took for the solver to solve the problem.
    setup_time : double
        The time (in seconds) it took for the solver to setup the problem.
    num_iters : int
        The number of iterations the solver had to go through to find a solution.
    extra_stats : object
        Extra statistics specific to the solver; these statistics are typically
        returned directly from the solver, without modification by CVXPY.
        This object may be a dict, or a custom Python object.
    r   r   NzOptional[float]
solve_time
setup_timezOptional[int]	num_itersr  extra_statsc           	         | ||j                  t        j                        |j                  t        j                        |j                  t        j                        |j                  t        j
                              S )aW  Construct a SolverStats object from a dictionary of attributes.

        Parameters
        ----------
        attr : dict
            A dictionary of attributes returned by the solver.
        solver_name : str
            The name of the solver.

        Returns
        -------
        SolverStats
            A SolverStats object.
        )r  r  r  r  )r   r   
SOLVE_TIME
SETUP_TIME	NUM_ITERSEXTRA_STATS)r   r  r   s      rG   r  zSolverStats.from_dictn  sT      xx-xx-hhq{{+/
 	
rI   )r  r   r   r   rW   r  )rY   rZ   r[   r  __annotations__r  r  r  r  r  r  rM   rI   rG   r  r  R  sI    ( "&J&"&J&#I}#"&K&
 
rI   r  c                      e Zd ZdZddZy)r   aR  Reports various metrics regarding the problem.

    Attributes
    ----------

    num_scalar_variables : integer
        The number of scalar variables in the problem.
    num_scalar_data : integer
        The number of scalar constants and parameters in the problem. The number of
        constants used across all matrices, vectors, in the problem.
        Some constants are not apparent when the problem is constructed: for example,
        The sum_squares expression is a wrapper for a quad_over_lin expression with a
        constant 1 in the denominator.
    num_scalar_eq_constr : integer
        The number of scalar equality constraints in the problem.
    num_scalar_leq_constr : integer
        The number of scalar inequality constraints in the problem.

    max_data_dimension : integer
        The longest dimension of any data block constraint or parameter.
    max_big_small_squared : integer
        The maximum value of (big)(small)^2 over all data blocks of the problem, where
        (big) is the larger dimension and (small) is the smaller dimension
        for each data block.
    c                   d| _         |j                         D ]!  }| xj                   |j                  z  c_         # d| _        d| _        d| _        |j                         |j                         z   D ]  }d}| xj                  |j                  z  c_        t        |j                        dk(  rdnt        |j                        }t        |j                        dk(  rdnt        |j                        }| j                  |k  r|| _        t        |      t        |      dz  z  }| j
                  |k  s|| _         d| _        |j                  D ]B  }t        |t         t"        f      s| xj                  |j$                  j                  z  c_        D d| _        |j                  D ]G  }t        |t(        t*        t,        f      s| xj&                  |j$                  j                  z  c_        I y )Nr   rT   r   )num_scalar_variablesr   sizemax_data_dimensionnum_scalar_datamax_big_small_squaredr   r   r   rE  r   minr  num_scalar_eq_constrrz   r]   r   r   r   num_scalar_leq_constrr   r   r   )rF   rQ  r   constbigsmallr  ra   s           rG   rH   zSizeMetrics.__init__  s   $%!$$& 	2C%%1%	2 #$ %&"&&(););)== 	CEC  EJJ. 5;;'1,!#ekk2BCU[[)Q.AC4DE &&,*-'$)#Jea$@!)),AA-B*	C  %&!!-- 	BJ*x&67))Z__-A-AA)	B
 &'"!-- 	CJ*z66&BC**joo.B.BB*	CrI   N)rQ  rd   rW   rX   )rY   rZ   r[   r  rH   rM   rI   rG   r   r     s    4#CrI   r   )dr  
__future__r   r  rj   collectionsr   dataclassesr   typingr   r   r   r	   numpyr  cvxpy.utilities	utilitiesu!cvxpy.utilities.performance_utilsperformance_utilsr  cvxpyr
   r   r   r   cvxpy.atoms.atomr   cvxpy.constraintsr   r   r   r   r   cvxpy.constraints.constraintr   cvxpy.errorr   cvxpy.expressionsr   cvxpy.expressions.variabler    cvxpy.interface.matrix_utilitiesr   cvxpy.problems.objectiver   r   cvxpy.reductionsr   cvxpy.reductions.chainr    cvxpy.reductions.dgp2dcp.dgp2dcpr   cvxpy.reductions.dqcp2dcpr   cvxpy.reductions.eval_paramsr   cvxpy.reductions.flip_objectiver   cvxpy.reductions.solutionr    cvxpy.reductions.solversr!   r"   r!  3cvxpy.reductions.solvers.conic_solvers.conic_solverr#    cvxpy.reductions.solvers.definesr$   r%   -cvxpy.reductions.solvers.qp_solvers.qp_solverr&   cvxpy.reductions.solvers.solverr'   &cvxpy.reductions.solvers.solving_chainr(   r)   cvxpy.settingsr*   r+   cvxpy.utilities.citationsr,   cvxpy.utilities.deterministicr-   r.   
_COL_WIDTHcenterversionrS  r	  ra  r[  re  r=   rb   	Canonicalrd   r  r   rM   rI   rG   <module>r     sZ   #   " ! . .   0 0 !  ! H H 3   & / 9 7 ( ( 4 . 3 9 8 . 7 K L B 2 # ' 3 5;=
 

N	Z ! 		 	8%%j1	2
 		 
N  
N	:&' 		 
N	  
N	
+, 		 
N	  
N	$% 		 
N	  
N	z"# 		 
N	 4 4(	+Eakk EP. 1
 1
 1
f>C >CrI   