o
    jgk                     @   s:  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 g dZedZedddgidZd0ddZd1ddZer`er`eZneZdd Zdd Zdd Zdd Zdd  Zd2d"d#Z d2d$d%Z!G d&d' d'eZ"d(d) Z#d*d+ Z$		!d3d,d-Z%d.d/ Z&dS )4    )deque)randint)import_module)BasicMul)Numberequal_valued)Pow)S)	represent)Dagger)	generate_gate_rulesgenerate_equivalent_idsGateIdentitybfs_identity_searchrandom_identity_searchis_scalar_sparse_matrixis_scalar_nonsparse_matrixis_degenerateis_reduciblenumpyscipyfromlistsparse)import_kwargsdy=c                 C   sL  t rts	 tt|  |dd}t|tr|r|dkS dS |  }t |j	| k|j	|k }t |j
| k|j
|k }t |d|j	}t |d|j
}	|	td }	||	 }
|
 d }|
 d }||k}| }|
d d }|dkrud	S |
|  }td
|}||k}t|j	d |k }t|j
|k }|o|}|r|nd}t|o|o|S )a  Checks if a given scipy.sparse matrix is a scalar matrix.

    A scalar matrix is such that B = bI, where B is the scalar
    matrix, b is some scalar multiple, and I is the identity
    matrix.  A scalar matrix would have only the element b along
    it's main diagonal and zeroes elsewhere.

    Parameters
    ==========

    circuit : Gate tuple
        Sequence of quantum gates representing a quantum circuit
    nqubits : int
        Number of qubits in the circuit
    identity_only : bool
        Check for only identity matrices
    eps : number
        The tolerance value for zeroing out elements in the matrix.
        Values in the range [-eps, +eps] will be changed to a zero.
    zscipy.sparse)nqubitsformat   Tg        y              ?r   y                F   g      ?)npr   r   r   
isinstanceinttodensegetAlogical_andrealimagwherecomplexnonzeroalltracepowabsbool)circuitr   identity_onlyepsmatrixdense_matrix	bool_real	bool_imagcorrected_realcorrected_imagcorrected_denserow_indicescol_indicesbool_indicesis_diagonalfirst_elementtrace_of_correctedexpected_tracehas_correct_tracereal_is_oneimag_is_zerois_oneis_identity rG   \/var/www/html/zoom/venv/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.pyr       sB   



r   Nc           	      C   s~   t t|  |d}t|tr|r|dkS dS | }|s!||d  n|}|r,t|d dnd}|td|k}t| o=|o=|S )a  Checks if a given circuit, in matrix form, is equivalent to
    a scalar value.

    Parameters
    ==========

    circuit : Gate tuple
        Sequence of quantum gates representing a quantum circuit
    nqubits : int
        Number of qubits in the circuit
    identity_only : bool
        Check for only identity matrices
    eps : number
        This argument is ignored. It is just for signature compatibility with
        is_scalar_sparse_matrix.

    Note: Used in situations when is_scalar_sparse_matrix has bugs
    )r   r   Tr   r    )	r   r   r"   r   r-   r	   r.   r0   r>   )	r1   r   r2   r3   r4   matrix_traceadjusted_matrix_tracerF   rB   rG   rG   rH   r   x   s   
r   c                 C   s   t | tr	| jjS | jS N)r"   r
   base
