§
    º³Ùg¶  ã                  ó4  — d Z ddlmZ ddlZddlmZ ddlmZ ddl	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 ddlmZ ddlmZ ddl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l*m+Z+ erddlm,Z,  G d„ dee¦  «        Z-dS )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                  ó€  ‡ — e Zd ZdZ	 dBdCˆ fd„Zdej        fd„Zˆ fd	„Zd
„ Z	e
d„ ¦   «         ZdBdDd„Zd„ Ze
d„ ¦   «         ZdEd„ZdFd„Zd„ Zd„ Zd„ ZdGd„ZdGd„Zd„ Zd„ Z	 dBdHd „ZdId!„ZdBd"„ZdBdJd&„Z	 dEdKd*„ZdBdLd+„ZedMd.„¦   «         Ze dNd2„¦   «         Z!edOd5„¦   «         Z"dBdPd7„Z#dBd8„Z$dBd9„Z%dBd:„Z&dEdQd?„Z'dRdA„Z(ˆ xZ)S )SÚDensityMatrixzDensityMatrix classNÚdataúSnp.ndarray | list | QuantumCircuit | circuit.instruction.Instruction | QuantumStateÚdimsúint | tuple | list | Nonec                ó,  •— t          |t          t          j        f¦  «        r!t          j        |t
          ¬¦  «        | _        nÚt          |t          t          f¦  «        r%t           
                    |¦  «        j        | _        n™t          |d¦  «        r7|                     ¦   «         }|j        | _        |€|                     ¦   «         }nRt          |d¦  «        r3t          j        |                     ¦   «         t
          ¬¦  «        | _        nt!          d¦  «        ‚| j        j        }| j        j        }|dk    r|d         |d         k    rn„|dk    r7t          j        | j        t          j        | j        ¦  «        ¦  «        | _        nG|dk    r2|d         dk    r&t          j        | j        |d         ¦  «        | _        nt!          d	¦  «        ‚t-          ¦   «                              t1          j        | j        j        ||¬
