o
    jg(                     @   s   d 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 ddlmZ ddlmZ ddlmZ ddlmZ g dZdd ZG dd deZG dd deZG dd deZdd ZdddZ dS )a
  Grover's algorithm and helper functions.

Todo:

* W gate construction (or perhaps -W gate based on Mermin's book)
* Generalize the algorithm for an unknown function that returns 1 on multiple
  qubit states, not just one.
* Implement _represent_ZGate in OracleGate
    )pi)sympify)Atom)floor)sqrt)eye)NegativeOne)qapply)QuantumErrorComplexSpace)UnitaryOperator)GateIntQubit)
OracleGateWGatesuperposition_basisgrover_iterationapply_groverc                    s0   dt d   t fddtd D S )a  Creates an equal superposition of the computational basis.

    Parameters
    ==========

    nqubits : int
        The number of qubits.

    Returns
    =======

    state : Qubit
        An equal superposition of the computational basis with nqubits.

    Examples
    ========

    Create an equal superposition of 2 qubits::

        >>> from sympy.physics.quantum.grover import superposition_basis
        >>> superposition_basis(2)
        |0>/2 + |1>/2 + |2>/2 + |3>/2
          c                 3   s     | ]} t |d  V  qdS )nqubitsNr   ).0nampr    T/var/www/html/zoom/venv/lib/python3.10/site-packages/sympy/physics/quantum/grover.py	<genexpr><   s    z&superposition_basis.<locals>.<genexpr>)r   sumranger   r   r   r   r   "   s    r   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	OracleGateFunctionz2Wrapper for python functions used in `OracleGate`sc                 C   s(   t |s
td| t| }||_|S )NzCallable expected, got: %r)callable	TypeErrorr   __new__function)clsr'   objr   r   r   r&   A   s
   
zOracleGateFunction.__new__c                 C   s   t | | jfS N)typer'   selfr   r   r   _hashable_contentH   s   z$OracleGateFunction._hashable_contentc                 G   s
   | j | S r*   )r'   )r-   argsr   r   r   __call__K   s   
zOracleGateFunction.__call__N)__name__
__module____qualname____doc__r&   r.   r0   r   r   r   r   r#   >   s
    r#   c                   @   sX   e Zd ZdZdZdZedd Zedd Ze	dd Z
e	d	d
 Zdd Zdd ZdS )r   a_  A black box gate.

    The gate marks the desired qubits of an unknown function by flipping
    the sign of the qubits.  The unknown function returns true when it
    finds its desired qubits and false otherwise.

    Parameters
    ==========

    qubits : int
        Number of qubits.

    oracle : callable
        A callable function that returns a boolean on a computational basis.

    Examples
    ========

    Apply an Oracle gate that flips the sign of ``|2>`` on different qubits::

        >>> from sympy.physics.quantum.qubit import IntQubit
        >>> from sympy.physics.quantum.qapply import qapply
        >>> from sympy.physics.quantum.grover import OracleGate
        >>> f = lambda qubits: qubits == IntQubit(2)
        >>> v = OracleGate(2, f)
        >>> qapply(v*IntQubit(2))
        -|2>
        >>> qapply(v*IntQubit(3))
        |3>
    Vc                 C   sh   t |dkr
td|d f}t|}|d js!td|d  |d }t|ts.t|}|d |fS )Nr   zhInsufficient/excessive arguments to Oracle.  Please supply the number of qubits and an unknown function.r   Integer expected, got: %rr   )lenr
   r   
_eval_args
is_Integerr%   
isinstancer#   )r(   r/   sub_argsr'   r   r   r   r8   v   s   



zOracleGate._eval_argsc                 C   s   t d|d  S )z1This returns the smallest possible Hilbert space.r   r   r   r(   r/   r   r   r   _eval_hilbert_space   s   zOracleGate._eval_hilbert_spacec                 C   s
   | j d S )z=The unknown function that helps find the sought after qubits.r   )labelr,   r   r   r   search_function   s   
zOracleGate.search_functionc                 C   s   t tt| jd S )zA tuple of target qubits.r   )r   tupler"   r/   r,   r   r   r   targets   s   zOracleGate.targetsc                 K   s4   |j | j krtd| j |j f | |r| S |S )a
  Apply this operator to a Qubit subclass.

        Parameters
        ==========

        qubits : Qubit
            The qubit subclass to apply this operator to.

        Returns
        =======

        state : Expr
            The resulting quantum state.
        z)OracleGate operates on %r qubits, got: %r)r   r
   r?   )r-   qubitsoptionsr   r   r   _apply_operator_Qubit   s   

