
    z	i	                       S r SSKJr  SSKrSSK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Jr  SSKJrJr  SSKJ r   SSK!J"r"  SSK#J$r$J%r%  \
(       a  SSKJ&r&   " S S\\5      r'g)z"
Statevector quantum state class.
    )annotationsN)Number)TYPE_CHECKING)_numpy_compat)QuantumCircuit)Instruction)QiskitError)QuantumState)TolerancesMixin)OperatorBaseOperator)PauliSparsePauliOp)OpShape)matrix_equal)expval_pauli_no_xexpval_pauli_with_x)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)S j5       rS'S*S	 jjrS
 rS+S jrS rS r\S,S j5       rS-S.S jjrS/S jrS0S jrS1S jrS1S jrS2S jrS3S jrS2S jrS rS r S'     S4S jjr S-       S5S jjrS0S jrS'S jr  S'     S6S jjr! S-     S7S jjr"S'S8S jjr#\$S9S  j5       r%\&S:S! j5       r'\$S;S" j5       r(S'S<S# jjr)\&S'S$ j5       r*\&S'S% j5       r+S&r,U =r-$ )=Statevector-   zStatevector classNc                  > [        U[        [        R                  45      (       a  [        R                  " U[
        S9U l        O[        U[        5      (       a+  UR                  U l        Uc  UR                  R                  nO[        U[        5      (       aE  UR                  u  p4US:w  a  [        S5      e[        R                  " UR                  5      U l        OK[        U[        [         45      (       a%  [        R#                  U5      R                  U l        O[        S5      eU R                  R$                  nU R                  R&                  nUS:w  ai  US:X  aI  US   S:X  a@  [        R(                  " U R                  US   5      U l        U R                  R&                  nOUS:w  d	  US   S:w  a  [        S5      e[*        TU ]Y  [.        R0                  " XbSS	9S
9  g)aA  Initialize a statevector object.

Args:
    data: Data from which the statevector can be constructed. This can be either a complex
        vector, another statevector, a ``Operator`` with only one column or a
        ``QuantumCircuit`` or ``Instruction``.  If the data is a circuit or instruction,
        the statevector is constructed by assuming that all qubits are initialized to 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 length of the input vector
      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.
dtypeN   z&Input Operator is not a column-vector.z)Invalid input data format for Statevector   r   z-Invalid input: not a vector or column-vector.)shapedims_lnum_qubits_r)op_shape)
isinstancelistnpndarrayasarraycomplex_datar   	_op_shape_dims_lr   dimr	   raveldatar   r   from_instructionndimr   reshapesuper__init__r   auto)selfr,   dims	input_dim_r.   r   	__class__s          `/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/quantum_info/states/statevector.pyr1   Statevector.__init__0   sj   L dT2::.// D8DJk**DJ|~~--h''88LIA~!"JKK$)),DJ~{;<<$55d;@@DJIJJ zz

  19qyU1X]ZZ

E!H=


((eAh!m!"QRR',,UVW"XY    c                v    Uc  U R                   R                  OUn[        R                  " U R                   XS9$ )N)r   copy)r,   r   r#   array)r3   r   r<   s      r8   	__array__Statevector.__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)r0   __eq__r#   allcloser'   rB   rC   )r3   otherr7   s     r8   rD   Statevector.__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Statevector( z, )	separatorprefixz,
zdims=))lenr#   array2stringr'   r(   r   )r3   rK   pads      r8   __repr__Statevector.__repr__}   sZ    &kChrtzzT&QRRUVYUZDNN))+,A/	
r:   c                P    U R                   U R                  R                  5       S.$ )zReturn settings.)r,   r4   )r'   r(   r   r3   s    r8   settingsStatevector.settings   s      

DNN,A,A,CDDr:   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 statevector using `plot_state_qsphere()`.

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

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

**city**: Matplotlib figure, rendering of statevector using `plot_state_city()`.

**paulivec**: Matplotlib figure, rendering of statevector using `plot_state_paulivec()`.

Args:
    output (str): Select the output method to use for drawing the
        state. Valid choices are `repr`, `text`, `latex`, `latex_source`,
        `qsphere`, `hinton`, `bloch`, `city`, or `paulivec`. 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.

Examples:

    Plot one of the Bell states

    .. plot::
       :alt: Output from the previous code.
       :include-source:

        from numpy import sqrt
        from qiskit.quantum_info import Statevector
        sv=Statevector([1/sqrt(2), 0, 0, -1/sqrt(2)])
        sv.draw(output='hinton')

r   )state_draweroutput)(qiskit.visualization.state_visualizationrW   )r3   rX   drawer_argsrW   s       r8   drawStatevector.draw   s    p 	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)r[   r!   strprintIPython.displayr^   )r3   outr^   s      r8   _ipython_display_Statevector._ipython_display_   s+    iikc3#J/CLr:   c                `   [        U[        5      (       a   [        US5      n[        U[        5      (       aO  XR
                  :  a  [	        SU SU R
                   S35      eUS:  a  [	        SU S	35      eU R                  U   $ [	        S
5      e! [         a    [	        SU S35      Sef = f)zReturn Statevector item either by index or binary label
Args:
    key (int or str): index or corresponding binary label, e.g. '01' = 1.

Returns:
    numpy.complex128: Statevector item.

Raises:
    QiskitError: if key is not valid.
r   zKey 'z' is not a valid binary string.NzKey z' is greater than Statevector dimension .r   z is not a valid positive value.z)Key must be int or a valid binary string.)r!   r_   int
ValueErrorr	   r*   r'   )r3   keys     r8   __getitem__Statevector.__getitem__   s     c3Z#qk c3hh!D-TUYU]U]T^^_"`aaQw!D-L"MNN::c?"IJJ  Z!E#.M"NOUYYZs   B B-c              #  8   #    U R                    S h  vN   g  N7fNr'   rS   s    r8   __iter__Statevector.__iter__   s     ::s   c                ,    [        U R                  5      $ rm   )rM   r'   rS   s    r8   __len__Statevector.__len__   s    4::r:   c                    U R                   $ )zReturn data.rn   rS   s    r8   r,   Statevector.data   s     zzr:   c                    Uc  U R                   nUc  U R                  n[        R                  R	                  U R
                  5      n[        R                  " USX!S9$ )z(Return True if a Statevector has norm 1.r   rA   )rC   rB   r#   linalgnormr,   rE   )r3   rC   rB   rx   s       r8   is_validStatevector.is_valid   sG    <99D<99Dyy~~dii({{499r:   c                    [         R                  " U R                  [         R                  " U R                  5      5      n[	        XR                  5       U R                  5       S9$ )z,Convert state to a rank-1 projector operator
input_dimsoutput_dims)r#   outerr,   conjr   r4   )r3   mats     r8   to_operatorStatevector.to_operator   s<    hhtyy"''$))"45		MMr:   c                n    [        [        R                  " U R                  5      U R	                  5       S9$ )z%Return the conjugate of the operator.r4   )r   r#   r   r,   r4   rS   s    r8   	conjugateStatevector.conjugate  s"    277499-DIIK@@r:   c                p    [         R                  " [         R                  " U R                  5      S-  5      $ )z:Return the trace of the quantum state as a density matrix.r   )r#   sumabsr,   rS   s    r8   traceStatevector.trace  s#    vvbffTYY'1,--r:   c                (    U R                  5       S-  $ )z'Return the purity of the quantum state.r   )r   rS   s    r8   purityStatevector.purity	  s     zz|q  r:   c                &   [        U[        5      (       d  [        U5      n[        R                  " U 5      nU R                  R                  UR                  5      Ul        [        R                  " U R                  UR                  5      Ul        U$ )u   Return the tensor product state self ⊗ other.

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

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

Raises:
    QiskitError: if other is not a quantum state.
)	r!   r   _copyr<   r(   tensorr#   kronr'   r3   rF   rets      r8   r   Statevector.tensor  sb     %--&Ejj--eoo>GGDJJ4	
r:   c                <   [        U[        5      (       d  [        U5      nU R                  5       UR                  5       :w  a.  [        SU R                  5        SUR                  5        S35      e[        R
                  " U R                  UR                  5      nU$ )aH  Return the inner product of self and other as
:math:`\langle self| other \rangle`.

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

Returns:
    np.complex128: the inner product of self and other, :math:`\langle self| other \rangle`.

Raises:
    QiskitError: if other is not a quantum state or has different dimension.
z%Statevector dimensions do not match: z and rf   )r!   r   r4   r	   r#   vdotr,   )r3   rF   inners      r8   r   Statevector.inner$  sz     %--&E99;%**,&7		}E%**,WXY  		5::.r:   c                &   [        U[        5      (       d  [        U5      n[        R                  " U 5      nU R                  R                  UR                  5      Ul        [        R                  " UR                  U R                  5      Ul        U$ )u   Return the tensor product state other ⊗ self.

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

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

Raises:
    QiskitError: if other is not a quantum state.
)	r!   r   r   r<   r(   expandr#   r   r'   r   s      r8   r   Statevector.expand:  sb     %--&Ejj--eoo>GGEKK4	
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 (Statevector): a quantum state object.

Returns:
    Statevector: the linear combination self + other.

Raises:
    QiskitError: if other is not a quantum state, or has
                 incompatible dimensions.
)r!   r   r(   _validate_addr   r<   r,   r'   r   s      r8   _addStatevector._addM  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 self * other.

Args:
    other (complex): a complex number.

Returns:
    Statevector: 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   r<   r,   r'   r   s      r8   	_multiplyStatevector._multiplya  s>     %((566jjII%	
r:   c                   Uc  [        USS5      n[        R                  " U 5      n[        U[        5      (       a  UR                  5       n[        U[        5      (       a(  U R                  c  [        S5      eU R                  X1US9$ [        U[        5      (       d  U R                  US9n[        XUS9nU R                  U5      UR                  5       :w  a  [        S5      e[        R                  X1US9$ )a  Evolve a quantum state by the operator.

Args:
    other (Operator | QuantumCircuit | circuit.Instruction): The operator to evolve by.
    qargs (list): a list of Statevector subsystem positions to apply
                   the operator on.

Returns:
    Statevector: the output quantum state.

Raises:
    QiskitError: if the operator dimension does not match the
                 specified Statevector subsystem dimensions.
Nqargsz5Cannot apply QuantumCircuit to non-qubit Statevector.r   r|   zLOperator input dimensions are not equal to statevector subsystem dimensions.)getattrr   r<   r!   r   to_instructionr   
num_qubitsr	   _evolve_instructionr   r4   r}   r   _evolve_operator)r3   rF   r   r   r4   s        r8   evolveStatevector.evolves  s    " =E7D1E jj e^,,((*Ee[))&!"YZZ++Ce+DD %**9959)DUFE 99Uu//11^  ++Ce+DDr:   c                   [        U[        5      (       d   [        U5      nU R                  UR                  :w  a  gUc  U R                  nUc  U R
                  n[        U R                  UR                  SX#S9$ ! [         a     gf = f)a5  Return True if other is equivalent as a statevector up to global phase.

.. note::

    If other is not a Statevector, but can be used to initialize a statevector object,
    this will check that Statevector(other) is equivalent to the current statevector up
    to global phase.

Args:
    other (Statevector): an object from which a ``Statevector`` can be constructed.
    rtol (float): relative tolerance value for comparison.
    atol (float): absolute tolerance value for comparison.

Returns:
    bool: True if statevectors are equivalent up to global phase.
FT)ignore_phaserB   rC   )r!   r   r	   r*   rC   rB   r   r,   )r3   rF   rB   rC   s       r8   equivStatevector.equiv  s~    & %--#E* 88uyy <99D<99DDIIuzz4[[  s   A; ;
BBc                   [         R                  " U 5      n[        [        U R                  R
                  S-
  SS5      5      n[        R                  " [        R                  " [        R                  " U R                  U R                  R                  5      U5      U R                  R                  5      Ul        U R                  R                  5       Ul        U$ )a  Return a Statevector with reversed subsystem ordering.

For a tensor product state this is equivalent to reversing the order
of tensor product subsystems. For a statevector
:math:`|\psi \rangle = |\psi_{n-1} \rangle \otimes ... \otimes |\psi_0 \rangle`
the returned statevector will be
:math:`|\psi_{0} \rangle \otimes ... \otimes |\psi_{n-1} \rangle`.

Returns:
    Statevector: the Statevector with reversed subsystem order.
r   )r   r<   tupleranger(   _num_qargs_lr#   r/   	transposer,   tensor_shaper   r'   reverse)r3   r   axess      r8   reverse_qargsStatevector.reverse_qargs  s     jjU4>>66:BCD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/  U[        R                  R                  U R                  5      S-  -  $ US:X  a$  U[        U R                  U R                  U5      -  $ XAR
                     S   nSUR                  5       -  n	U	S   n	U[        U R                  U R                  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   r   r   )rM   r#   aranger=   dotxzphaserw   rx   r,   r   r   _count_yr   )
r3   paulir   n_pauliqubitsx_maskz_maskpauli_phasex_maxy_phases
             r8   _expectation_value_pauli$Statevector._expectation_value_pauli  s    e*=YYw'FXXe_FVUWW-VUWW-.3kksu{{*q?a		!:a!???Q;!2499doov!VVVww#5>>++!*0IIt
 
 	
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      $ T R                  UTS9nT R                  5       n[        R                  " UR                  UR                  5      $ )zCompute the expectation value of an operator.

Args:
    oper (Operator): an operator to evaluate expval of.
    qargs (None or list): subsystems to apply 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rm   )r   r   ).0r   r   coeffr   r3   s       r8   	<genexpr>0Statevector.expectation_value.<locals>.<genexpr>  s4      #QKA% 55eQFmUKK#Qs   /2r   )r!   r   r   r   r   zippaulisr   r   coeffsr   r   r#   r   r,   )r3   operr   valr   s   ` `  r8   expectation_valueStatevector.expectation_value  s     dE""00u==dM** #&t{{}}dkkmmT[[#Q  
 kk$ek,~~vvdii**r:   c                    U R                  [        R                  " U R                  5      S-  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:`|\psi\rangle=|+\rangle\otimes|0\rangle`.

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

        from qiskit.quantum_info import Statevector

        psi = Statevector.from_label('+0')

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

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

        # Probabilities for measuring only qubit-1
        probs_qubit_1 = psi.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 Statevector

        psi = Statevector.from_label('+0')

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

        # Probabilities for measuring both qubits
        # but swapping qubits 0 and 1 in output
        probs_swapped = psi.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   r   )a_mina_max)decimals)_subsystem_probabilitiesr#   r   r,   r(   r   clipround)r3   r   r   probss       r8   probabilitiesStatevector.probabilities  so    T --FF499"DNN$9$9$;5 . 

 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 R                  U5      nU R                  R                  [        U5      USS9n[        R                  " [        U5      [        S9nS[        R                  " XV   5      -  Xv'   [        R                  " [        U5      5      nSUS'   SXU4'   SUSU4'   [        R                  " U[        R                   " U5      5      nU R#                  [%        XUS9US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:
    Statevector: 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 a measurement on those subsystems and
    evolve the subsystems so that the collapsed post-measurement
    states are rotated to the 0-state. The RNG seed for this
    sampling can be set using the :meth:`seed` method.
r   r   r   )psize)r   r   r|   r   )r   r<   r#   zerosr(   r   r&   r'   r4   r   _rngchoicerM   sqrteyer   diagr   r   )	r3   r   r   stater4   r   sampleprojresets	            r8   r   Statevector.resetd  s   & =**T"CHHT^^11AEE!HIJ yy""5)!!#e*A!> xxE
'22775=11 s5z"d !fnai ubggdm,{{8EMUZ{[[r:   c                
   [         R                  " SU5      c  [        S5      eUnSn[         R                  " SU5      cJ  SnUR                  SS5      nUR                  SS5      nUR                  S	S
5      nUR                  SS
5      n[	        U5      n[
        R                  " SU-  [        S9n[        US5      nSXV'   [        U5      nU(       a  [
        R                  " SS/SS//[        S9[        R                  " S5      -  n[
        R                  " [
        R                  " SS/5      U5      n	[        [!        U5      5       H5  u  pUS;   a  UR#                  X/S9nM  US;   d  M%  UR#                  X/S9nM7     U$ )a3  Return a tensor product of Pauli X,Y,Z eigenstates.

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

   * - Label
     - Statevector
   * - ``"0"``
     - :math:`[1, 0]`
   * - ``"1"``
     - :math:`[0, 1]`
   * - ``"+"``
     - :math:`[1 / \sqrt{2},  1 / \sqrt{2}]`
   * - ``"-"``
     - :math:`[1 / \sqrt{2},  -1 / \sqrt{2}]`
   * - ``"r"``
     - :math:`[1 / \sqrt{2},  i / \sqrt{2}]`
   * - ``"l"``
     - :math:`[1 / \sqrt{2},  -i / \sqrt{2}]`

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

Returns:
    Statevector: 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.
z^[01rl\-+]+$z"Label contains invalid characters.Fz^[01]+$T+0r-1lr   r   r   r                 ?)r   r   r   )r   r   )rematchr	   replacerM   r#   r   r&   rg   r   r=   mathr   r   r   	enumeratereversedr   )clslabelz_label	xy_statesr   r,   posr   x_maty_matqubitchars               r8   
from_labelStatevector.from_label  sY   F 88OU+3BCC
 	88Iu%- Iooc3/Gooc3/Gooc3/Gooc3/GZ
xxZw7'1o	D!HHq!fq"g.g>1MEFF277Ar7+U3E(%9:%!LLgL>EZ'!LLgL>E	  :
 r:   c                z    [         R                  " U5      n[         R                  " U[        S9nSX0'   [	        X1S9$ )a  Return a computational basis statevector.

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

Returns:
    Statevector: The computational basis state :math:`|i\rangle`.

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         ?r   )r#   prodr   r&   r   )ir4   r   r   s       r8   from_intStatevector.from_int  s3    . wwt}W-5,,r:   c                    [        U[        5      (       a  UR                  5       n[        R                  " SUR
                  -  [        S9nSUS'   [        X!R
                  S-  S9n[        R                  X15      $ )a  Return the output statevector 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 (qiskit.circuit.Instruction or QuantumCircuit): instruction or circuit

Returns:
    Statevector: The final statevector.

Raises:
    QiskitError: if the instruction contains invalid instructions for
                 the statevector simulation.
r   r   r  r   r   r   )	r!   r   r   r#   r   r   r&   r   r   )r  instructioninitvecs       r8   r-   Statevector.from_instruction  si    & k>22%446Kxx;111AQ$%;%;d%BC..s@@r:   c                j    U R                  U R                  U R                  R                  5       USS9$ )a  Convert the statevector 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 Statevector.

Example:

    The ket-form of a 2-qubit statevector
    :math:`|\psi\rangle = |-\rangle\otimes |0\rangle`

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

        from qiskit.quantum_info import Statevector

        psi = Statevector.from_label('-0')
        print(psi.to_dict())

    .. code-block:: text

        {'00': (0.7071067811865475+0j), '10': (-0.7071067811865475+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 Statevector

        vec = np.zeros(9)
        vec[0] = 1 / np.sqrt(2)
        vec[-1] = 1 / np.sqrt(2)
        psi = Statevector(vec, dims=(3, 3))
        print(psi.to_dict())

    .. code-block:: text

        {'00': (0.7071067811865475+0j), '22': (0.7071067811865475+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 Statevector

        vec = np.zeros(2 * 10)
        vec[0] = 1 / np.sqrt(2)
        vec[-1] = 1 / np.sqrt(2)
        psi = Statevector(vec, dims=(2, 10))
        print(psi.to_dict())

    .. code-block:: text

        {'00': (0.7071067811865475+0j), '91': (0.7071067811865475+0j)}

T)r   string_labels)_vector_to_dictr,   r(   r   )r3   r   s     r8   to_dictStatevector.to_dict  s8    X ##IIt~~,,.QU $ 
 	
r:   c           	        U R                   R                  UR                   US9nUc8  [        R                  " UR                  U R                  5      U l        X0l         U $ U R                   R
                  S   n[        U5       Vs/ s H
  oTS-
  U-
  PM     nnU[        U5       Vs/ s H  oUU;  d  M
  UPM     sn-   n[        R                  " U5      R                  5       nUR                   R                  S   n	XR                   R                  S   U	-  4n
[        R                  " [        R                  " U R                  U R                   R                  5      U5      nUR                  n[        R                  " [        R                  " UR                  [        R                  " X5      5      U5      n[        R                  " [        R                  " X5      UR                  S   5      U l        X0l         U $ s  snf s  snf )zEvolve a qudit statevectorr   r   r   )r(   composer#   r   r'   	num_qargsr  r   argsorttolistr   r   r/   r,   r   )statevecr   r   	new_shaper   r  indicesr   axes_invcontract_dimcontract_shaper   r   s                r8   r   Statevector._evolve_operator^  s    &&..t~~U.K	=VVDJJ?HN!*O &&003	.6uo>oq=1$o>U9%5J%5'9I!%5JJ::d#**, ~~++A.&(:(:(@(@(C|(ST JJx}}h&8&8&E&EF
 || FF499bjj@A
 BLL$BIOOTUDVW '5 ?Js   G>'	H4Hc                   SSK Jn  SSKJn  SSKJn  [        R                  " U5      nUb  [        R                  U [        U5      US9$ [        X5      (       a"  U R                  U5      R                  U l        U $ [        X5      (       a  U $ [        X5      (       Gav  [        S UR                   5       5      (       a9  [        R                  SR!                  UR                  5      5      R                  nO[#        UR                  5      S	:X  aZ  [%        [&        R(                  " UR                  S   5      5      n[        R+                  US
UR,                  -  5      R                  nO#[&        R.                  " UR                  [0        S9nUc  Xpl        U $ U R                  U5      R                  U l        [&        R2                  " S[#        U5      -  S[#        U5      -  4[0        S9nXvSS2S4'   [        R                  U [        U5      US9n U $ UR4                  c  [7        SUR8                   35      e[        UR4                  [:        5      (       d.  [7        UR8                   S[=        UR4                  5       S35      eUR4                  R>                  (       aI  U =R                  [&        R@                  " S[C        UR4                  R>                  5      -  5      -  sl        [E        UR4                  RF                  5       V	V
s0 s H  u  pX_M	     nn	n
UR4                   H  nURH                  (       a"  [7        SURJ                  R8                   35      eUc  URF                   Vs/ s H  oU   PM	     nnO URF                   Vs/ s H	  oX      PM     nn[        RM                  XRJ                  US9  M     U $ s  sn
n	f s  snf s  snf )z:Update the current Statevector by applying an instruction.r   )Reset)Barrier)
InitializeNr   c              3  B   #    U  H  n[        U[        5      v   M     g 7frm   )r!   r_   )r   params     r8   r   2Statevector._evolve_instruction.<locals>.<genexpr>  s     Bze:eS))zs    r   r  r   r   zCannot apply Instruction: z instruction definition is z; expected QuantumCircuitr   z.Cannot apply instruction with classical bits: )'qiskit.circuit.resetr+  qiskit.circuit.barrierr,  3qiskit.circuit.library.data_preparation.initializerr-  r   _instruction_to_matrixr   r   r!   r   r'   allparamsr  joinrM   rg   r#   realr  r   r%   r&   r   
definitionr	   namer   typeglobal_phaseexpfloatr   r   clbits	operationr   )r#  objr   r+  r,  r-  r   initializationr   r  r	  r   r  tup	new_qargss                  r8   r   Statevector._evolve_instruction  s    	/2 	S--c2? //(3-u/UU c!!%^^E288HNOc##Oc&&BszzBBB!,!7!7

8K!L!R!R
 SZZA%BGGCJJqM23!,!5!5eTCNN=R!S!Y!Y "$CJJg!F}!/ O "*!6!<!<hhSZc%jAQ*AqD	&77(3-W\7]O
 >>! :388*EFF#...9988*7S^^8L7MMfg  >>&&NNbffR%0K0K*L%LMMN+4S^^5J5J+KL+Kxq%(+KL>>K!!!D[EZEZE_E_D`a  }4?4F4FG4FSC[4F	G	;F;M;MN;MC6;/;M	N++H6K6KS\+] *  M HNs   O1OOrn   rm   )r,   z]np.ndarray | list | Statevector | Operator | QuantumCircuit | circuit.instruction.Instructionr4   zint | tuple | list | None)returndict)rX   z
str | None)ri   z	int | strrG  np.complex128)rG  
np.ndarray)NN)rC   float | NonerB   rK  rG  bool)rG  r   )rG  r   )rG  z
np.float64)rF   r   rG  r   )rF   r   rG  rI  )rF   z'Operator | QuantumCircuit | Instructionr   list[int] | NonerG  r   )rF   r   rB   rK  rC   rK  rG  rL  )r   z+BaseOperator | QuantumCircuit | Instructionr   None | list[int]rG  r&   )r   rN  r   
None | intrG  rJ  )r   rM  rG  r   )r  r_   rG  r   )r  rg   r4   zint | tuple | listrG  r   )r  zInstruction | QuantumCircuitrG  r   )r   rO  rG  rH  ).__name__
__module____qualname____firstlineno____doc__r1   r   COPY_ONLY_IF_NEEDEDr>   rD   rP   propertyrT   r[   rc   rj   ro   rr   r,   ry   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   classmethodr  staticmethodr  r-   r  r   r   __static_attributes____classcell__)r7   s   @r8   r   r   -   s    +/BZ.BZ (BZ BZH #)J)J ;


 E E:@xK2  :N
A.!&,&(& Y])E<)EEU)E	)EX SW\ \(4\CO\	\@* 
F \`+?+HX+	+4 FJT%T8BT	Tl,\\ B BH - -6 A A4N
` % %N J Jr:   r   )(rT  
__future__r   r<   r   r   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.operatorr   r   (qiskit.quantum_info.operators.symplecticr   r   &qiskit.quantum_info.operators.op_shaper   (qiskit.quantum_info.operators.predicatesr   qiskit._accelerate.pauli_expvalr   r   r   r    r:   r8   <module>rk     s\    #   	       8 2 ) A K I I : A
 d, dr:   