¦  «        ¬¦  «         dS )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"   r   Úoutput_dimsr#   r	   Úndimr&   ÚouterÚconjÚreshapeÚsuperÚ__init__r   Úauto)Úselfr   r   Úopr4   r&   Ú	__class__s         €ú^/granary/edev/quantum/lib/python3.11/site-packages/qiskit/quantum_info/states/densitymatrix.pyr9   zDensityMatrix.__init__1   sË  ø€ õ> �d�T¥2¤:Ð.Ñ/Ô/ð 	Mõ œ DµÐ8Ñ8Ô8ˆDŒJˆJÝ˜�~­{Ð;Ñ<Ô<ð 	Mõ '×7Ò7¸Ñ=Ô=ÔCˆDŒJˆJÝ�T˜=Ñ)Ô)ð 	Mð ×!Ò!Ñ#Ô#ˆBØœˆDŒJØˆ|Ø—~’~Ñ'Ô'�øÝ�T˜;Ñ'Ô'ð 	Mõ œ D§N¢NÑ$4Ô$4½GÐDÑDÔDˆDŒJˆJåÐKÑLÔLÐLàŒzŒˆØ”
Ô ˆØ�1Š9ˆ9˜˜qœ U¨1¤XÒ-Ð-ØØ�QŠYˆYÝœ $¤*­b¬g°d´jÑ.AÔ.AÑBÔBˆDŒJˆJØ�QŠYˆY˜5 œ8 qš=˜=Ýœ D¤J°°a´Ñ9Ô9ˆDŒJˆJåÐQÑRÔRÐRÝ‰Œ×Ò¥'¤,°T´ZÔ5EÈdÐ[_Ð"`Ñ"`Ô"`ÐÑaÔaÐaÐaÐaó    c                óZ   — |€| j         j        n|}t          j        | j         ||¬¦  «        S )N)r!   Úcopy)r   r!   r,   Úarray)r;   r!   rA   s      r>   Ú	__array__zDensityMatrix.__array__t   s,   € Ø#( =�”	”�°eˆÝŒx˜œ	¨°TÐ:Ñ:Ô:Ð:r?   c                óž   •— t          ¦   «                              |¦  «        o+t          j        | j        |j        | j        | j        ¬¦  «        S )N©ÚrtolÚatol)r8   Ú__eq__r,   Úallcloser0   rF   rG   )r;   Úotherr=   s     €r>   rH   zDensityMatrix.__eq__x   sD   ø€ Ý‰wŒw�~Š~˜eÑ$Ô$ð 
­¬ØŒJ˜œ¨$¬)¸$¼)ð*
ñ *
ô *
ð 	
r?   c                ó¦   — d}t          |¦  «        dz  }|› t          j        | j        d|¬¦  «        › d|› d| j                             ¦   «         › d�S )NzDensityMatrix(ú z, )Ú	separatorÚprefixz,
zdims=ú))Úlenr,   Úarray2stringr0   Ú	_op_shaper'   )r;   rN   Úpads      r>   Ú__repr__zDensityMatrix.__repr__}   sp   € Ø!ˆÝ�&‰kŒk˜CÑˆàð 4•r” t¤z¸TÈ&ÐQÑQÔQð 4ð 4Øð4ð 4Øœ×.Ò.Ñ0Ô0ð4ð 4ð 4ð	
r?   c                óD   — | j         | j                             ¦   «         dœS )zReturn settings.)r   r   )r   rR   r'   ©r;   s    r>   ÚsettingszDensityMatrix.settings…   s"   € ð œ	¨4¬>×+@Ò+@Ñ+BÔ+BÐCÐCÐCr?   Úoutputú
str | Nonec                ó$   — ddl m}  || fd|i|¤ŽS )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_drawerrX   )Ú(qiskit.visualization.state_visualizationr[   )r;   rX   Údrawer_argsr[   s       r>   ÚdrawzDensityMatrix.drawŠ   s5   € ðL 	JÐIÐIÐIÐIÐIàˆ|˜DÐ?Ð?¨Ð?°;Ð?Ð?Ð?r?   c                óœ   — |                       ¦   «         }t          |t          ¦  «        rt          |¦  «         d S ddlm}  ||¦  «         d S )Nr   )Údisplay)r^   r*   ÚstrÚprintÚIPython.displayr`   )r;   Úoutr`   s      r>   Ú_ipython_display_zDensityMatrix._ipython_display_´   sS   € Ø�iŠi‰kŒkˆÝ�c�3ÑÔð 	Ý�#‰JŒJˆJˆJˆJà/Ð/Ð/Ð/Ð/Ð/àˆG�C‰LŒLˆLˆLˆLr?   c                ó   — | j         S )zReturn data.)r0   rV   s    r>   r   zDensityMatrix.data½   s   € ð ŒzÐr?   c                óÞ   — |€| j         }|€| j        }t          j        |                      ¦   «         d||¬¦  «        sdS t          | j        ||¬¦  «        sdS t          | j        ||¬¦  «        S )z1Return True if trace 1 and positive semidefinite.Nr%   rE   F)rG   rF   r,   rI   Útracer   r   r   )r;   rG   rF   s      r>   Úis_validzDensityMatrix.is_validÂ   sw   € àˆ<Ø”9ˆDØˆ<Ø”9ˆDåŒ{˜4Ÿ:š:™<œ<¨°¸DÐAÑAÔAð 	Ø�5å" 4¤9°4¸dÐCÑCÔCð 	Ø�5å.¨t¬y¸tÈ$ÐOÑOÔOÐOr?   Úreturnr   c                óX   — |                       ¦   «         }t          | j        ||¬¦  «        S )zConvert to Operator©Ú
input_dimsr3   )r   r   r   )r;   r   s     r>   r"   zDensityMatrix.to_operatorÑ   s&   € à�yŠy‰{Œ{ˆÝ˜œ	¨dÀÐEÑEÔEÐEr?   c                óv   — t          t          j        | j        ¦  «        |                      ¦   «         ¬¦  «        S )z+Return the conjugate of the density matrix.©r   )r   r,   r6   r   r   rV   s    r>   Ú	conjugatezDensityMatrix.conjugateÖ   s)   € å�RœW T¤YÑ/Ô/°d·i²i±k´kÐBÑBÔBÐBr?   c                ó4   — t          j        | j        ¦  «        S )z'Return the trace of the density matrix.)r,   rh   r   rV   s    r>   rh   zDensityMatrix.traceÚ   s   € åŒx˜œ	Ñ"Ô"Ð"r?   c                ód   — t          j        t          j        | j        | j        ¦  «        ¦  «        S )z'Return the purity of the quantum state.)r,   rh   Údotr   rV   s    r>   ÚpurityzDensityMatrix.purityÞ   s$   € õ Œx�œ˜tœy¨$¬)Ñ4Ô4Ñ5Ô5Ð5r?   rJ   c                ó  — t          |t          ¦  «        st          |¦  «        }t          j        | ¦  «        }t	          j        | j        |j        ¦  «        |_        | j                             |j        ¦  «        |_        |S )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,   Úkronr0   rR   Útensor©r;   rJ   Úrets      r>   rx   zDensityMatrix.tensoræ   sg   € õ ˜%¥Ñ/Ô/ð 	)Ý! %Ñ(Ô(ˆEÝŒj˜ÑÔˆÝ”G˜DœJ¨¬Ñ4Ô4ˆŒ	Øœ×-Ò-¨e¬oÑ>Ô>ˆŒØˆ
r?   c                ó  — t          |t          ¦  «        st          |¦  «        }t          j        | ¦  «        }t	          j        |j        | j        ¦  «        |_        | j                             |j        ¦  «        |_        |S )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   rv   rA   r,   rw   r0   rR   Úexpandry   s      r>   r|   zDensityMatrix.expandù   sg   € õ ˜%¥Ñ/Ô/ð 	)Ý! %Ñ(Ô(ˆEÝŒj˜ÑÔˆÝ”G˜EœK¨¬Ñ4Ô4ˆŒ	Øœ×-Ò-¨e¬oÑ>Ô>ˆŒØˆ
r?   c                óÜ   — t          |t          ¦  «        st          |¦  «        }| j                             |j        ¦  «         t	          j        | ¦  «        }| j        |j        z   |_        |S )aT  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   rR   Ú_validate_addrv   rA   r   r0   ry   s      r>   Ú_addzDensityMatrix._add  s_   € õ ˜%¥Ñ/Ô/ð 	)Ý! %Ñ(Ô(ˆEØŒ×$Ò$ U¤_Ñ5Ô5Ð5ÝŒj˜ÑÔˆØ”I ¤
Ñ*ˆŒ	Øˆ
r?   c                ó”   — t          |t          ¦  «        st          d¦  «        ‚t          j        | ¦  «        }|| j        z  |_        |S )a   Return 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	   rv   rA   r   r0   ry   s      r>   Ú	_multiplyzDensityMatrix._multiply   sG   € õ ˜%¥Ñ(Ô(ð 	7ÝÐ5Ñ6Ô6Ð6ÝŒj˜ÑÔˆØ˜DœIÑ%ˆŒ	Øˆ
r?   úLOperator | QuantumChannel | circuit.instruction.Instruction | QuantumCircuitÚqargsúlist[int] | Nonec                ó   — |€t          |dd¦  «        }t          |t          t          f¦  «        r|                      ||¬¦  «        S t          |d¦  «        r)|                     ¦   «                              | |¬¦  «        S t          |t          ¦  «        r|                     | |¬¦  «        S t          |t          ¦  «        s(|  
                    |¬¦  «        }t          |||¬¦  «        }|                      ||¬¦  «        S )aš  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.
        Nrƒ   ©rƒ   Úto_quantumchannelrl   )Úgetattrr*   r   r   Ú_evolve_instructionr2   r‡   Ú_evolver   r   r   Ú_evolve_operator)r;   rJ   rƒ   r   s       r>   ÚevolvezDensityMatrix.evolve2  s  € ð$ ˆ=Ý˜E 7¨DÑ1Ô1ˆEõ �e�n­kÐ:Ñ;Ô;ð 	@Ø×+Ò+¨E¸Ð+Ñ?Ô?Ð?õ
 �5Ð-Ñ.Ô.ð 	HØ×*Ò*Ñ,Ô,×4Ò4°TÀÐ4ÑGÔGÐGÝ�e�^Ñ,Ô,ð 	4Ø—=’= ¨U�=Ñ3Ô3Ð3õ ˜%¥Ñ*Ô*ð 	GØ—9’9 5�9Ñ)Ô)ˆDÝ˜U¨tÀÐFÑFÔFˆEØ×$Ò$ U°%Ð$Ñ8Ô8Ð8r?   c                ó°  ‡— t          j        | ¦  «        }t          t          | j        j        dz
  dd¦  «        ¦  «        Š‰t          ˆfd„‰D ¦   «         ¦  «        z   Št          j        t          j        t          j        | j	        | j        j
        ¦  «        ‰¦  «        | j        j        ¦  «        |_        | j                             ¦   «         |_        |S )a·  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  ó<   •K  — | ]}t          ‰¦  «        |z   V — Œd S ©N)rP   )Ú.0ÚiÚaxess     €r>   ú	<genexpr>z.DensityMatrix.reverse_qargs.<locals>.<genexpr>g  s-   øè è € Ð8Ð8¨a�C ™IœI¨™MÐ8Ð8Ð8Ð8Ð8Ð8r?   )rv   rA   ÚtupleÚrangerR   Ú_num_qargs_lr,   r7   Ú	transposer   Útensor_shaper&   r0   Úreverse)r;   rz   r“   s     @r>   Úreverse_qargszDensityMatrix.reverse_qargsY  s·   ø€ õ Œj˜ÑÔˆÝ•U˜4œ>Ô6¸Ñ:¸BÀÑCÔCÑDÔDˆØ•eÐ8Ð8Ð8Ð8°4Ð8Ñ8Ô8Ñ8Ô8Ñ8ˆÝ”JÝŒL�œ D¤I¨t¬~Ô/JÑKÔKÈTÑRÔRØŒNÔ ñ
