
    z	i#7                         S r SSKJrJr  SSK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  SSKJr  SSKJr  Sr " S S\5      r " S S\5      rg)z>Prepare a quantum state from the state where all qubits are 0.    )UnionOptionalN)QiskitError)QuantumCircuit)QuantumRegister)Gate)XGate)HGate)SGateSdgGate)Isometry)CircuitError)Statevectorg|=c                      ^  \ rS rSrSr    SS\\\\\	4   S\
\   S\S\
\   S\4
U 4S jjjrS	 rS
 rS rS rS rSS\4S jjrS rS rS\SS4S jrSrU =r$ )StatePreparation#   zComplex amplitude state preparation.

Class that implements the (complex amplitude) state preparation of some
flexible collection of qubit registers.
params
num_qubitsinverselabel	normalizec                 z  > Xl         X0l        U R                  (       a  SOSU l        Uc  U R                  (       a  SOSU l        OU R                  (       a  U S3OUU l        [	        U[
        5      (       a  UR                  n[	        U[        5      (       d  Ub  [        S5      e[	        U[        5      U l
        [	        U[        5      U l        U R                  (       d  U R                  (       d{  [        R                  R                  U5      nU(       a'  [        R                  " U[        R                   S9U-  nO.["        R$                  " US	[&        S
9(       d  [        SU S35      eU R)                  X!5      n[	        U[        5      (       a  U/OUn[*        TU ]Y  U R                  X!U R                  S9  g)ai  
Args:
    params:
        * Statevector: Statevector to initialize to.
        * list: vector of complex amplitudes to initialize to.
        * string: labels of basis states of the Pauli eigenstates Z, X, Y. See
          :meth:`.Statevector.from_label`.
          Notice the order of the labels is reversed with respect to the qubit index to
          be applied to. Example label '01' initializes the qubit zero to :math:`|1\rangle`
          and the qubit one to :math:`|0\rangle`.
        * int: an integer that is used as a bitmap indicating which qubits to initialize
          to :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit 2
          to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`.
    num_qubits: This parameter is only used if params is an int. Indicates the total
        number of qubits in the `initialize` call. Example: `initialize` covers 5 qubits
        and params is 3. This allows qubits 0 and 1 to be initialized to :math:`|1\rangle`
        and the remaining 3 qubits to be initialized to :math:`|0\rangle`.
    inverse: if True, the inverse state is constructed.
    label: An optional label for the gate
    normalize (bool): Whether to normalize an input array to a unit vector.

Raises:
    QiskitError: ``num_qubits`` parameter used when ``params`` is not an integer

When a Statevector argument is passed the state is prepared based on the
:class:`~.library.Isometry` synthesis described in [1].

References:

[1] Iten et al., Quantum circuits for isometries (2016).
`Phys. Rev. A 93, 032318
<https://journals.aps.org/pra/abstract/10.1103/PhysRevA.93.032318>`__.

state_preparation_dgstate_preparationNState Preparation DgState Preparationz DgzZThe num_qubits parameter to StatePreparation should only be used when params is an integer)dtypeg      ?)abs_tolz(Sum of amplitudes-squared is not 1, but .)r   )_params_arg_inverse_name_label
isinstancer   dataintr   str_from_label	_from_intnplinalgnormarray
complex128mathisclose_EPS_get_num_qubitssuper__init__)selfr   r   r   r   r   r,   	__class__s          s/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/circuit/library/data_preparation/state_preparation.pyr4   StatePreparation.__init__*   sL   T "/3}}+BU
=48MM0GZDK+/==UG3-eDKfk**[[F&#&&:+A2  &fc2#FC0 99>>&)D&>E\\$T:!$LTFRS"TUU))*=
'44&&Zt{{K    c                     U R                   (       a  U R                  5       U l        g U R                  (       a  U R	                  5       U l        g U R                  5       U l        g )N)r(   _define_from_label
definitionr)   _define_from_int_define_synthesis_isom)r5   s    r7   _defineStatePreparation._defineu   sB    "557DO^^"335DO"99;DOr9   c                    [        U R                  S5      n[        USS9n[        [	        U R
                  5      5       GH  u  p4US:X  a  UR                  [        5       X   /5        M+  US:X  a  UR                  [        5       X   /5        MP  US:X  a<  UR                  [        5       X   /5        UR                  [        5       X   /5        M  US:X  a<  UR                  [        5       X   /5        UR                  [        5       X   /5        M  US:X  d  M  UR                  [        5       X   /5        UR                  [        5       X   /5        GM     U R                  (       a  UR                  5       nU$ )	Nqinit_defname1+-rl)r   r   r   	enumeratereversedr   appendr	   r
   r   r   r!   r   )r5   rB   initialize_circuitqubitparams        r7   r;   #StatePreparation._define_from_label}   s*   DOOS1+AJ?%ht{{&;<LE|"))%'AH:>#"))%'AH:>#"))%'AH:>"))%'AH:>#"))%'AH:>"))%'AH:>#"))%'AH:>"))')ahZ@ = ==!3!;!;!=!!r9   c                    [        U R                  S5      n[        USS9n[        [        R
                  " U R                  S   5      5      SU R                   S3 S S S2   n[        U5      U R                  :  a%  [        S[        U5       S	U R                   S
35      e[        U5       H*  u  pEUS:X  d  M  UR                  [        5       X   /5        M,     U$ )NrB   rC   rD   r   0bzStatePreparation integer has z= bits, but this exceeds the number of qubits in the circuit, r   rF   )r   r   r   r&   r*   realr   lenr   rK   rM   r	   )r5   rB   rN   intstrrO   bits         r7   r=   !StatePreparation._define_from_int   s    DOOS1+AJ? A/04??2C10DEttL v;(/F} =559__4EQH 
 $F+JEcz"))%'AH:> , "!r9   c                     [        U R                  S5      n[        USS9n[        U R                  SS5      nUR                  UR                  SSS9  U R                  SL a  UR                  5       $ U$ )zGCalculate a subcircuit that implements this initialization via isometryrB   rC   rD   r   FT)copyinplace)	r   r   r   r   r   composer<   r!   r   )r5   rB   rN   isoms       r7   r>   'StatePreparation._define_synthesis_isom   sm    DOOS1+AJ?Q*""4??"M ==D %--//!!r9   c                 b   [        U[        5      (       a  [        U5      nU$ [        U[        5      (       a'  Uc"  [        [        R
                  " U5      5      S-   nU$ [        R
                  " [        U5      5      nUS:X  d  UR                  5       (       d  [        S5      e[        U5      nU$ )z1Get number of qubits needed for state preparation   r   z5Desired statevector length not a positive power of 2.)r$   r'   rW   r&   r/   log2
is_integerr   )r5   r   r   s      r7   r2    StatePreparation._get_num_qubits   s    fc""VJ  $$! 6!23a7
  3v;/J Qj&;&;&=&=!"YZZZJr9   	annotatedc                     U R                   S;   a  SOU R                   n[        U R                  U R                  (       + US9$ )z Return inverted StatePreparation)r   r   N)r   r   )r#   r   r    r!   )r5   rf   r   s      r7   r   StatePreparation.inverse   s@     KK#PPDVZVaVa 	   0 0dmm:KSXYYr9   c           
   #      #    U VVs/ s H  o3  H  oDPM     M     nnnU R                   [        U5      :w  a5  [        SSU R                   -   SU R                    S[        U5       S35      eU/ 4v   g s  snnf 7f)Nz&StatePreparation parameter vector has    z elements, therefore expects z qubits. However, z were provided.)r   rW   r   )r5   qargscargssublistqarg
flat_qargss         r7   broadcast_arguments$StatePreparation.broadcast_arguments   s     */D%wGDdGd%
D??c*o-8DOO9K8L//@ A$$'
O#4OE 
 "n Es   A:A4AA:c                    [        U[        5      (       a-  US;   a  U$ [        S[        U5       SU R                   S35      e[        U[
        [        [        45      (       a  [        U5      $ [        U[        R                  5      (       a  [        UR                  5       5      $ [        S[        U5       SU R                   35      e)zKStatePreparation instruction parameter can be str, int, float, and complex.)rS   rF   rG   rH   rJ   rI   zinvalid param label z for instruction z&. Label should be 0, 1, +, -, l, or r zinvalid param type z for instruction  )r$   r'   r   typerE   r&   floatcomplexr*   numberitem)r5   	parameters     r7   validate_parameter#StatePreparation.validate_parameter   s     i%%::  &tI&77H T' '  i#ug!6779%%	299--9>>+,,!4T)_4EEWX\XaXaWbcddr9   exponentreturnr   c                 J    [        U R                   SU 3U R                  / S9$ )N*)rE   r   r   )r   rE   r   )r5   r{   s     r7   _return_repeatStatePreparation._return_repeat   s%    DII;az2tWYZZr9   )r)   r(   r!   r#   r"   r    r<   )NFNF)F)__name__
__module____qualname____firstlineno____doc__r   r'   listr&   r   r   boolr4   r?   r;   r=   r>   r2   r   rp   ry   rt   r   __static_attributes____classcell__r6   s   @r7   r   r   #   s     %)#ILc4k12IL SMIL 	IL
 }IL IL ILV<"0".""Z Z	e([u [ [ [r9   r   c                   L   ^  \ rS rSrSr  SS\S\\   4U 4S jjjrS rSr	U =r
$ )	UniformSuperpositionGate   a  Implements a uniform superposition state.

This gate is used to create the uniform superposition state
:math:`\frac{1}{\sqrt{M}} \sum_{j=0}^{M-1}  |j\rangle` when it acts on an input
state :math:`|0...0\rangle`. Note, that `M` is not required to be
a power of 2, in which case the uniform superposition could be
prepared by a single layer of Hadamard gates.

.. note::

    This class uses the Shukla-Vedula algorithm [1], which only needs
    :math:`O(\log_2 (M))` qubits and :math:`O(\log_2 (M))` gates,
    to prepare the superposition.

References:

[1]: A. Shukla and P. Vedula (2024), An efficient quantum algorithm for preparation
of uniform quantum superposition states, `Quantum Inf Process 23, 38
<https://link.springer.com/article/10.1007/s11128-024-04258-4>`_.
num_superpos_statesr   c                 ,  > US::  a  [        S5      eUc4  [        [        R                  " [        R                  " U5      5      5      nO:[        U[        5      (       a  U[        R                  " U5      :  d  [        S5      e[        TU ]  SX!/5        g)a  
Args:
    num_superpos_states (int):
        A positive integer M = num_superpos_states (> 1) representing the number of computational
        basis states with an amplitude of 1/sqrt(M) in the uniform superposition
        state (:math:`\frac{1}{\sqrt{M}} \sum_{j=0}^{M-1}  |j\rangle`, where
        :math:`1< M <= 2^n`). Note that the remaining (:math:`2^n - M`) computational basis
        states have zero amplitudes. Here M need not be an integer power of 2.

    num_qubits (int):
        A positive integer representing the number of qubits used.  If num_qubits is None
        or is not specified, then num_qubits is set to ceil(log2(num_superpos_states)).

Raises:
    ValueError: num_qubits must be an integer greater than or equal to log2(num_superpos_states).

rb   z>num_superpos_states must be a positive integer greater than 1.NzQnum_qubits must be an integer greater than or equal to log2(num_superpos_states).USup)
ValueErrorr&   r/   ceilrc   r$   r3   r4   )r5   r   r   r6   s      r7   r4   !UniformSuperpositionGate.__init__  s~    , !#]^^TYYtyy1D'EFGJz3//Z499M`Ca5a g  	-BCr9   c           
      j   [        U R                  5      nU R                  S   nX"S-
  -  S:X  a@  [        [        R
                  " U5      5      nUR                  [        U5      5        Xl        g [        [        R                  " U5      5       Vs/ s H  n[        U5      PM     nn[        U5      n[        U5       VVs/ s H  u  pxUS:X  d  M  UPM     n	nnUR                  U	SU 5        SU	S   -  n
S[        R                  " [        R                   " X-  5      5      -  nU	S   S:  a  UR                  [        U	S   5      5        UR#                  XS   5        UR%                  U	S   [        U	S   U	S   5      SS9  [        S[        U	5      S-
  5       H  nS[        R                  " [        R                   " SX   -  X*-
  -  5      5      -  nUR'                  XU   XS-      SS9  UR%                  XS-      [        X   XS-      5      SS9  U
SX   -  -   n
M     Xl        g s  snf s  snnf )Nr   rb   rj   rS   )
ctrl_state)r   _num_qubitsr   r&   r/   rc   hranger<   rL   r*   binary_reprrW   rK   xarccossqrtrychcry)r5   qcr   mr   n_valuekindexrw   l_valuem_current_valuethetas               r7   r?    UniformSuperpositionGate._define/  s   D,,-"kk!n  #:; DII123ADDqN O#+BNN;N,O#PQ#Pa3q6#PQL.7.@N.@]eDAI5.@N
WQq\wqz/RYYrww'LMNN1:>DDwqz"#
eQZ 
gaj%
GAJ7CHq#g,*+AWZ+>+PQR E FF5!*g!enFEEE'a%.%
GEN"CPSET-WZ?O , + RNs   H*H/H/)r<   )rj   N)r   r   r   r   r   r&   r   r4   r?   r   r   r   s   @r7   r   r      s?    . $%$(D D SMD DB# #r9   r   )r   typingr   r   r/   numpyr*   qiskit.exceptionsr   qiskit.circuit.quantumcircuitr   qiskit.circuitr   qiskit.circuit.gater   'qiskit.circuit.library.standard_gates.xr	   'qiskit.circuit.library.standard_gates.hr
   'qiskit.circuit.library.standard_gates.sr   r   (qiskit.circuit.library.generalized_gatesr   qiskit.circuit.exceptionsr   &qiskit.quantum_info.states.statevectorr   r1   r   r    r9   r7   <module>r      sZ    E "   ) 8 * $ 9 9 B = 2 R[t R[jZt Zr9   