min_qubits)a_gaterG   rG   rH   _get_min_qubits   s   
rO   c                 C   sf   t | dkr| d }tt||ft|d}t | dkr1|r1| dt |  }t|f| }||fS dS )a  Perform a LL operation.

    A LL operation multiplies both left and right circuits
    with the dagger of the left circuit's leftmost gate, and
    the dagger is multiplied on the left side of both circuits.

    If a LL is possible, it returns the new gate rule as a
    2-tuple (LHS, RHS), where LHS is the left circuit and
    and RHS is the right circuit of the new rule.
    If a LL is not possible, None is returned.

    Parameters
    ==========

    left : Gate tuple
        The left circuit of a gate rule expression.
    right : Gate tuple
        The right circuit of a gate rule expression.

    Examples
    ========

    Generate a new gate rule using a LL operation:

    >>> from sympy.physics.quantum.identitysearch import ll_op
    >>> from sympy.physics.quantum.gate import X, Y, Z
    >>> x = X(0); y = Y(0); z = Z(0)
    >>> ll_op((x, y, z), ())
    ((Y(0), Z(0)), (X(0),))

    >>> ll_op((y, z), (x,))
    ((Z(0),), (Y(0), X(0)))
    r   Tr   Nlenis_scalar_matrixr   rO   )leftrightll_gatell_gate_is_unitarynew_left	new_rightrG   rG   rH   ll_op      #rY   c                 C   sr   t | dkr| t | d  }tt||ft|d}t | dkr7|r7| dt | d  }|t|f }||fS dS )a  Perform a LR operation.

    A LR operation multiplies both left and right circuits
    with the dagger of the left circuit's rightmost gate, and
    the dagger is multiplied on the right side of both circuits.

    If a LR is possible, it returns the new gate rule as a
    2-tuple (LHS, RHS), where LHS is the left circuit and
    and RHS is the right circuit of the new rule.
    If a LR is not possible, None is returned.

    Parameters
    ==========

    left : Gate tuple
        The left circuit of a gate rule expression.
    right : Gate tuple
        The right circuit of a gate rule expression.

    Examples
    ========

    Generate a new gate rule using a LR operation:

    >>> from sympy.physics.quantum.identitysearch import lr_op
    >>> from sympy.physics.quantum.gate import X, Y, Z
    >>> x = X(0); y = Y(0); z = Z(0)
    >>> lr_op((x, y, z), ())
    ((X(0), Y(0)), (Z(0),))

    >>> lr_op((x, y), (z,))
    ((X(0),), (Z(0), Y(0)))
    r   r   TNrP   )rS   rT   lr_gatelr_gate_is_unitaryrW   rX   rG   rG   rH   lr_op      #r]   c                 C   sf   t |dkr|d }tt||ft|d}t |dkr1|r1|dt | }t|f|  }||fS dS )a  Perform a RL operation.

    A RL operation multiplies both left and right circuits
    with the dagger of the right circuit's leftmost gate, and
    the dagger is multiplied on the left side of both circuits.

    If a RL is possible, it returns the new gate rule as a
    2-tuple (LHS, RHS), where LHS is the left circuit and
    and RHS is the right circuit of the new rule.
    If a RL is not possible, None is returned.

    Parameters
    ==========

    left : Gate tuple
        The left circuit of a gate rule expression.
    right : Gate tuple
        The right circuit of a gate rule expression.

    Examples
    ========

    Generate a new gate rule using a RL operation:

    >>> from sympy.physics.quantum.identitysearch import rl_op
    >>> from sympy.physics.quantum.gate import X, Y, Z
    >>> x = X(0); y = Y(0); z = Z(0)
    >>> rl_op((x,), (y, z))
    ((Y(0), X(0)), (Z(0),))

    >>> rl_op((x, y), (z,))
    ((Z(0), X(0), Y(0)), ())
    r   Tr   NrP   )rS   rT   rl_gaterl_gate_is_unitaryrX   rW   rG   rG   rH   rl_op  rZ   ra   c                 C   sr   t |dkr|t |d  }tt||ft|d}t |dkr7|r7|dt |d  }| t|f }||fS dS )a  Perform a RR operation.

    A RR operation multiplies both left and right circuits
    with the dagger of the right circuit's rightmost gate, and
    the dagger is multiplied on the right side of both circuits.

    If a RR is possible, it returns the new gate rule as a
    2-tuple (LHS, RHS), where LHS is the left circuit and
    and RHS is the right circuit of the new rule.
    If a RR is not possible, None is returned.

    Parameters
    ==========

    left : Gate tuple
        The left circuit of a gate rule expression.
    right : Gate tuple
        The right circuit of a gate rule expression.

    Examples
    ========

    Generate a new gate rule using a RR operation:

    >>> from sympy.physics.quantum.identitysearch import rr_op
    >>> from sympy.physics.quantum.gate import X, Y, Z
    >>> x = X(0); y = Y(0); z = Z(0)
    >>> rr_op((x, y), (z,))
    ((X(0), Y(0), Z(0)), ())

    >>> rr_op((x,), (y, z))
    ((X(0), Z(0)), (Y(0),))
    r   r   TNrP   )rS   rT   rr_gaterr_gate_is_unitaryrX   rW   rG   rG   rH   rr_opM  r^   rd   Fc           	         s$  t | tr|rtjtjfhS dhS t | tr| j} t t t|   fdd}	| ddf 