ô 
ˆŒ	ð œ×.Ò.Ñ0Ô0ˆŒØˆ
r?   c           	     ó`  — t          |¦  «        }|€t          j        |¦  «        }nt          j        |¦  «        }t          j        d|z  |j        ¦  «        }t          j        d|z  |j        ¦  «        }|j        r
d|j        z  nd}||z   dk    r||                      ¦   «         z  S t          j	        | j
        d¬¦  «        }|dk    r|t          || j        |¦  «        z  S ||j                 d         }	d|                     ¦   «         z  }
|
d         }
|t          || j        |||
|	¦  «        z  S )a  Compute 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.
        Nr%   y       €      ð¿r   ÚF)ÚorderrŽ   )rP   r,   ÚarangerB   rs   ÚxÚzÚphaserh   Úravelr   r   Ú
num_qubitsÚ_count_yr   )r;   Úpaulirƒ   Ún_pauliÚqubitsÚx_maskÚz_maskÚpauli_phaser   Úx_maxÚy_phases              r>   Ú_expectation_value_pauliz&DensityMatrix._expectation_value_paulio  s*  € õ �e‘*”*ˆØˆ=Ý”Y˜wÑ'Ô'ˆFˆFå”X˜e‘_”_ˆFÝ”˜˜V™ U¤WÑ-Ô-ˆÝ”˜˜V™ U¤WÑ-Ô-ˆØ.3¬kÐ@�s˜uœ{Ñ*Ð*¸qˆà�F‰?˜aÒÐØ §¢¡¤Ñ-Ð-åŒx˜œ	¨Ð-Ñ-Ô-ˆØ�QŠ;ˆ;ØÕ!:¸4ÀÄÐRXÑ!YÔ!YÑYÐYà�u”w” Ô#ˆØ˜5Ÿ>š>Ñ+Ô+Ñ+ˆØ˜!”*ˆØÕ8Ø�$”/ 6¨6°7¸Eñ
ô 
ñ 
ð 	
r?   ÚoperúNone | list[int]r/   c                óÌ  ‡ ‡— t          |t          ¦  «        r‰                      |‰¦  «        S t          |t          ¦  «        rDt	          ˆˆ fd„t          |j        j        |j        j        |j	        ¦  «        D ¦   «         ¦  «        S t          |t          ¦  «        st          |¦  «        }t          j        t          ‰ ¦  «                             |‰¬¦  «        j        ¦  «        S )a  Compute 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  óp   •K  — | ]0\  }}}|‰                      t          ||f¦  «        ‰¦  «        z  V — Œ1d S r�   )r®   r   )r‘   r¡   r    Úcoeffrƒ   r;   s       €€r>   r”   z2DensityMatrix.expectation_value.<locals>.<genexpr>ž  s\   øè è € ð ð á�A�q˜%ð ˜×5Ò5µe¸QÀ¸F±m´mÀUÑKÔKÑKðð ð ð ð ð r?   r†   )r*   r   r®   r   ÚsumÚzipÚpaulisr¡   r    Úcoeffsr   r,   rh   rs   r   )r;   r¯   rƒ   s   ` `r>   Úexpectation_valuezDensityMatrix.expectation_value�  sÞ   øø€ õ �d�EÑ"Ô"ð 	>Ø×0Ò0°°uÑ=Ô=Ð=å�d�MÑ*Ô*ð 	Ýð ð ð ð ð å#& t¤{¤}°d´k´mÀTÄ[Ñ#QÔ#Qðñ ô ñ ô ð õ
 ˜$¥Ñ)Ô)ð 	"Ý˜D‘>”>ˆDÝŒx� ™œ×*Ò*¨4°uÐ*Ñ=Ô=ÔBÑCÔCÐCr?   Údecimalsú
None | intú
np.ndarrayc                ó  — |                       t          j        | j                             ¦   «         ¦  «        | j                             ¦   «         |¬¦  «        }t          j        |dd¬¦  «        }|�|                     |¬¦  «        }|S )aK	  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|`.

            .. code-block::

                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

            .. code-block::

                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_maxN)r¹   )	Ú_subsystem_probabilitiesr,   Úabsr   ÚdiagonalrR   r'   ÚclipÚround)r;   rƒ   r¹   Úprobss       r>   ÚprobabilitieszDensityMatrix.probabilities§  s‚   € ðL ×-Ò-ÝŒF�4”9×%Ò%Ñ'Ô'Ñ(Ô(¨$¬.×*?Ò*?Ñ*AÔ*AÈð .ñ 
