
    z	iπ                    6   S r SSKJr  SSKrSSKJr  SSKJr  SSK	r
SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJrJr  SSKJr  SSK J!r!  SSK J"r"  SSK#J$r$  SSK%J&r&  SSK'J(r(J)r)  SSK*J+r+  \(       a  SSKJ,r,   " S S\\5      r-g)z$
DensityMatrix quantum state class.
    )annotationsN)Number)TYPE_CHECKING)_numpy_compat)QuantumCircuit)Instruction)QiskitError)QuantumState)TolerancesMixin)OpShape)Operator)PauliSparsePauliOp)ScalarOp)is_hermitian_matrix)is_positive_semidefinite_matrix)QuantumChannel)SuperOp)density_expval_pauli_no_xdensity_expval_pauli_with_x)Statevector)circuitc                    ^  \ rS rSrSr S%   S&U 4S jjjrS\R                  4S jrU 4S jr	S r
\S 5       rS%S'S	 jjrS
 r\S 5       rS(S jrS)S jrS rS rS rS*S jrS*S jrS rS r S%     S+S jjrS,S jrS%S jrS%S-S jjr S(     S.S jjrS%S/S jjr\S0S j5       r \!S1S j5       r"\    S2S j5       r#S%S3S jjr$S%S jr%S%S  jr&S%S! jr'S(S4S" jjr(S5S# jr)S$r*U =r+$ )6DensityMatrix.   zDensityMatrix classNc                0  > [        U[        [        R                  45      (       a  [        R                  " U[
        S9U l        O[        U[        [        45      (       a%  [        R                  U5      R                  U l        O[        US5      (       a5  UR                  5       nUR                  U l        Uc  UR                  5       nOI[        US5      (       a-  [        R                  " UR                  5       [
        S9U l        O[!        S5      eU R                  R"                  nU R                  R$                  nUS:X  a  US   US   :X  a  OUS:X  aE  [        R&                  " U R                  [        R(                  " U R                  5      5      U l        ODUS:X  a3  US   S:X  a*  [        R*                  " U R                  US   5      U l        O[!        S	5      e[,        TU ]]  [0        R2                  " U R                  R$                  X"S
9S9  g)a_  Initialize a density matrix object.

Args:
    data: A statevector, quantum instruction or an object with a ``to_operator`` or
        ``to_matrix`` method from which the density matrix can be constructed.
        If a vector the density matrix is constructed as the projector of that vector.
        If a quantum instruction, the density matrix is constructed by assuming all
        qubits are initialized in the zero state.
    dims: The subsystem dimension of the state (See additional information).

Raises:
    QiskitError: if input data is not valid.

Additional Information:
    The ``dims`` kwarg can be None, an integer, or an iterable of
    integers.

    * ``Iterable`` -- the subsystem dimensions are the values in the list
      with the total number of subsystems given by the length of the list.

    * ``Int`` or ``None`` -- the leading dimension of the input matrix
      specifies the total dimension of the density matrix. If it is a
      power of two the state will be initialized as an N-qubit state.
      If it is not a power of two the state will have a single
      d-dimensional subsystem.
dtypeto_operatorN	to_matrixz+Invalid input data format for DensityMatrix   r      z1Invalid DensityMatrix input: not a square matrix.)shapedims_ldims_r)op_shape)
isinstancelistnpndarrayasarraycomplex_datar   r   r   from_instructionhasattrr   dataoutput_dimsr    r	   ndimr#   outerconjreshapesuper__init__r   auto)selfr0   dimsopr2   r#   	__class__s         b/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/quantum_info/states/densitymatrix.pyr7   DensityMatrix.__init__1   s   > dT2::.// D8DJ~{;<< '77=CCDJT=)) !!#BDJ|~~'T;'' DNN$4GDDJKLLzz

  19qU1X-QY$**bggdjj.ABDJQY58q=DJJa9DJQRR',,TZZ5E5Ed"`a    c                v    Uc  U R                   R                  OUn[        R                  " U R                   XS9$ )N)r   copy)r0   r   r)   array)r9   r   rA   s      r=   	__array__DensityMatrix.__array__t   s*    #(=		exx		::r?   c                   > [         TU ]  U5      =(       a?    [        R                  " U R                  UR                  U R
                  U R                  S9$ )Nrtolatol)r6   __eq__r)   allcloser-   rG   rH   )r9   otherr<   s     r=   rI   DensityMatrix.__eq__x   s=    w~e$ 
JJ$))$))*
 	
r?   c                    Sn[        U5      S-  nU [        R                  " U R                  SUS9 SU SU R                  R                  5        S3$ )NzDensityMatrix( z, )	separatorprefixz,
zdims=))lenr)   array2stringr-   	_op_shaper$   )r9   rP   pads      r=   __repr__DensityMatrix.__repr__}   sX    !&kChrtzzT&QRRUe5..014	
r?   c                P    U R                   U R                  R                  5       S.$ )zReturn settings.)r0   r:   )r0   rT   r$   r9   s    r=   settingsDensityMatrix.settings   s      		4>>+@+@+BCCr?   c                $    SSK Jn  U" U 4SU0UD6$ )a  Return a visualization of the Statevector.