| df tdkru \}}}t||}||| t||}||| t||}||| t||}||| tdks@|rt }D ]}|\}}|
t| t| f q||S )am  Returns a set of gate rules.  Each gate rules is represented
    as a 2-tuple of tuples or Muls.  An empty tuple represents an arbitrary
    scalar value.

    This function uses the four operations (LL, LR, RL, RR)
    to generate the gate rules.

    A gate rule is an expression such as ABC = D or AB = CD, where
    A, B, C, and D are gates.  Each value on either side of the
    equal sign represents a circuit.  The four operations allow
    one to find a set of equivalent circuits from a gate identity.
    The letters denoting the operation tell the user what
    activities to perform on each expression.  The first letter
    indicates which side of the equal sign to focus on.  The
    second letter indicates which gate to focus on given the
    side.  Once this information is determined, the inverse
    of the gate is multiplied on both circuits to create a new
    gate rule.

    For example, given the identity, ABCD = 1, a LL operation
    means look at the left value and multiply both left sides by the
    inverse of the leftmost gate A.  If A is Hermitian, the inverse
    of A is still A.  The resulting new rule is BCD = A.

    The following is a summary of the four operations.  Assume
    that in the examples, all gates are Hermitian.

        LL : left circuit, left multiply
             ABCD = E -> AABCD = AE -> BCD = AE
        LR : left circuit, right multiply
             ABCD = E -> ABCDD = ED -> ABC = ED
        RL : right circuit, left multiply
             ABC = ED -> EABC = EED -> EABC = D
        RR : right circuit, right multiply
             AB = CD -> ABD = CDD -> ABD = C

    The number of gate rules generated is n*(n+1), where n
    is the number of gates in the sequence (unproven).

    Parameters
    ==========

    gate_seq : Gate tuple, Mul, or Number
        A variable length tuple or Mul of Gates whose product is equal to
        a scalar matrix
    return_as_muls : bool
        True to return a set of Muls; False to return a set of tuples

    Examples
    ========

    Find the gate rules of the current circuit using tuples:

    >>> from sympy.physics.quantum.identitysearch import generate_gate_rules
    >>> from sympy.physics.quantum.gate import X, Y, Z
    >>> x = X(0); y = Y(0); z = Z(0)
    >>> generate_gate_rules((x, x))
    {((X(0),), (X(0),)), ((X(0), X(0)), ())}

    >>> generate_gate_rules((x, y, z))
    {((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))),
     ((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))),
     ((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))),
     ((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)),
     ((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()),
     ((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())}

    Find the gate rules of the current circuit using Muls:

    >>> generate_gate_rules(x*x, return_as_muls=True)
    {(1, 1)}

    >>> generate_gate_rules(x*y*z, return_as_muls=True)
    {(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)),
     (1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)),
     (Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)),
     (X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1),
     (Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)),
     (Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))}
    )rG   rG   c                    sZ   | d ur)| \}}| vr||fvr |  |d  k r+| |d f  d S d S d S )Nr   )addappend)new_ruleopsrW   rX   max_opsqueuerulesrG   rH   process_new_rule  s   
z-generate_gate_rules.<locals>.process_new_rulerG   r   )r"   r   r   Oner   argsr   setrQ   rf   re   popleftrY   r]   ra   rd   )	gate_seqreturn_as_mulsrm   rS   rT   rh   rg   	mul_rulesrulerG   ri   rH   r     s<   
R
	