ô 
ˆõ
 ”˜ Q¨aÐ0Ñ0Ô0ˆàÐØ—K’K¨�KÑ2Ô2ˆEàˆr?   c                óž  — |€Gt          j        | ¦  «        }t          j        | j        j        t          ¬¦  «        }d|d<   ||_        |S |                      |¦  «        }t          t          |d¬¦  «        ¦  «        }t          t          |¦  «        ¦  «        j                             ¦   «         |j        d<   |                      ||¬¦  «        S )ax  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.
        Nr    r%   ©r   r   r   )r³   r†   )rv   rA   r,   ÚzerosrR   r&   r/   r0   r   r   r   r   r   r£   rŒ   )r;   rƒ   rz   Ústater   Úreset_superops         r>   ÚresetzDensityMatrix.resetù  s³   € ð" ˆ=å”*˜TÑ"Ô"ˆCÝ”H˜Tœ^Ô1½ÐAÑAÔAˆEØˆE�$‰KØˆCŒIØˆJð �yŠy˜ÑÔˆÝ¥¨°QÐ 7Ñ 7Ô 7Ñ8Ô8ˆÝ (­°$©¬Ñ 8Ô 8Ô =× CÒ CÑ EÔ EˆÔ˜1ÑØ�{Š{˜=°ˆ{Ñ6Ô6Ð6r?   Úlabelra   c                óD   — t          t          j        |¦  «        ¦  «        S )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)ÚclsrÌ   s     r>   rÎ   zDensityMatrix.from_label  s   € õD �[Ô3°EÑ:Ô:Ñ;Ô;Ð;r?   r’   Úintúint | tuple | listc                ó”   — t          j        |¦  «        }t          j        ||ft          ¬¦  «        }d|| | f<   t	          ||¬¦  «        S )a¬  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      ð?ro   )r,   ÚprodrÈ   r/   r   )r’   r   ÚsizerÉ   s       r>   Úfrom_intzDensityMatrix.from_int<  sI   € õ. Œw�t‰}Œ}ˆÝ”˜$ ˜­WÐ5Ñ5Ô5ˆØˆˆa�ˆd‰Ý˜U¨Ð.Ñ.Ô.Ð.r?   Úinstructionú0circuit.instruction.Instruction | QuantumCircuitc                ó  — t          |t          ¦  «        r|                     ¦   «         }|j        }t	          j        d|z  d|z  ft          ¬¦  «        }d|d<   t          ||dz  ¬¦  «        }|                     |¦  «         |S )a1  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$   ro   )	r*   r   Úto_instructionr¤   r,   rÈ   r/   r   Ú_append_instruction)rÏ   rÖ   r¤   ÚinitÚvecs        r>   r1   zDensityMatrix.from_instructionX  s‰   € õ* �k¥>Ñ2Ô2ð 	7Ø%×4Ò4Ñ6Ô6ˆKà Ô+ˆ