**repr**: ASCII TextMatrix of the state's ``__repr__``.

**text**: ASCII TextMatrix that can be printed in the console.

**latex**: An IPython Latex object for displaying in Jupyter Notebooks.

**latex_source**: Raw, uncompiled ASCII source to generate array using LaTeX.

**qsphere**: Matplotlib figure, rendering of density matrix using `plot_state_qsphere()`.

**hinton**: Matplotlib figure, rendering of density matrix using `plot_state_hinton()`.

**bloch**: Matplotlib figure, rendering of density matrix using `plot_bloch_multivector()`.

Args:
    output (str): Select the output method to use for drawing the
        state. Valid choices are `repr`, `text`, `latex`, `latex_source`,
        `qsphere`, `hinton`, or `bloch`. Default is `repr`. Default can
        be changed by adding the line ``state_drawer = <default>`` to
        ``~/.qiskit/settings.conf`` under ``[default]``.
    drawer_args: Arguments to be passed directly to the relevant drawing
        function or constructor (`TextMatrix()`, `array_to_latex()`,
        `plot_state_qsphere()`, `plot_state_hinton()` or `plot_bloch_multivector()`).
        See the relevant function under `qiskit.visualization` for that function's
        documentation.

Returns:
    :class:`matplotlib.Figure` or :class:`str` or
    :class:`TextMatrix` or :class:`IPython.display.Latex`:
    Drawing of the Statevector.

Raises:
    ValueError: when an invalid output method is selected.