r   c                 C   s   t | tr	tjhS t | tr| j} t }t| }|D ]}|\}}|dkr*|| q|dkr3|| q|rAdd }tt	||}|S )a   Returns a set of equivalent gate identities.

    A gate identity is a quantum circuit such that the product
    of the gates in the circuit is equal to a scalar value.
    For example, XYZ = i, where X, Y, Z are the Pauli gates and
    i is the imaginary value, is considered a gate identity.

    This function uses the four operations (LL, LR, RL, RR)
    to generate the gate rules and, subsequently, to locate equivalent
    gate identities.

    Note that all equivalent identities are reachable in n operations
    from the starting gate identity, where n is the number of gates
    in the sequence.

    The max number of gate identities is 2n, where n is the number
    of gates in the sequence (unproven).

    Parameters
    ==========

    gate_seq : Gate tuple, Mul, or Number
        A variable length tuple or Mul of Gates whose product is equal to
        a scalar matrix.
    return_as_muls: bool
        True to return as Muls; False to return as tuples

    Examples
    ========

    Find equivalent gate identities from the current circuit with tuples:

    >>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids
    >>> from sympy.physics.quantum.gate import X, Y, Z
    >>> x = X(0); y = Y(0); z = Z(0)
    >>> generate_equivalent_ids((x, x))
    {(X(0), X(0))}

    >>> generate_equivalent_ids((x, y, z))
    {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
     (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}

    Find equivalent gate identities from the current circuit with Muls:

    >>> generate_equivalent_ids(x*x, return_as_muls=True)
    {1}

    >>> generate_equivalent_ids(x*y*z, return_as_muls=True)
    {X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0),
     Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)}
    rG   c                 S   s   t |  S rK   r   )id_seqrG   rG   rH   <lambda>Z  s    z)generate_equivalent_ids.<locals>.<lambda>)
r"   r   r   rn   r   ro   rp   r   re   map)rr   rs   eq_ids
gate_rulesru   lrconvert_to_mulrG   rG   rH   r     s"   
5

r   c                   @   sP   e Zd ZdZdd Zedd Zedd Zedd	 Zed
d Z	dd Z
dS )r   a  Wrapper class for circuits that reduce to a scalar value.

    A gate identity is a quantum circuit such that the product
    of the gates in the circuit is equal to a scalar value.
    For example, XYZ = i, where X, Y, Z are the Pauli gates and
    i is the imaginary value, is considered a gate identity.

    Parameters
    ==========

    args : Gate tuple
        A variable length tuple of Gates that form an identity.

    Examples
    ========

    Create a GateIdentity and look at its attributes:

    >>> from sympy.physics.quantum.identitysearch import GateIdentity
    >>> from sympy.physics.quantum.gate import X, Y, Z
    >>> x = X(0); y = Y(0); z = Z(0)
    >>> an_identity = GateIdentity(x, y, z)
    >>> an_identity.circuit
    X(0)*Y(0)*Z(0)

    >>> an_identity.equivalent_ids
    {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
     (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
    c                 G   s4   t j| g|R  }t| |_t||_t||_|S rK   )r   __new__r   _circuitr   _rulesr   _eq_ids)clsro   objrG   rG   rH   r~     s
   


zGateIdentity.__new__c                 C      | j S rK   )r   selfrG   rG   rH   r1        zGateIdentity.circuitc                 C   r   rK   )r   r   rG   rG   rH   rz     r   zGateIdentity.gate_rulesc                 C   r   rK   )r   r   rG   rG   rH   equivalent_ids  r   zGateIdentity.equivalent_idsc                 C   r   rK   )ro   r   rG   rG   rH   sequence  r   zGateIdentity.sequencec                 C   s
   t | jS )z'Returns the string of gates in a tuple.)strr1   r   rG   rG   rH   __str__  s   