ÝŒx˜˜J™¨¨:©Ð6½gÐFÑFÔFˆØˆˆT‰
Ý˜D z°DÑ'8Ð9Ñ9Ô9ˆØ×Ò Ñ,Ô,Ð,Øˆ
r?   Údictc                ól   — |                       | j        | j                             ¦   «         |d¬¦  «        S )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|`

            .. code-block::

                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

            .. code-block::

                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.

            .. code-block::

                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_dictr   rR   r'   )r;   r¹   s     r>   Úto_dictzDensityMatrix.to_dictw  s<   € ðX ×#Ò#ØŒI�t”~×,Ò,Ñ.Ô.¸ÐQUð $ñ 
ô 
ð 	
r?   c                ó^  ‡— | j                              |j         |¬¦  «        }|j        |_        |j        |_        t          j        | ¦  «        }|€Y|j        }t          j
        || j        ¦  «         
                    |j                             ¦   «         ¦  «        |_        ||_         |S t          j        | j        | j         j        ¦  «        }t!          |                      ¦   «         ¦  «        Šˆfd„|D ¦   «         }t          j        |j        |j         j        ¦  «        }t%          j        |||¦  «        }|                     ¦   «         }	t          j        |	j        |	j         j        ¦  «        }
t%          j        ||
|‰d¦  «        }t          j        ||j        ¦  «        |_        ||_         |S )z$Evolve density matrix by an operatorr†   Nc                ó    •— g | ]
}‰d z
  |z
  ‘ŒS )r%   © )r‘   ÚqubitÚnum_indicess     €r>   ú
<listcomp>z2DensityMatrix._evolve_operator.<locals>.<listcomp>Ú  s"   ø€ Ð>Ð>Ð>¨u�; ‘? UÑ*Ð>Ð>Ð>r?   T)rR   ÚcomposeÚ_dims_lÚ_dims_rr—   Ú_num_qargs_rrv   rA   r   r,   rs   ÚTr6   r0   r7   r™   rP   r   r   Ú_einsum_matmulÚadjointr&   )r;   rJ   rƒ   Ú	new_shaperz   Úop_matrx   ÚindicesÚmatÚadjÚmat_adjræ   s              @r>   r‹   zDensityMatrix._evolve_operatorÇ  s^  ø€ ð ”N×*Ò*¨5¬?À%Ð*ÑHÔHˆ	Ø%Ô-ˆ	ÔØ!*Ô!7ˆ	ÔåŒj˜ÑÔˆØˆ=à”ZˆFÝœ˜v t¤yÑ1Ô1×5Ò5°f´h·m²m±o´oÑFÔFˆCŒIØ%ˆCŒMØˆJõ ”˜DœI t¤~Ô'BÑCÔCˆå˜$Ÿ)š)™+œ+Ñ&Ô&ˆØ>Ð>Ð>Ð>¸Ð>Ñ>Ô>ˆåŒj˜œ U¤_Ô%AÑBÔBˆÝÔ(¨°°gÑ>Ô>ˆà�mŠm‰oŒoˆÝ”*˜SœX s¤}Ô'AÑBÔBˆÝÔ(¨°¸'À;ÐPTÑUÔUˆå”J˜v y¤Ñ7Ô7ˆŒ	Ø!ˆŒØˆ
r?   c                óš  ‡‡	— ddl m} ddlm} t	          j        |¦  «        }|�0|                      t	          |¦  «        ‰¬¦  «        j        | _        dS t          ||¦  «        r!|  
                    ‰¦  «        j        | _        dS t          ||¦  «        rdS t          j        |¦  «        }|�#|                     | ‰¬¦  «        j        | _        dS |j        €t          d|j        › �¦  «        ‚t          |j        t"          ¦  «        s,t          |j        › dt%          |j        ¦  «        › d�¦  «        ‚d	„ t'          |j        j        ¦  «        D ¦   «         Š	|j        D ]k}|j        rt          d
|j        j        › �¦  «        ‚‰€ˆ	fd„|j        D ¦   «         }nˆˆ	fd„|j        D ¦   «         }|                      |j        |¬¦  «         ŒldS )z:Update the current Statevector by applying an instruction.r   )ÚReset)ÚBarrierNr†   zCannot apply Instruction: z instruction definition is z; expected QuantumCircuitc                ó   — i | ]\  }}||“Œ	S rä   rä   )r‘   ÚidxÚbits      r>   ú
<dictcomp>z5DensityMatrix._append_instruction.<locals>.<dictcomp>	  s   € ÐUÐUÐU¡h c¨3˜˜cÐUÐUÐUr?   z.Cannot apply instruction with classical bits: c                ó    •— g | ]
}‰|         ‘ŒS rä   rä   )r‘   ÚtupÚqubit_indicess     €r>   rç   z5DensityMatrix._append_instruction.<locals>.<listcomp>  s   ø€ ÐNÐNÐN°C˜]¨3Ô/ÐNÐNÐNr?   c                ó,   •— g | ]}‰‰|                  ‘ŒS rä   rä   )r‘   rý   rƒ   rþ   s     €€r>   rç   z5DensityMatrix._append_instruction.<locals>.<listcomp>  s#   ø€ ÐUÐUÐU¸3˜U =°Ô#5Ô6ÐUÐUÐUr?   )Úqiskit.circuit.resetrö   Úqiskit.circuit.barrierr÷   r   Ú_instruction_to_matrixr‹   r   r0   r*   rË   r   Ú_instruction_to_superoprŠ   Ú
definitionr	   Únamer   ÚtypeÚ	enumerater¨   ÚclbitsÚ	operationrÚ   )
r;   rJ   rƒ   rö   r÷   rò   ÚchanrÖ   Ú	new_qargsrþ   s
     `      @r>   rÚ   z!DensityMatrix._append_instructionç  s/  øø€ à.Ð.Ð.Ð.Ð.Ð.Ø2Ð2Ð2Ð2Ð2Ð2õ Ô-¨eÑ4Ô4ˆØˆ?Ø×.Ò.­x¸©}¬}ÀEÐ.ÑJÔJÔOˆDŒJØˆFõ �e˜UÑ#Ô#ð 	ØŸš EÑ*Ô*Ô0ˆDŒJØˆFÝ�e˜WÑ%Ô%ð 	ØˆFõ Ô.¨uÑ5Ô5ˆØÐàŸš d°%˜Ñ8Ô8Ô=ˆDŒJØˆFð ÔÐ#ÝÐG¸5¼:ÐGÐGÑHÔHÐHÝ˜%Ô*­NÑ;Ô;ð 	ÝØ”:ð ,ð ,½$¸uÔ?OÑ:PÔ:Pð ,ð ,ð ,ñô ð ð VÐUµ)¸EÔ<LÔ<SÑ2TÔ2TÐUÑUÔUˆØ Ô+ð 
	Mð 
	MˆKØÔ!ð Ý!ØaÀ[ÔEZÔE_ÐaÐañô ð ð ˆ}ØNÐNÐNÐN¸;Ô;MÐNÑNÔN�	�	àUÐUÐUÐUÐUÀ+ÔBTÐUÑUÔU�	Ø×$Ò$ [Ô%:À)Ð$ÑLÔLÐLÐLð
	Mð 
	Mr?   c                ó®   — t          |t          ¦  «        r|                     ¦   «         }t          j        | ¦  «        }|                     ||¬¦  «         |S )z4Return a new statevector by applying an instruction.r†   )r*   r   rÙ   rv   rA   rÚ   )r;   Úobjrƒ   rÜ   s       r>   r‰   z!DensityMatrix._evolve_instruction  sR   € å�c�>Ñ*Ô*ð 	'Ø×$Ò$Ñ&Ô&ˆCÝŒj˜ÑÔˆØ×Ò ¨5ÐÑ1Ô1Ð1Øˆ