r   )state_draweroutput)(qiskit.visualization.state_visualizationr]   )r9   r^   drawer_argsr]   s       r=   drawDensityMatrix.draw   s    L 	JD??;??r?   c                    U R                  5       n[        U[        5      (       a  [        U5        g SSKJn  U" U5        g )Nr   )display)ra   r'   strprintIPython.displayrd   )r9   outrd   s      r=   _ipython_display_DensityMatrix._ipython_display_   s+    iikc3#J/CLr?   c                    U R                   $ )zReturn data.r-   rY   s    r=   r0   DensityMatrix.data   s     zzr?   c                    Uc  U R                   nUc  U R                  n[        R                  " U R	                  5       SX!S9(       d  g[        U R                  X!S9(       d  g[        U R                  X!S9$ )z1Return True if trace 1 and positive semidefinite.r"   rF   F)rH   rG   r)   rJ   tracer   r0   r   )r9   rH   rG   s      r=   is_validDensityMatrix.is_valid   sY    <99D<99D{{4::<A"4994C.tyytOOr?   c                J    U R                  5       n[        U R                  XS9$ )zConvert to Operator
input_dimsr1   )r:   r   r0   )r9   r:   s     r=   r   DensityMatrix.to_operator   s    yy{		dEEr?   c                n    [        [        R                  " U R                  5      U R	                  5       S9$ )z+Return the conjugate of the density matrix.r:   )r   r)   r4   r0   r:   rY   s    r=   	conjugateDensityMatrix.conjugate   s"    RWWTYY/diikBBr?   c                B    [         R                  " U R                  5      $ )z'Return the trace of the density matrix.)r)   ro   r0   rY   s    r=   ro   DensityMatrix.trace   s    xx		""r?   c                    [         R                  " [         R                  " U R                  U R                  5      5      $ )z'Return the purity of the quantum state.)r)   ro   dotr0   rY   s    r=   purityDensityMatrix.purity   s&     xxtyy$))455r?   c                &   [        U[        5      (       d  [        U5      n[        R                  " U 5      n[        R
                  " U R                  UR                  5      Ul        U R                  R                  UR                  5      Ul        U$ )u   Return the tensor product state self ⊗ other.

Args:
    other (DensityMatrix): a quantum state object.

Returns:
    DensityMatrix: the tensor product operator self ⊗ other.

Raises:
    QiskitError: if other is not a quantum state.
)	r'   r   _copyrA   r)   kronr-   rT   tensorr9   rK   rets      r=   r   DensityMatrix.tensor   sb     %//!%(EjjGGDJJ4	--eoo>
r?   c                &   [        U[        5      (       d  [        U5      n[        R                  " U 5      n[        R
                  " UR                  U R                  5      Ul        U R                  R                  UR                  5      Ul        U$ )u   Return the tensor product state other ⊗ self.

Args:
    other (DensityMatrix): a quantum state object.

Returns:
    DensityMatrix: the tensor product state other ⊗ self.

Raises:
    QiskitError: if other is not a quantum state.
)	r'   r   r   rA   r)   r   r-   rT   expandr   s      r=   r   DensityMatrix.expand   sb     %//!%(EjjGGEKK4	--eoo>
r?   c                    [        U[        5      (       d  [        U5      nU R                  R                  UR                  5        [        R
                  " U 5      nU R                  UR                  -   Ul        U$ )a  Return the linear combination self + other.

Args:
    other (DensityMatrix): a quantum state object.

Returns:
    DensityMatrix: the linear combination self + other.

Raises:
    QiskitError: if other is not a quantum state, or has
                 incompatible dimensions.
)r'   r   rT   _validate_addr   rA   r0   r-   r   s      r=   _addDensityMatrix._add  sX     %//!%(E$$U__5jjII

*	
r?   c                    [        U[        5      (       d  [        S5      e[        R                  " U 5      nXR
                  -  Ul        U$ )zReturn the scalar multiplied state other * self.

Args:
    other (complex): a complex number.

Returns:
    DensityMatrix: the scalar multiplied state other * self.

Raises:
    QiskitError: if other is not a valid complex number.
zother is not a number)r'   r   r	   r   rA   r0   r-   r   s      r=   	_multiplyDensityMatrix._multiply   s>     %((566jjII%	
r?   c                   Uc  [        USS5      n[        U[        [        45      (       a  U R	                  XS9$ [        US5      (       a  UR                  5       R                  XS9$ [        U[        5      (       a  UR                  XS9$ [        U[        5      (       d  U R                  US9n[        XUS9nU R                  XS9$ )aR  Evolve a quantum state by an operator.

Args:
    other: The operator to evolve by.
    qargs: a list of QuantumState subsystem positions to apply the operator on.

Returns:
    The output density matrix.

Raises:
    QiskitError: if the operator dimension does not match the
                 specified QuantumState subsystem dimensions.
Nqargsr   to_quantumchannelrs   )getattrr'   r   r   _evolve_instructionr/   r   _evolver   r   r:   _evolve_operator)r9   rK   r   r:   s       r=   evolveDensityMatrix.evolve2  s    $ =E7D1E enk:;;++E+??
 5-..**,44T4GGe^,,===33 %**9959)DUFE$$U$88r?   c                  ^ [         R                  " U 5      n[        [        U R                  R
                  S-
  SS5      5      mT[        U4S jT 5       5      -   m[        R                  " [        R                  " [        R                  " U R                  U R                  R                  5      T5      U R                  R                  5      Ul        U R                  R                  5       Ul        U$ )aw  Return a DensityMatrix with reversed subsystem ordering.

For a tensor product state this is equivalent to reversing the order
of tensor product subsystems. For a density matrix
:math:`\rho = \rho_{n-1} \otimes ... \otimes \rho_0`
the returned state will be
:math:`\rho_0 \otimes ... \otimes \rho_{n-1}`.

Returns:
    DensityMatrix: the state with reversed subsystem order.
r"   c              3  @   >#    U  H  n[        T5      U-   v   M     g 7fN)rR   ).0iaxess     r=   	<genexpr>.DensityMatrix.reverse_qargs.<locals>.<genexpr>g  s     84aCIM4s   )r   rA   tuplerangerT   _num_qargs_lr)   r5   	transposer0   tensor_shaper#   r-   reverse)r9   r   r   s     @r=   reverse_qargsDensityMatrix.reverse_qargsY  s     jjU4>>66:BCDe84888JJLLDIIt~~/J/JKTRNN  
	 ..0
r?   c           	        [        U5      nUc  [        R                  " U5      nO[        R                  " U5      n[        R                  " SU-  UR
                  5      n[        R                  " SU-  UR                  5      nUR                  (       a  SUR                  -  OSnXV-   S:X  a  XpR                  5       -  $ [        R                  " U R                  SS9nUS:X  a  U[        XR                  U5      -  $ XAR
                     S   n	SUR                  5       -  n
U
S   n
U[        XR                  XeX5      -  $ )zCompute the expectation value of a Pauli.

Args:
    pauli (Pauli): a Pauli operator to evaluate expval of.
    qargs (None or list): subsystems to apply operator on.

Returns:
    complex: the expectation value.
r"   y             r   F)orderr   )rR   r)   arangerB   r}   xzphasero   ravelr0   r   
num_qubits_count_yr   )r9   paulir   n_pauliqubitsx_maskz_maskpauli_phaser0   x_maxy_phases              r=   _expectation_value_pauli&DensityMatrix._expectation_value_paulio  s	    e*=YYw'FXXe_FVUWW-VUWW-.3kksu{{*q?a--xx		-Q;!:4RX!YYYww#5>>++!*8//67
 
 	
r?   c                  ^ ^ [        U[        5      (       a  T R                  UT5      $ [        U[        5      (       aS  [	        UU 4S j[        UR                  R                  UR                  R                  UR                  5       5       5      $ [        U[        5      (       d  [        U5      n[        R                  " [        T 5      R                  UTS9R                  5      $ )zCompute the expectation value of an operator.

Args:
    oper (Operator): an operator to evaluate expval.
    qargs (None or list): subsystems to apply the operator on.

Returns:
    complex: the expectation value.
c              3  h   >#    U  H'  u  pnUTR                  [        X45      T5      -  v   M)     g 7fr   )r   r   )r   r   r   coeffr   r9   s       r=   r   2DensityMatrix.expectation_value.<locals>.<genexpr>  s4      #QKA% 55eQFmUKK#Qs   /2r   )r'   r   r   r   sumzippaulisr   r   coeffsr   r)   ro   r}   r0   )r9   operr   s   ` `r=   expectation_valueDensityMatrix.expectation_value  s     dE""00u==dM** #&t{{}}dkkmmT[[#Q  
 $))D>Dxx**4u*=BBCCr?   c                    U R                  [        R                  " U R                  R	                  5       5      U R
                  R                  5       US9n[        R                  " USSS9nUb  UR                  US9nU$ )a'  Return the subsystem measurement probability vector.

Measurement probabilities are with respect to measurement in the
computation (diagonal) basis.

Args:
    qargs (None or list): subsystems to return probabilities for,
        if None return for all subsystems (Default: None).
    decimals (None or int): the number of decimal places to round
        values. If None no rounding is done (Default: None).

Returns:
    np.array: The Numpy vector array of probabilities.

Examples:

    Consider a 2-qubit product state :math:`\rho=\rho_1\otimes\rho_0`
    with :math:`\rho_1=|+\rangle\!\langle+|`,
    :math:`\rho_0=|0\rangle\!\langle0|`.

    .. plot::
       :include-source:
       :nofigs:

        from qiskit.quantum_info import DensityMatrix

        rho = DensityMatrix.from_label('+0')

        # Probabilities for measuring both qubits
        probs = rho.probabilities()
        print('probs: {}'.format(probs))

        # Probabilities for measuring only qubit-0
        probs_qubit_0 = rho.probabilities([0])
        print('Qubit-0 probs: {}'.format(probs_qubit_0))

        # Probabilities for measuring only qubit-1
        probs_qubit_1 = rho.probabilities([1])
        print('Qubit-1 probs: {}'.format(probs_qubit_1))

    .. code-block:: text

        probs: [0.5 0.  0.5 0. ]
        Qubit-0 probs: [1. 0.]
        Qubit-1 probs: [0.5 0.5]

    We can also permute the order of qubits in the ``qargs`` list
    to change the qubit position in the probabilities output

    .. plot::
       :include-source:
       :nofigs:

        from qiskit.quantum_info import DensityMatrix

        rho = DensityMatrix.from_label('+0')

        # Probabilities for measuring both qubits
        probs = rho.probabilities([0, 1])
        print('probs: {}'.format(probs))

        # Probabilities for measuring both qubits
        # but swapping qubits 0 and 1 in output
        probs_swapped = rho.probabilities([1, 0])
        print('Swapped probs: {}'.format(probs_swapped))

    .. code-block:: text

        probs: [0.5 0.  0.5 0. ]
        Swapped probs: [0.5 0.5 0.  0. ]
r   r   r"   )a_mina_max)decimals)	_subsystem_probabilitiesr)   absr0   diagonalrT   r$   clipround)r9   r   r   probss       r=   probabilitiesDensityMatrix.probabilities  ss    T --FF499%%'($..*?*?*A . 

 Qa0KKK2Er?   c                   UcP  [         R                  " U 5      n[        R                  " U R                  R
                  [        S9nSUS'   X2l        U$ U R                  U5      n[        [        USS95      n[        [        U5      5      R                  R                  5       UR                  S'   U R                  XQS9$ )a  Reset state or subsystems to the 0-state.

Args:
    qargs (list or None): subsystems to reset, if None all
                          subsystems will be reset to their 0-state
                          (Default: None).

Returns:
    DensityMatrix: the reset state.

Additional Information:
    If all subsystems are reset this will return the ground state
    on all subsystems. If only a some subsystems are reset this
    function will perform evolution by the reset
    :class:`~qiskit.quantum_info.SuperOp` of the reset subsystems.
r   r"   r   r   r   )r   r   )r   rA   r)   zerosrT   r#   r,   r-   r:   r   r   r   r0   r   r   )r9   r   r   stater:   reset_superops         r=   resetDensityMatrix.reset  s    " =**T"CHHT^^11AEE$KIJ yyQ 78 ($ 8 = = C C E1{{={66r?   c                @    [        [        R                  " U5      5      $ )a  Return a tensor product of Pauli X,Y,Z eigenstates.

.. list-table:: Single-qubit state labels
   :header-rows: 1

   * - Label
     - Statevector
   * - ``"0"``
     - :math:`\begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}`
   * - ``"1"``
     - :math:`\begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}`
   * - ``"+"``
     - :math:`\frac{1}{2}\begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}`
   * - ``"-"``
     - :math:`\frac{1}{2}\begin{pmatrix} 1 & -1 \\ -1 & 1 \end{pmatrix}`
   * - ``"r"``
     - :math:`\frac{1}{2}\begin{pmatrix} 1 & -i \\ i & 1 \end{pmatrix}`
   * - ``"l"``
     - :math:`\frac{1}{2}\begin{pmatrix} 1 & i \\ -i & 1 \end{pmatrix}`

Args:
    label (string): a eigenstate string ket label (see table for
                    allowed values).

Returns:
    DensityMatrix: The N-qubit basis state density matrix.

Raises:
    QiskitError: if the label contains invalid characters, or the length
                 of the label is larger than an explicitly specified num_qubits.
)r   r   
from_label)clslabels     r=   r   DensityMatrix.from_label  s    D [33E:;;r?   c                    [         R                  " U5      n[         R                  " X"4[        S9nSX0U 4'   [	        X1S9$ )a4  Return a computational basis state density matrix.

Args:
    i (int): the basis state element.
    dims (int or tuple or list): The subsystem dimensions of the statevector
                                 (See additional information).

Returns:
    DensityMatrix: The computational basis state :math:`|i\rangle\!\langle i|`.

Additional Information:
    The ``dims`` kwarg can be an integer or an iterable of integers.

    * ``Iterable`` -- the subsystem dimensions are the values in the list
      with the total number of subsystems given by the length of the list.

    * ``Int`` -- the integer specifies the total dimension of the
      state. If it is a power of two the state will be initialized
      as an N-qubit state. If it is not a power of  two the state
      will have a single d-dimensional subsystem.
r   g      ?rw   )r)   prodr   r,   r   )r   r:   sizer   s       r=   from_intDensityMatrix.from_int@  s9    . wwt}$W5dU..r?   c                    [        U[        5      (       a  UR                  5       nUR                  n[        R
                  " SU-  SU-  4[        S9nSUS'   [        X2S-  S9nUR                  U5        U$ )a  Return the output density matrix of an instruction.

The statevector is initialized in the state :math:`|{0,\ldots,0}\rangle` of
the same number of qubits as the input instruction or circuit, evolved
by the input instruction, and the output statevector returned.

Args:
    instruction: instruction or circuit

Returns:
    The final density matrix.

Raises:
    QiskitError: if the instruction contains invalid instructions for
                 density matrix simulation.
r!   r   r"   r   )r!   rw   )	r'   r   to_instructionr   r)   r   r,   r   _append_instruction)r   instructionr   initvecs        r=   r.   DensityMatrix.from_instruction\  sr    * k>22%446K ++
xxJ:6gFT
DD'89,
r?   c                j    U R                  U R                  U R                  R                  5       USS9$ )a  Convert the density matrix to dictionary form.

This dictionary representation uses a Ket-like notation where the
dictionary keys are qudit strings for the subsystem basis vectors.
If any subsystem has a dimension greater than 10 comma delimiters are
inserted between integers so that subsystems can be distinguished.

Args:
    decimals (None or int): the number of decimal places to round
                            values. If None no rounding is done
                            (Default: None).

Returns:
    dict: the dictionary form of the DensityMatrix.

Examples:

    The ket-form of a 2-qubit density matrix
    :math:`rho = |-\rangle\!\langle -|\otimes |0\rangle\!\langle 0|`

    .. plot::
       :include-source:
       :nofigs:

        from qiskit.quantum_info import DensityMatrix

        rho = DensityMatrix.from_label('-0')
        print(rho.to_dict())

    .. code-block:: text

       {
           '00|00': (0.4999999999999999+0j),
           '10|00': (-0.4999999999999999-0j),
           '00|10': (-0.4999999999999999+0j),
           '10|10': (0.4999999999999999+0j)
       }

    For non-qubit subsystems the integer range can go from 0 to 9. For
    example in a qutrit system

    .. plot::
       :include-source:
       :nofigs:

        import numpy as np
        from qiskit.quantum_info import DensityMatrix

        mat = np.zeros((9, 9))
        mat[0, 0] = 0.25
        mat[3, 3] = 0.25
        mat[6, 6] = 0.25
        mat[-1, -1] = 0.25
        rho = DensityMatrix(mat, dims=(3, 3))
        print(rho.to_dict())

    .. code-block:: text

        {'00|00': (0.25+0j), '10|10': (0.25+0j), '20|20': (0.25+0j), '22|22': (0.25+0j)}

    For large subsystem dimensions delimiters are required. The
    following example is for a 20-dimensional system consisting of
    a qubit and 10-dimensional qudit.

    .. plot::
       :include-source:
       :nofigs:

        import numpy as np
        from qiskit.quantum_info import DensityMatrix

        mat = np.zeros((2 * 10, 2 * 10))
        mat[0, 0] = 0.5
        mat[-1, -1] = 0.5
        rho = DensityMatrix(mat, dims=(2, 10))
        print(rho.to_dict())

    .. code-block:: text

        {'00|00': (0.5+0j), '91|91': (0.5+0j)}
T)r   string_labels)_matrix_to_dictr0   rT   r$   )r9   r   s     r=   to_dictDensityMatrix.to_dict{  s8    d ##IIt~~,,.QU $ 
 	
r?   c                    U R                   R                  UR                   US9nUR                  Ul        UR                  Ul        [        R                  " U 5      nUc`  UR                  n[        R                  " XPR                  5      R                  UR                  R                  5       5      Ul        X4l         U$ [        R                  " U R                  U R                   R                  5      n[!        U R#                  5       5      nU Vs/ s H
  oS-
  U-
  PM     n	n[        R                  " UR                  UR                   R                  5      n
[$        R&                  " XjU	5      nUR)                  5       n[        R                  " UR                  UR                   R                  5      n[$        R&                  " XlXS5      n[        R                  " XcR*                  5      Ul        X4l         U$ s  snf )z$Evolve density matrix by an operatorr   r"   T)rT   compose_dims_l_dims_rr   _num_qargs_rr   rA   r0   r)   r}   Tr4   r-   r5   r   rR   r:   r   _einsum_matmuladjointr#   )r9   rK   r   	new_shaper   op_matr   num_indicesqubitindicesmatadjmat_adjs                r=   r   DensityMatrix._evolve_operator  sh    NN**5??%*H	%--	!*!7!7	jj=ZZFvyy155fhhmmoFCI%MJ DIIt~~'B'BC$))+&8=>u?U*>jjU__%A%AB((g>mmo**SXXs}}'A'AB(('PTUJJv7	!
 ?s   G;c                B   SSK Jn  SSKJn  [        R
                  " U5      nUb)  U R                  [	        U5      US9R                  U l        g[        X5      (       a!  U R                  U5      R                  U l        g[        X5      (       a  g[        R                  " U5      nUb  UR                  XS9R                  U l        gUR                  c  [        SUR                    35      e[        UR                  ["        5      (       d.  [        UR                    S[%        UR                  5       S35      e['        UR                  R(                  5       VVs0 s H  u  pxX_M	     n	nnUR                   H  n
U
R*                  (       a"  [        S	U
R,                  R                    35      eUc  U
R(                   Vs/ s H  oU   PM	     nnO U
R(                   Vs/ s H	  oX      PM     nnU R/                  U
R,                  US9  M     gs  snnf s  snf s  snf )
z:Update the current Statevector by applying an instruction.r   )Reset)BarrierNr   zCannot apply Instruction: z instruction definition is z; expected QuantumCircuitz.Cannot apply instruction with classical bits: )qiskit.circuit.resetr  qiskit.circuit.barrierr  r   _instruction_to_matrixr   r0   r-   r'   r   r   _instruction_to_superopr   
definitionr	   namer   type	enumerater   clbits	operationr   )r9   rK   r   r  r  r  chanidxbitqubit_indicesr   tup	new_qargss                r=   r   !DensityMatrix._append_instruction  s   .2 --e4?..x}E.JOODJ e##E*00DJe%% ..u5d8==DJ # :5::,GHH%**N;;::,9$u?O?O:P9Q R+ ,  3<E<L<L<S<S2TU2Thc2TU ++K!!!D[EZEZE_E_D`a  };F;M;MN;MC3/;M	N	BMBTBTUBT3=#56BT	U$$[%:%:)$L , V OUs   HH Hc                    [        U[        5      (       a  UR                  5       n[        R                  " U 5      nUR                  XS9  U$ )z4Return a new statevector by applying an instruction.r   )r'   r   r   r   rA   r   )r9   objr   r   s       r=   r   !DensityMatrix._evolve_instruction   sA    c>**$$&Cjj1
r?   c                   Uc  U R                   nUc  U R                  n[        U R                  XS9(       d  [	        S5      e[
        R                  R                  U R                  5      u  p4U[        U5      U:     n[        U5      S:w  d  [
        R                  " US   SXS9(       d  [	        S5      eUSS2[
        R                  " U5      4   n[        U5      $ )a  Return a statevector from a pure density matrix.

Args:
    atol (float): Absolute tolerance for checking operation validity.
    rtol (float): Relative tolerance for checking operation validity.

Returns:
    Statevector: The pure density matrix's corresponding statevector.
        Corresponds to the eigenvector of the only non-zero eigenvalue.

Raises:
    QiskitError: if the state is not pure.
N)rH   rG   z+Not a valid density matrix (non-hermitian).r"   r   z"Density matrix is not a pure state)rH   rG   r   r-   r	   r)   linalgeigr   rR   iscloseargmaxr   )r9   rH   rG   evalsevecsnonzero_evalspsis          r=   to_statevectorDensityMatrix.to_statevector(  s     <99D<99D"4::DDKLLyy}}TZZ0c%j4/0}""**]15Eqt*_BCCAryy''(3r?   c                    U R                   R                  U R                  R                  5      n[	        U R                  R                  5       5      S-
  [        R                  " U5      -
  n[	        U R                  5       5      n[        [        SU-  5      5      nU H  nXEU-      XE   sXE'   XEU-   '   M     [        R                  " X$5      n[        R                  " X`R                  R                  5      n[        X`R                  5       S9$ )zReturn partially transposed density matrix.

Args:
    qargs (list): The subsystems to be transposed.

Returns:
    DensityMatrix: The partially transposed density matrix.
r"   r!   rw   )r-   r5   rT   r   rR   r$   r)   rB   r:   r(   r   r   r#   r   )r9   r   arrnlstr   rhos          r=   partial_transposeDensityMatrix.partial_transposeH  s     jj  !<!<=DNN))+,q0288E?B		5Q< A!$USVCFCAJ ll3$jjnn223Syy{33r?   rl   r   )r0   zSnp.ndarray | list | QuantumCircuit | circuit.instruction.Instruction | QuantumStater:   zint | tuple | list | None)r^   z
str | None)NN)returnr   )rK   r   r.  r   )rK   zLOperator | QuantumChannel | circuit.instruction.Instruction | QuantumCircuitr   list[int] | Noner.  r   )r.  r   )r   r   r   None | list[int]r.  r,   )r   r0  r   
None | intr.  z
np.ndarray)r   r/  r.  r   )r   re   r.  r   )r   intr:   zint | tuple | listr.  r   )r   z0circuit.instruction.Instruction | QuantumCircuitr.  r   )r   r1  r.  dict)rH   float | NonerG   r4  r.  r   )r   z	list[int]r.  r   ),__name__
__module____qualname____firstlineno____doc__r7   r   COPY_ONLY_IF_NEEDEDrC   rI   rV   propertyrZ   ra   ri   r0   rp   r   rx   ro   r~   r   r   r   r   r   r   r   r   r   r   classmethodr   staticmethodr   r.   r   r   r   r   r%  r,  __static_attributes____classcell__)r<   s   @r=   r   r   .   s   
 +/AbaAb (Ab AbF #)J)J ;


 D D(@T  PF
C#6&&(* #'%9[%9  %9 
	%9N,
BD0 FJT%T8BT	Tl7> !< !<F / /6 J	 <T
l@-M^ @4 4r?   r   ).r9  
__future__r   rA   r   numbersr   typingr   numpyr)   qiskitr   qiskit.circuit.quantumcircuitr   qiskit.circuit.instructionr   qiskit.exceptionsr	   (qiskit.quantum_info.states.quantum_stater
   /qiskit.quantum_info.operators.mixins.tolerancesr   &qiskit.quantum_info.operators.op_shaper   &qiskit.quantum_info.operators.operatorr   (qiskit.quantum_info.operators.symplecticr   r   'qiskit.quantum_info.operators.scalar_opr   (qiskit.quantum_info.operators.predicatesr   r   5qiskit.quantum_info.operators.channel.quantum_channelr   -qiskit.quantum_info.operators.channel.superopr   qiskit._accelerate.pauli_expvalr   r   &qiskit.quantum_info.states.statevectorr   r   r    r?   r=   <module>rT     sa    #        8 2 ) A K : ; I < H T P A b >k4L/ k4r?   