z OracleGate._apply_operator_Qubitc                 K   sF   d| j  }t|}t|D ]}| t|| j dr t |||f< q|S )zF
        Represent the OracleGate in the computational basis.
        r   r   )r   r   r"   r?   r   r   )r-   basisrC   nbasismatrixOracleir   r   r   _represent_ZGate   s   
zOracleGate._represent_ZGateN)r1   r2   r3   r4   	gate_namegate_name_latexclassmethodr8   r=   propertyr?   rA   rD   rI   r   r   r   r   r   O   s    



r   c                   @   s8   e Zd ZdZdZdZedd Zedd Z	dd Z
d	S )
r   a  General n qubit W Gate in Grover's algorithm.

    The gate performs the operation ``2|phi><phi| - 1`` on some qubits.
    ``|phi> = (tensor product of n Hadamards)*(|0> with n qubits)``

    Parameters
    ==========

    nqubits : int
        The number of qubits to operate on

    Wc                 C   s<   t |dkr
tdt|}|d jstd|d  |S )Nr   z^Insufficient/excessive arguments to W gate.  Please supply the number of qubits to operate on.r   r6   )r7   r
   r   r8   r9   r%   r<   r   r   r   r8      s   

zWGate._eval_argsc                 C   s   t ttt| jd S )Nr   )r   r@   reversedr"   r/   r,   r   r   r   rA      s   zWGate.targetsc                 K   sH   |j | j krtd| j |j f t| j }dtd| j   | }|| S )zn
        qubits: a set of qubits (Qubit)
        Returns: quantum object (quantum expression - QExpr)
        z$WGate operates on %r qubits, got: %rr   )r   r
   r   r   )r-   rB   rC   basis_stateschange_to_basisr   r   r   rD      s   

	zWGate._apply_operator_QubitN)r1   r2   r3   r4   rJ   rK   rL   r8   rM   rA   rD   r   r   r   r   r      s    

r   c                 C   s   t |j}|| |  S )a  Applies one application of the Oracle and W Gate, WV.

    Parameters
    ==========

    qstate : Qubit
        A superposition of qubits.
    oracle : OracleGate
        The black box operator that flips the sign of the desired basis qubits.

    Returns
    =======

    Qubit : The qubits after applying the Oracle and W gate.

    Examples
    ========

    Perform one iteration of grover's algorithm to see a phase change::

        >>> from sympy.physics.quantum.qapply import qapply
        >>> from sympy.physics.quantum.qubit import IntQubit
        >>> from sympy.physics.quantum.grover import OracleGate
        >>> from sympy.physics.quantum.grover import superposition_basis
        >>> from sympy.physics.quantum.grover import grover_iteration
        >>> numqubits = 2
        >>> basis_states = superposition_basis(numqubits)
        >>> f = lambda qubits: qubits == IntQubit(2)
        >>> v = OracleGate(numqubits, f)
        >>> qapply(grover_iteration(basis_states, v))
        |2>

    )r   r   )qstateoraclewgater   r   r   r     s   
"r   Nc                 C   sj   |dkr
t d| |du rttd| td  }t|| }t|}t|D ]}t||}t|}q'|S )a  Applies grover's algorithm.

    Parameters
    ==========

    oracle : callable
        The unknown callable function that returns true when applied to the
        desired qubits and false otherwise.

    Returns
    =======

    state : Expr
        The resulting state after Grover's algorithm has been iterated.

    Examples
    ========

    Apply grover's algorithm to an even superposition of 2 qubits::

        >>> from sympy.physics.quantum.qapply import qapply
        >>> from sympy.physics.quantum.qubit import IntQubit
        >>> from sympy.physics.quantum.grover import apply_grover
        >>> f = lambda qubits: qubits == IntQubit(2)
        >>> qapply(apply_grover(f, 2))
        |2>

    r   z8Grover's algorithm needs nqubits > 0, received %r qubitsNr      )	r
   r   r   r   r   r   r"   r   r	   )rS   r   
iterationsviteratediterr   r   r   r   .  s   


r   r*   )!r4   sympy.core.numbersr   sympy.core.sympifyr   sympy.core.basicr   #sympy.functions.elementary.integersr   (sympy.functions.elementary.miscellaneousr   sympy.matrices.denser   r   sympy.physics.quantum.qapplyr	   sympy.physics.quantum.qexprr
   sympy.physics.quantum.hilbertr   sympy.physics.quantum.operatorr   sympy.physics.quantum.gater   sympy.physics.quantum.qubitr   __all__r   r#   r   r   r   r   r   r   r   r   <module>   s*    
	|=&