r?   rG   úfloat | NonerF   r   c                óÌ  — |€| j         }|€| j        }t          | j        ||¬¦  «        st	          d¦  «        ‚t
          j                             | j        ¦  «        \  }}|t          |¦  «        |k             }t          |¦  «        dk    st          j
        |d         d||¬¦  «        st	          d¦  «        ‚|dd…t          j        |¦  «        f         }t          |¦  «        S )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)rG   rF   z+Not a valid density matrix (non-hermitian).r%   r   z"Density matrix is not a pure state)rG   rF   r   r0   r	   r,   ÚlinalgÚeigrÀ   rP   ÚiscloseÚargmaxr   )r;   rG   rF   ÚevalsÚevecsÚnonzero_evalsÚpsis          r>   Úto_statevectorzDensityMatrix.to_statevector  sÞ   € ð ˆ<Ø”9ˆDØˆ<Ø”9ˆDå" 4¤:°D¸tÐDÑDÔDð 	MÝÐKÑLÔLÐLå”y—}’} T¤ZÑ0Ô0‰ˆˆuà�c %™jœj¨4Ò/Ô0ˆÝˆ}ÑÔ Ò"Ð"­"¬*°]À1Ô5EÀqÈtÐZ^Ð*_Ñ*_Ô*_Ð"ÝÐBÑCÔCÐCà�A�A�A•r”y Ñ'Ô'Ð'Ô(ˆÝ˜3ÑÔÐr?   ú	list[int]c                ó8  — | j                              | j        j        ¦  «        }t	          | j                             ¦   «         ¦  «        dz
  t          j        |¦  «        z
  }t	          |                      ¦   «         ¦  «        }t          t          d|z  ¦  «        ¦  «        }|D ]}|||z            ||         c||<   |||z   <   Œ t          j        ||¦  «        }t          j        || j        j        ¦  «        }t          ||                      ¦   «         ¬¦  «        S )zÔReturn partially transposed density matrix.

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

        Returns:
            DensityMatrix: The partially transposed density matrix.
        r%   r$   ro   )r0   r7   rR   r™   rP   r'   r,   rB   r   r+   r–   r˜   r&   r   )r;   rƒ   ÚarrÚnÚlstr’   Úrhos          r>   Úpartial_transposezDensityMatrix.partial_transpose>  sî   € ð Œj× Ò  ¤Ô!<Ñ=Ô=ˆÝ�D”N×)Ò)Ñ+Ô+Ñ,Ô,¨qÑ0µ2´8¸E±?´?ÑBˆÝ�—	’	‘”ÑÔˆÝ•5˜˜Q™‘<”<Ñ Ô ˆØð 	4ð 	4ˆAØ!$ Q¨¡U¤¨S°¬VÐˆC�‰F�C˜˜A™‘J�JÝŒl˜3 Ñ$Ô$ˆÝŒj˜˜dœnÔ2Ñ3Ô3ˆÝ˜S t§y¢y¡{¤{Ð3Ñ3Ô3Ð3r?   r�   )r   r   r   r   )rX   rY   )NN)rj   r   )rJ   r   rj   r   )rJ   r‚   rƒ   r„   rj   r   )rj   r   )r¯   r   rƒ   r°   rj   r/   )rƒ   r°   r¹   rº   rj   r»   )rƒ   r„   rj   r   )rÌ   ra   rj   r   )r’   rÐ   r   rÑ   rj   r   )rÖ   r×   rj   r   )r¹   rº   rj   rÝ   )rG   r  rF   r  rj   r   )rƒ   r  rj   r   )*Ú__name__Ú