zGateIdentity.__str__N)__name__
__module____qualname____doc__r~   propertyr1   rz   r   r   r   rG   rG   rG   rH   r   `  s    	



r   c                 C   s   | D ]
}||j v r dS qdS )a  Checks if a gate identity is a permutation of another identity.

    Parameters
    ==========

    identity_set : set
        A Python set with GateIdentity objects.
    gate_identity : GateIdentity
        The GateIdentity to check for existence in the set.

    Examples
    ========

    Check if the identity is a permutation of another identity:

    >>> from sympy.physics.quantum.identitysearch import (
    ...     GateIdentity, is_degenerate)
    >>> from sympy.physics.quantum.gate import X, Y, Z
    >>> x = X(0); y = Y(0); z = Z(0)
    >>> an_identity = GateIdentity(x, y, z)
    >>> id_set = {an_identity}
    >>> another_id = (y, z, x)
    >>> is_degenerate(id_set, another_id)
    True

    >>> another_id = (x, x)
    >>> is_degenerate(id_set, another_id)
    False
    TF)r   )identity_setgate_identityan_idrG   rG   rH   r     s
   !
r   c                 C   s@   d}t t||D ]}| | }|f| }t||dr dS q	dS )a  Determines if a circuit is reducible by checking
    if its subcircuits are scalar values.

    Parameters
    ==========

    circuit : Gate tuple
        A tuple of Gates representing a circuit.  The circuit to check
        if a gate identity is contained in a subcircuit.
    nqubits : int
        The number of qubits the circuit operates on.
    begin : int
        The leftmost gate in the circuit to include in a subcircuit.
    end : int
        The rightmost gate in the circuit to include in a subcircuit.

    Examples
    ========

    Check if the circuit can be reduced:

    >>> from sympy.physics.quantum.identitysearch import is_reducible
    >>> from sympy.physics.quantum.gate import X, Y, Z
    >>> x = X(0); y = Y(0); z = Z(0)
    >>> is_reducible((x, y, z), 1, 0, 3)
    True

    Check if an interval in the circuit can be reduced:

    >>> is_reducible((x, y, z), 1, 1, 3)
    False

    >>> is_reducible((x, y, y), 1, 1, 3)
    True
    rG   FT)reversedrangerR   )r1   r   beginendcurrent_circuitndx	next_gaterG   rG   rH   r     s   %
r   c                 C   s   |du s|dkrt | }|}tdg}t }t |dkr[| }| D ]2}||f }	t|	|dt |	}
t|	||rGt||	sG|
sG|t|	  q"t |	|k rT|
sT|	|	 q"t |dks|S )aA  Constructs a set of gate identities from the list of possible gates.

    Performs a breadth first search over the space of gate identities.
    This allows the finding of the shortest gate identities first.

    Parameters
    ==========

    gate_list : list, Gate
        A list of Gates from which to search for gate identities.
    nqubits : int
        The number of qubits the quantum circuit operates on.
    max_depth : int
        The longest quantum circuit to construct from gate_list.
    identity_only : bool
        True to search for gate identities that reduce to identity;
        False to search for gate identities that reduce to a scalar.

    Examples
    ========

    Find a list of gate identities:

    >>> from sympy.physics.quantum.identitysearch import bfs_identity_search
    >>> from sympy.physics.quantum.gate import X, Y, Z
    >>> x = X(0); y = Y(0); z = Z(0)
    >>> bfs_identity_search([x], 1, max_depth=2)
    {GateIdentity(X(0), X(0))}

    >>> bfs_identity_search([x, y, z], 1)
    {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
     GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))}

    Find a list of identities that only equal to 1:

    >>> bfs_identity_search([x, y, z], 1, identity_only=True)
    {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
     GateIdentity(Z(0), Z(0))}
    Nr   rG   r   )
rQ   r   rp   rq   r   rR   r   re   r   rf   )	gate_listr   	max_depthr2   id_onlyrk   idsr   r   new_circuitcircuit_reduciblerG   rG   rH   r     s2   *


r   c                 C   sN   t | }d}t|D ]}| td|d  }||f }q
t||d}|r%|S dS )zRandomly selects numgates from gate_list and checks if it is
    a gate identity.

    If the circuit is a gate identity, the circuit is returned;
    Otherwise, None is returned.
    rG   r   r   FN)rQ   r   r   rR   )r   numgatesr   	gate_sizer1   ir   	is_scalarrG   rG   rH   r   D  s   r   )r   rK   )F)NF)'collectionsr   sympy.core.randomr   sympy.externalr   sympy.core.basicr   sympy.core.mulr   sympy.core.numbersr   r	   sympy.core.powerr
   sympy.core.singletonr   sympy.physics.quantum.representr   sympy.physics.quantum.daggerr   __all__r!   r   r   r   rR   rO   rY   r]   ra   rd   r   r   r   r   r   r   r   rG   rG   rG   rH   <module>   sB    

X/333
3 
O='2
N