__module__Ú__qualname__Ú__doc__r9   r   ÚCOPY_ONLY_IF_NEEDEDrC   rH   rT   ÚpropertyrW   r^   re   r   ri   r"   rp   rh   rt   rx   r|   r   r�   rŒ   r›   r®   r¸   rÅ   rË   ÚclassmethodrÎ   ÚstaticmethodrÕ   r1   rá   r‹   rÚ   r‰   r  r  Ú__classcell__)r=   s   @r>   r   r   .   sD  ø€ € € € € ØÐð
 +/ðAbð Abð Abð Abð Abð Abð AbðF #¨Ô)Jð ;ð ;ð ;ð ;ð
ð 
ð 
ð 
ð 
ð

ð 
ð 
ð ðDð Dñ „XðDð(@ð (@ð (@ð (@ð (@ðTð ð ð ðð ñ „XððPð Pð Pð PðFð Fð Fð Fð
Cð Cð Cð#ð #ð #ð6ð 6ð 6ðð ð ð ð&ð ð ð ð&ð ð ð(ð ð ð* #'ð%9ð %9ð %9ð %9ð %9ðNð ð ð ð,
ð 
ð 
ð 
ðBDð Dð Dð Dð Dð0 FJðPð Pð Pð Pð Pðd7ð 7ð 7ð 7ð 7ð> ð!<ð !<ð !<ñ „[ð!<ðF ð/ð /ð /ñ „\ð/ð6 ðð ð ñ „[ðð<N
ð N
ð N
ð N
ð N
ð`ð ð ð ð@-Mð -Mð -Mð -Mð^ð ð ð ð ð  ð  ð  ð  ð@4ð 4ð 4ð 4ð 4ð 4ð 4ð 4r?   r   ).r#  Ú
__future__r   rA   rv   Ú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?   r>   ú<module>r<     så  ððð ð #Ð "Ð "Ð "Ð "Ð "Ø Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø  Ð  Ð  Ð  Ð  Ð  à Ð Ð Ð à  Ð  Ð  Ð  Ð  Ð  Ø 8Ð 8Ð 8Ð 8Ð 8Ð 8Ø 2Ð 2Ð 2Ð 2Ð 2Ð 2Ø )Ð )Ð )Ð )Ð )Ð )Ø AÐ AÐ AÐ AÐ AÐ AØ KÐ KÐ KÐ KÐ KÐ KØ :Ð :Ð :Ð :Ð :Ð :Ø ;Ð ;Ð ;Ð ;Ð ;Ð ;Ø IÐ IÐ IÐ IÐ IÐ IÐ IÐ IØ <Ð <Ð <Ð <Ð <Ð <Ø HÐ HÐ HÐ HÐ HÐ HØ TÐ TÐ TÐ TÐ TÐ TØ PÐ PÐ PÐ PÐ PÐ PØ AÐ AÐ AÐ AÐ AÐ Aà bÐ bÐ bÐ bÐ bÐ bÐ bÐ bØ >Ð >Ð >Ð >Ð >Ð >àð ØÐÐÐÐÐða4ð a4ð a4ð a4ð a4�L /ñ a4ô a4ð a4ð a4ð a4r?   