o
    jg\                     @   s  d 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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%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0 g dZ1da2dd Z3dd Z4dd Z5d d! Z6G d"d# d#e%Z7G d$d% d%e7Z8G d&d' d'e8Z9G d(d) d)e7Z:G d*d+ d+e7Z;G d,d- d-e7Z<G d.d/ d/e;Z=G d0d1 d1e'e;Z>G d2d3 d3e'e;Z?G d4d5 d5e'e;Z@G d6d7 d7e'e;ZAG d8d9 d9e;ZBG d:d; d;e;ZCe>ZDe?ZEe@ZFeAZGeCZHeB ZIZG d<d= d=e'e8e<ZJG d>d? d?e<ZKeJZLeKZMd@dA ZNdOdCdDZOdEdF ZPdGdH ZQeEeFeGeeHeDeLeMffdIdJZRdOdKdLZSdOdMdNZTdS )Pa  An implementation of gates that act on qubits.

Gates are unitary operators that act on the space of qubits.

Medium Term Todo:

* Optimize Gate._apply_operators_Qubit to remove the creation of many
  intermediate Qubit objects.
* Add commutation relationships to all operators and use this in gate_sort.
* Fix gate_sort and gate_simp.
* Get multi-target UGates plotting properly.
* Get UGate to work with either sympy/numpy matrices and output either
  format. This should also use the matrix slots.
    )chainN)Add)Tuple)Mul)IInteger)Pow)Number)S)default_sort_key)_sympify)sqrt)
prettyForm
stringPict)AntiCommutator)
Commutator)QuantumError)ComplexSpace)UnitaryOperatorOperatorHermitianOperator)matrix_tensor_product
matrix_eye)matrix_cache)
MatrixBase)is_sequence)GateCGateUGateOneQubitGateTwoQubitGateIdentityGateHadamardGateXGateYGateZGateTGate	PhaseGateSwapGateCNotGateCNOTSWAPHXYZTr
   Phase
normalized	gate_sort	gate_simprandom_circuitCPHASECGateSTc                  O      d|vrt |d< t| i |S Nkey)r   maxargskwargs r?   R/var/www/html/zoom/venv/lib/python3.10/site-packages/sympy/physics/quantum/gate.py_maxT      rA   c                  O   r8   r9   )r   minr<   r?   r?   r@   _minZ   rB   rD   c                 C   s   | a dS )a  Set flag controlling normalization of Hadamard gates by `1/\sqrt{2}`.

    This is a global setting that can be used to simplify the look of various
    expressions, by leaving off the leading `1/\sqrt{2}` of the Hadamard gate.

    Parameters
    ----------
    normalize : bool
        Should the Hadamard gate include the `1/\sqrt{2}` normalization factor?
        When True, the Hadamard gate will have the `1/\sqrt{2}`. When False, the
        Hadamard gate will not have this factor.
    N)_normalized)	normalizer?   r?   r@   r2   `   s   r2   c                 C   sN   t | } | D ]}|js|jstd| |  qtt| t| kr%tdd S )NzInteger expected, got: %rz4Target/control qubits in a gate cannot be duplicated)list
is_Integer	is_Symbol	TypeErrorlensetr   )tandcbitr?   r?   r@   _validate_targets_controlsq   s   rO   c                   @   s   e Zd 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e
dd Ze
dd Zd$ddZdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#S )%r   a8  Non-controlled unitary gate operator that acts on qubits.

    This is a general abstract gate that needs to be subclassed to do anything
    useful.

    Parameters
    ----------
    label : tuple, int
        A list of the target qubits (as ints) that the gate will apply to.

    Examples
    ========


    ,Gc                 C   s   t t| }t| |S N)r   r   
_eval_argsrO   clsr=   r?   r?   r@   rS      s   zGate._eval_argsc                 C      t dt|d  S 1This returns the smallest possible Hilbert space.      r   rA   rT   r?   r?   r@   _eval_hilbert_space      zGate._eval_hilbert_spacec                 C   s
   t | jS zThe total number of qubits this gate acts on.

        For controlled gate subclasses this includes both target and control
        qubits, so that, for examples the CNOT gate acts on 2 qubits.
        )rK   targetsselfr?   r?   r@   nqubits   s   
zGate.nqubitsc                 C      t | jd S z7The minimum number of qubits this gate needs to act on.rZ   )rA   r_   r`   r?   r?   r@   
min_qubits      zGate.min_qubitsc                 C   s   | j S A tuple of target qubits.labelr`   r?   r?   r@   r_      s   zGate.targetsc                 C   s
   d| j  S )Nz$%s$)gate_name_latexr`   r?   r?   r@   gate_name_plot   s   
zGate.gate_name_plotsympyc                 C      t d)zThe matrix representation of the target part of the gate.

        Parameters
        ----------
        format : str
            The format string ('sympy','numpy', etc.)
        z-get_target_matrix is not implemented in Gate.NotImplementedErrorra   formatr?   r?   r@   get_target_matrix   s   zGate.get_target_matrixc                 K      | j |fi |S )z(Redirect an apply from IntQubit to Qubit)_apply_operator_Qubitra   qubitsoptionsr?   r?   r@   _apply_operator_IntQubit      zGate._apply_operator_IntQubitc                 K   s   |j | jk rtd| j|j f t| tr| |s|S | j}| jdd}d}d}|D ]}||||  7 }|d> }q+|ddt|f }d}	t	|j
D ](}
|j|j }t|D ]\}}|| |
|? d@ krj||}qW|	||
 | 7 }	qK|	S )zApply this gate to a Qubit.4Gate needs a minimum of %r qubits to act on, got: %rrm   rr   r   rZ   N)rb   re   r   
isinstancer   eval_controlsr_   rs   intrangerows	__class__r=   	enumerateflip)ra   rw   rx   r_   target_matrixcolumn_indexntargetcolumnresultindex	new_qubitrN   r?   r?   r@   ru      s4   




zGate._apply_operator_Qubitc                 K   s   | j di |S )NrR   )_represent_ZGate)ra   rx   r?   r?   r@   _represent_default_basis  s   zGate._represent_default_basisc           	      K   sx   | dd}| dd}|dkrtd|| jk rtd| | |}| j}t| tr0| j}ng }t|||||}|S )Nrr   rm   rb   r   z.The number of qubits must be given as nqubits.z2The number of qubits %r is too small for the gate.)	getr   re   rs   r_   r}   r   controlsrepresent_zbasis)	ra   basisrx   rr   rb   r   r_   r   mr?   r?   r@   r     s&   



zGate._represent_ZGatec                 G       | j |g|R  }d| j|f S )Nz%s(%s))_print_label	gate_namera   printerr=   rj   r?   r?   r@   	_sympystr#     zGate._sympystrc                 G   s(   t | j}| j|g|R  }| ||S rR   )r   r   _print_label_pretty_print_subscript_pretty)ra   r   r=   abr?   r?   r@   _pretty'  s   
zGate._prettyc                 G   r   )N%s_{%s})r   rk   r   r?   r?   r@   _latex,  r   zGate._latexc                 C   rn   )Nzplot_gate is not implemented.ro   )ra   axesgate_idx	gate_grid	wire_gridr?   r?   r@   	plot_gate0  s   zGate.plot_gateNrm   )__name__
__module____qualname____doc___label_separatorr   rk   classmethodrS   r\   propertyrb   re   r_   rl   rs   ry   ru   r   r   r   r   r   r   r?   r?   r?   r@   r   ~   s4    






/r   c                   @   s   e Zd ZdZdZdZejZdZ	e
dd Ze
dd Zedd	 Zed
d Zedd Zedd Zedd Zd(ddZdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'S ))r   a  A general unitary gate with control qubits.

    A general control gate applies a target gate to a set of targets if all
    of the control qubits have a particular values (set by
    ``CGate.control_value``).

    Parameters
    ----------
    label : tuple
        The label in this case has the form (controls, gate), where controls
        is a tuple/list of control qubits (as ints) and gate is a ``Gate``
        instance that is the target operator.

    Examples
    ========

    CFc                 C   sD   |d }|d }t |s|f}t|}tt||j t| |fS )Nr   rZ   )r   r   rS   rO   r   r_   r   )rU   r=   r   gater?   r?   r@   rS   S  s   
zCGate._eval_argsc                 C   s$   t dtt|d d |d j S rX   rY   r   rZ   )r   rA   re   rT   r?   r?   r@   r\   ^  s   $zCGate._eval_hilbert_spacec                 C   s   t | jt | j S r^   )rK   r_   r   r`   r?   r?   r@   rb   g  s   zCGate.nqubitsc                 C   s   t t | jt | jd S rd   )rA   r   r_   r`   r?   r?   r@   re   p  s   zCGate.min_qubitsc                 C   s   | j jS rg   )r   r_   r`   r?   r?   r@   r_   u  s   zCGate.targetsc                 C      t | jd S zA tuple of control qubits.r   tuplerj   r`   r?   r?   r@   r   z  rf   zCGate.controlsc                 C   
   | j d S z<The non-controlled gate that will be applied to the targets.rZ   ri   r`   r?   r?   r@   r     s   
z
CGate.gaterm   c                 C   s   | j |S rR   )r   rs   rq   r?   r?   r@   rs        zCGate.get_target_matrixc                    s   t  fddjD S )z<Return True/False to indicate if the controls are satisfied.c                 3   s    | ]
} | j kV  qd S rR   )control_value).0rN   qubitra   r?   r@   	<genexpr>  s    z&CGate.eval_controls.<locals>.<genexpr>)allr   )ra   r   r?   r   r@   r~     s   zCGate.eval_controlsc                 K   s   t | jdkrL| jd }| jjd }t| jtr1t|}t||}t|}t|}|| | | S t| jtrJt	|}t||}t	|}|| | S dS | S )z@Decompose the controlled gate into CNOT and single qubits gates.rZ   r   N)
rK   r   r   r_   r}   r$   r'   r)   r%   r"   )ra   rx   ctg1g2g3g4r?   r?   r@   	decompose  s    


zCGate.decomposec                 G   s8   | j | jd|g|R  }|j| jg|R  }d||f S )NrP   z(%s),%s)_print_sequencer   _printr   ra   r   r=   r   r   r?   r?   r@   r     s   zCGate._print_labelc                 G   sV   | j | jd|g|R  }|| j}t| j}| ||}| |}t|	| }|S NrP   )
_print_sequence_prettyr   r   r   r   r   r   _print_parens_prettyr   right)ra   r   r=   r   r   r   firstfinalr?   r?   r@   r     s   

zCGate._prettyc                 G   s<   | j | jd|g|R  }|j| jg|R  }d| j||f S )NrP   z%s_{%s}{\left(%s\right)})r   r   r   r   rk   r   r?   r?   r@   r     s
   
zCGate._latexc                 C   s   t tt| j| j}t tt| j| j}|||| | jD ]
}||t | q | jrW| j	j
dkr=| j	|| dS | j	j
dkrN||| jd  dS | j	|| dS | j	|| dS )z
        Plot the controlled gate. If *simplify_cgate* is true, simplify
        C-X and C-Z gates into their more familiar forms.
        r-   r/   r   N)r   rD   r   r   r_   rA   control_linecontrol_pointsimplify_cgater   r   plot_gate_plusr   )ra   	circ_plotr   min_wiremax_wirer   r?   r?   r@   r     s   
zCGate.plot_gatec                 C      t | jtr| S t| S rR   )r}   r   r   r   _eval_daggerr`   r?   r?   r@   r        
zCGate._eval_daggerc                 C   r   rR   )r}   r   r   r   _eval_inverser`   r?   r?   r@   r     r   zCGate._eval_inversec                 C   sN   t | jtr!|dkrt| |S t|d dkr| t|  S | S t| |S )NrY   r   )r}   r   r   r   _eval_powerabsr   )ra   expr?   r?   r@   r     s   zCGate._eval_powerNr   )r   r   r   r   r   rk   _SOner   r   r   rS   r\   r   rb   re   r_   r   r   rs   r~   r   r   r   r   r   r   r   r   r?   r?   r?   r@   r   4  s<    









r   c                   @   s   e Zd ZdZdZdS )r7   zpVersion of CGate that allows gate simplifications.
    I.e. cnot looks like an oplus, cphase has dots, etc.
    TN)r   r   r   r   r   r?   r?   r?   r@   r7     s    r7   c                   @   s^   e Zd ZdZdZdZedd Zedd Ze	dd Z
dd
dZdd Zdd Zdd ZdS )r   a  General gate specified by a set of targets and a target matrix.

    Parameters
    ----------
    label : tuple
        A tuple of the form (targets, U), where targets is a tuple of the
        target qubits and U is a unitary matrix with dimension of
        len(targets).
    Uc                    s   |d }t |s|f}t|}t| |d }t|ts#td| t|}dt|  t	 fdd|j
D sAtd||f ||fS )Nr   rZ   zMatrix expected, got: %rrY   c                 3   s    | ]} |kV  qd S rR   r?   )r   shapedimr?   r@   r         z#UGate._eval_args.<locals>.<genexpr>z3Number of targets must match the matrix size: %r %r)r   r   rS   rO   r}   r   rJ   r   rK   r   r   
IndexError)rU   r=   r_   matr?   r   r@   rS     s"   

zUGate._eval_argsc                 C   s   t dt|d d  S r   r[   rT   r?   r?   r@   r\     s   zUGate._eval_hilbert_spacec                 C   r   )rh   r   r   r`   r?   r?   r@   r_     rf   zUGate.targetsrm   c                 C   r   )zThe matrix rep. of the target part of the gate.

        Parameters
        ----------
        format : str
            The format string ('sympy','numpy', etc.)
        rZ   ri   rq   r?   r?   r@   rs   (  s   
zUGate.get_target_matrixc                 G   s.   | j | jd|g|R  }t| j}| ||S r   )r   r_   r   r   r   )ra   r   r=   r_   r   r?   r?   r@   r   5  s   
zUGate._prettyc                 G   s&   | j | jd|g|R  }d| j|f S )NrP   r   )r   r_   rk   )ra   r   r=   r_   r?   r?   r@   r   ;  s   zUGate._latexc                 C      | | j|t| jd  d S Nr   one_qubit_boxrl   r   r_   ra   r   r   r?   r?   r@   r   ?     zUGate.plot_gateNr   )r   r   r   r   r   rk   r   rS   r\   r   r_   rs   r   r   r   r?   r?   r?   r@   r     s    	



r   c                   @   s.   e Zd ZdZejZdd Zdd Zdd Z	dS )	r   z'A single qubit unitary gate base class.c                 C   r   r   r   r   r?   r?   r@   r   K  r   zOneQubitGate.plot_gatec                 K   s<   t |tr| j|jks| j|jkrtjS tj| |fi |S rR   )r}   r   r_   r   r   Zeror   _eval_commutatorra   otherhintsr?   r?   r@   r   Q  s   
zOneQubitGate._eval_commutatorc                 K   sF   t |tr| j|jks| j|jkrtd|  | S tj| |fi |S NrY   )r}   r   r_   r   r   r   _eval_anticommutatorr   r?   r?   r@   r   W  s   
z!OneQubitGate._eval_anticommutatorN)
r   r   r   r   r   r   rb   r   r   r   r?   r?   r?   r@   r   F  s    r   c                   @   s   e Zd ZdZedZdS )r    z$A two qubit unitary gate base class.rY   N)r   r   r   r   r   rb   r?   r?   r?   r@   r    ^  s    r    c                   @   s>   e Zd ZdZdZdZdZdd ZdddZd	d
 Z	dd Z
dS )r!   zThe single qubit identity gate.

    Parameters
    ----------
    target : int
        The target qubit this gate will apply to.

    Examples
    ========

    T1c                 K   s$   |j | jk rtd| j|j f |S )Nr{   )rb   re   r   rv   r?   r?   r@   ru   y  s   
z"IdentityGate._apply_operator_Qubitrm   c                 C      t d|S )Neye2r   
get_matrixrq   r?   r?   r@   rs     r   zIdentityGate.get_target_matrixc                 K      t jS rR   r   r   r   r?   r?   r@   r        zIdentityGate._eval_commutatorc                 K   s   t d| S r   )r   r   r?   r?   r@   r     r   z!IdentityGate._eval_anticommutatorNr   )r   r   r   r   is_hermitianr   rk   ru   rs   r   r   r?   r?   r?   r@   r!   h  s    
	r!   c                   @   R   e Zd ZdZdZdZdddZdd Zdd	 Zd
d Z	dd Z
dd Zdd ZdS )r"   az  The single qubit Hadamard gate.

    Parameters
    ----------
    target : int
        The target qubit this gate will apply to.

    Examples
    ========

    >>> from sympy import sqrt
    >>> from sympy.physics.quantum.qubit import Qubit
    >>> from sympy.physics.quantum.gate import HadamardGate
    >>> from sympy.physics.quantum.qapply import qapply
    >>> qapply(HadamardGate(0)*Qubit('1'))
    sqrt(2)*|0>/2 - sqrt(2)*|1>/2
    >>> # Hadamard on bell state, applied on 2 qubits.
    >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
    >>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
    sqrt(2)*|00>/2 + sqrt(2)*|11>/2

    r,   rm   c                 C   s   t rtd|S td|S )Nr,   Hsqrt2)rE   r   r   rq   r?   r?   r@   rs     s   zHadamardGate.get_target_matrixc                 K   s   t td t| jd  S NrY   r   r   r   r$   r_   r   r?   r?   r@   _eval_commutator_XGate     z#HadamardGate._eval_commutator_XGatec                 K   s(   t td t| jd t| jd   S r   )r   r   r%   r_   r#   r   r?   r?   r@   _eval_commutator_YGate  s   (z#HadamardGate._eval_commutator_YGatec                 K   s   t  td t| jd  S r   r   r   r?   r?   r@   _eval_commutator_ZGate  s   z#HadamardGate._eval_commutator_ZGatec                 K      t dt| jd  S r   r   r!   r_   r   r?   r?   r@   _eval_anticommutator_XGate     z'HadamardGate._eval_anticommutator_XGatec                 K   r   rR   r   r   r?   r?   r@   _eval_anticommutator_YGate  r   z'HadamardGate._eval_anticommutator_YGatec                 K   r  r   r  r   r?   r?   r@   _eval_anticommutator_ZGate  r  z'HadamardGate._eval_anticommutator_ZGateNr   )r   r   r   r   r   rk   rs   r  r  r  r  r	  r
  r?   r?   r?   r@   r"     s    
r"   c                   @   r   )r#   zThe single qubit X, or NOT, gate.

    Parameters
    ----------
    target : int
        The target qubit this gate will apply to.

    Examples
    ========

    r-   rm   c                 C   r   )Nr-   r   rq   r?   r?   r@   rs     r   zXGate.get_target_matrixc                 C   s   t | || d S rR   )r   r   r   r?   r?   r@   r     s   zXGate.plot_gatec                 C   s   | |t| jd  d S r   )	not_pointr   rj   r   r?   r?   r@   r     s   zXGate.plot_gate_plusc                 K      t dt t| jd  S r   )r   r   r%   r_   r   r?   r?   r@   r    r  zXGate._eval_commutator_YGatec                 K   r  r   r   r!   r_   r   r?   r?   r@   r    r  z XGate._eval_anticommutator_XGatec                 K   r   rR   r   r   r?   r?   r@   r	    r   z XGate._eval_anticommutator_YGatec                 K   r   rR   r   r   r?   r?   r@   r
    r   z XGate._eval_anticommutator_ZGateNr   )r   r   r   r   r   rk   rs   r   r   r  r  r	  r
  r?   r?   r?   r@   r#     s    
r#   c                   @   s:   e Zd ZdZdZdZdddZdd Zdd	 Zd
d Z	dS )r$   zThe single qubit Y gate.

    Parameters
    ----------
    target : int
        The target qubit this gate will apply to.

    Examples
    ========

    r.   rm   c                 C   r   )Nr.   r   rq   r?   r?   r@   rs     r   zYGate.get_target_matrixc                 K   r  r   )r   r   r#   r_   r   r?   r?   r@   r    r  zYGate._eval_commutator_ZGatec                 K   r  r   r  r   r?   r?   r@   r	    r  z YGate._eval_anticommutator_YGatec                 K   r   rR   r   r   r?   r?   r@   r
    r   z YGate._eval_anticommutator_ZGateNr   )
r   r   r   r   r   rk   rs   r  r	  r
  r?   r?   r?   r@   r$     s    
r$   c                   @   s2   e Zd ZdZdZdZdddZdd Zdd	 Zd
S )r%   zThe single qubit Z gate.

    Parameters
    ----------
    target : int
        The target qubit this gate will apply to.

    Examples
    ========

    r/   rm   c                 C   r   )Nr/   r   rq   r?   r?   r@   rs     r   zZGate.get_target_matrixc                 K   r  r   )r   r   r$   r_   r   r?   r?   r@   r    r  zZGate._eval_commutator_XGatec                 K   r   rR   r   r   r?   r?   r@   r	    r   z ZGate._eval_anticommutator_YGateNr   )	r   r   r   r   r   rk   rs   r  r	  r?   r?   r?   r@   r%     s    
r%   c                   @   6   e Zd ZdZdZdZdZdddZdd Zd	d
 Z	dS )r'   a"  The single qubit phase, or S, gate.

    This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
    does nothing if the state is ``|0>``.

    Parameters
    ----------
    target : int
        The target qubit this gate will apply to.

    Examples
    ========

    Fr
   rm   c                 C   r   )Nr
   r   rq   r?   r?   r@   rs   .  r   zPhaseGate.get_target_matrixc                 K   r   rR   r   r   r?   r?   r@   r  1  r   z PhaseGate._eval_commutator_ZGatec                 K   r   rR   r   r   r?   r?   r@   _eval_commutator_TGate4  r   z PhaseGate._eval_commutator_TGateNr   )
r   r   r   r   r   r   rk   rs   r  r  r?   r?   r?   r@   r'         
r'   c                   @   r  )r&   a  The single qubit pi/8 gate.

    This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
    does nothing if the state is ``|0>``.

    Parameters
    ----------
    target : int
        The target qubit this gate will apply to.

    Examples
    ========

    Fr0   rm   c                 C   r   )Nr0   r   rq   r?   r?   r@   rs   K  r   zTGate.get_target_matrixc                 K   r   rR   r   r   r?   r?   r@   r  N  r   zTGate._eval_commutator_ZGatec                 K   r   rR   r   r   r?   r?   r@   _eval_commutator_PhaseGateQ  r   z TGate._eval_commutator_PhaseGateNr   )
r   r   r   r   r   r   rk   rs   r  r  r?   r?   r?   r@   r&   8  r  r&   c                   @   s   e Zd 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e
dd Ze
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!S )"r)   a  Two qubit controlled-NOT.

    This gate performs the NOT or X gate on the target qubit if the control
    qubits all have the value 1.

    Parameters
    ----------
    label : tuple
        A tuple of the form (control, target).

    Examples
    ========

    >>> from sympy.physics.quantum.gate import CNOT
    >>> from sympy.physics.quantum.qapply import qapply
    >>> from sympy.physics.quantum.qubit import Qubit
    >>> c = CNOT(1,0)
    >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
    |11>

    r*   z\text{CNOT}Tc                 C   s   t |}|S rR   )r   rS   rT   r?   r?   r@   rS     s   
zCNotGate._eval_argsc                 C   rV   rW   r[   rT   r?   r?   r@   r\     r]   zCNotGate._eval_hilbert_spacec                 C   rc   rd   )rA   rj   r`   r?   r?   r@   re     rf   zCNotGate.min_qubitsc                 C      | j d fS )rh   rZ   ri   r`   r?   r?   r@   r_        zCNotGate.targetsc                 C   r  r   ri   r`   r?   r?   r@   r     r  zCNotGate.controlsc                 C   r   r   )r#   rj   r`   r?   r?   r@   r     rf   zCNotGate.gatec                 G      t j| |g|R  S rR   )r   r   ra   r   r=   r?   r?   r@   r        zCNotGate._print_labelc                 G   r  rR   )r   r   r  r?   r?   r@   r     r  zCNotGate._prettyc                 G   r  rR   )r   r   r  r?   r?   r@   r     r  zCNotGate._latexc                 K   s&   | j d |jd krtjS td| )z[CNOT(i, j), Z(i)] == 0.r   Commutator not implemented: %r)r   r_   r   r   rp   r   r?   r?   r@   r       zCNotGate._eval_commutator_ZGatec                 K   rt   )z[CNOT(i, j), T(i)] == 0.r  r   r?   r?   r@   r    rz   zCNotGate._eval_commutator_TGatec                 K   rt   )z[CNOT(i, j), S(i)] == 0.r  r   r?   r?   r@   r    rz   z#CNotGate._eval_commutator_PhaseGatec                 K   &   | j d |j d krtjS td| )z[CNOT(i, j), X(j)] == 0.r   r  )r_   r   r   rp   r   r?   r?   r@   r    r  zCNotGate._eval_commutator_XGatec                 K   r  )z[CNOT(i, j), CNOT(i,k)] == 0.r   r  )r   r   r   rp   r   r?   r?   r@   _eval_commutator_CNotGate  r  z"CNotGate._eval_commutator_CNotGateN)r   r   r   r   r   rk   r   r   rS   r\   r   re   r_   r   r   r   r   r   r  r  r  r  r  r?   r?   r?   r@   r)   c  s2    





r)   c                   @   s>   e Zd ZdZdZdZdZdddZdd	 Zd
d Z	dd Z
dS )r(   zTwo qubit SWAP gate.

    This gate swap the values of the two qubits.

    Parameters
    ----------
    label : tuple
        A tuple of the form (target1, target2).

    Examples
    ========

    Tr+   z\text{SWAP}rm   c                 C   r   )Nr+   r   rq   r?   r?   r@   rs     r   zSwapGate.get_target_matrixc                 K   s6   | j d | j d }}t||}t||}|| | S )z(Decompose the SWAP gate into CNOT gates.r   rZ   )r_   r)   )ra   rx   ijr   r   r?   r?   r@   r     s   

zSwapGate.decomposec                 C   sF   t t| j}t t| j}|||| ||| ||| d S rR   )r   rD   r_   rA   r   
swap_point)ra   r   r   r   r   r?   r?   r@   r     s
   zSwapGate.plot_gatec                 K   s   | dd}dd | jD }t|}t|}| d| j}td|}td|}	td|}
td	|}td
|}d}||	f|	|f||f|
|
ffD ](\}}||g }|||| d < |||| d < t| }|du ro|}qK|| }qK|S )zRepresent the SWAP gate in the computational basis.

        The following representation is used to compute this:

        SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
        rr   rm   c                 S      g | ]}t |qS r?   r   r   r   r?   r?   r@   
<listcomp>       z-SwapGate._represent_ZGate.<locals>.<listcomp>rb   op01op10op11op00r   NrZ   )r   r_   rD   rA   re   r   r   r   )ra   r   rx   rr   r_   
min_target
max_targetrb   r$  r%  r&  r'  r   r   r  r  product
new_resultr?   r?   r@   r     s(   $

zSwapGate._represent_ZGateNr   )r   r   r   r   r   r   rk   rs   r   r   r   r?   r?   r?   r@   r(     s    
r(   c                 C   s   t | ft|S rR   )r7   r/   )r   r   r?   r?   r@   r6     s    r6   rm   c                 C   sL  dd | D } dd |D }t |}td|}td|}t| dkr]t|dkr]g }|d }||d krE|td|| d  |d	 || |dkrY|td| |d	 t| S t|dkrt| dkr|d }	g }
t|D ]}|
td|d	 qs| D ]
}||
|d | < q|| |
|d |	 < td| |d	t|
  S td
)a  Represent a gate with controls, targets and target_matrix.

    This function does the low-level work of representing gates as matrices
    in the standard computational basis (ZGate). Currently, we support two
    main cases:

    1. One target qubit and no control qubits.
    2. One target qubits and multiple control qubits.

    For the base of multiple controls, we use the following expression [1]:

    1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})

    Parameters
    ----------
    controls : list, tuple
        A sequence of control qubits.
    targets : list, tuple
        A sequence of target qubits.
    target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
        The matrix form of the transformation to be performed on the target
        qubits.  The format of this matrix must match that passed into
        the `format` argument.
    nqubits : int
        The total number of qubits used for the representation.
    format : str
        The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').

    Examples
    ========

    References
    ----------
    [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
    c                 S   r  r?   r   r   xr?   r?   r@   r"  H  r#  z$represent_zbasis.<locals>.<listcomp>c                 S   r  r?   r   r,  r?   r?   r@   r"  I  r#  r&  r   r   rZ   rY   r|   zKThe representation of multi-target, multi-control gates is not implemented.)	r   r   r   rK   appendr   r   r   rp   )r   r_   r   rb   rr   r&  r   r*  rN   r   product2r  controlr?   r?   r@   r   $  s8   $
r   c                 C   s  t | } t| trtdd | jD S t| tr| j}nt| tr/|  \}}t|| f}n| S t	t
|D ]}t|| trt|| jttttfrxt|| jtrx|d| || j|| jd  f ||d d  }tt| }  | S t|| jtr|d| }|t|| jjd t|| jd  || j|| jd  f }|||d d  }tt| }  | S t|| jtr|d| }|t|| jjd t|| jd  || j|| jd  f }|||d d  }tt| }  | S q7| S )zSimplifies gates symbolically

    It first sorts gates using gate_sort. It then applies basic
    simplification rules to the circuit, e.g., XGate**2 = Identity
    c                 s       | ]}t |V  qd S rR   )r4   r!  r?   r?   r@   r     r   zgate_simp.<locals>.<genexpr>NrY   rZ   r   )r3   r}   r   sumr=   r   r   as_base_expr4   r   rK   baser"   r#   r$   r%   r   r	   r'   r   r&   )circuitcircuit_argsr   er  newargsr?   r?   r@   r4   y  sh   





 r4   c           
      C   s  t | trtdd | jD S t | trt| j| j S t | tr#| S t | t	s*| S d}|rd}| j}t
t|d D ]}t || ttfrt ||d  ttfr||  \}}||d   \}}||dkrt|| dkr| jd| | j|d  f | j| f | j|d d  }t	| } d} n9t|| dkr| jd| | j|d  f | j| f | j|d d  }tj||  }	|	t	|  } d} nq;|s.| S )	ac  Sorts the gates while keeping track of commutation relations

    This function uses a bubble sort to rearrange the order of gate
    application. Keeps track of Quantum computations special commutation
    relations (e.g. things that apply to the same Qubit do not commute with
    each other)

    circuit is the Mul of gates that are to be sorted.
    c                 s   r1  rR   )r3   r!  r?   r?   r@   r     r   zgate_sort.<locals>.<genexpr>TFrZ   r   NrY   )r}   r   r2  r=   r   r3   r4  r   r   r   r   rK   r3  comparer   doitr   r   NegativeOne)
r5  changes
circ_arrayr  
first_base	first_expsecond_base
second_expnew_argssignr?   r?   r@   r3     sR   





r3   c           	      C   sn   t |}g }t | D ](}t|}|tks|tkr$t|d}|| }n	t|}||}|| q
t| S )a  Return a random circuit of ngates and nqubits.

    This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
    gates.

    Parameters
    ----------
    ngates : int
        The number of gates in the circuit.
    nqubits : int
        The number of qubits in the circuit.
    gate_space : tuple
        A tuple of the gate classes that will be used in the circuit.
        Repeating gate classes multiple times in this tuple will increase
        the frequency they appear in the random circuit.
    rY   )r   randomchoicer)   r(   sampler.  r   )	ngatesrb   
gate_spacequbit_spacer   r  grw   r   r?   r?   r@   r5     s   


r5   c                 C   r   )z(Transformation matrix from Z to X basis.ZXr   rq   r?   r?   r@   zx_basis_transform     rL  c                 C   r   )z(Transformation matrix from Z to Y basis.ZYr   rq   r?   r?   r@   zy_basis_transform  rM  rO  r   )Ur   	itertoolsr   rD  sympy.core.addr   sympy.core.containersr   sympy.core.mulr   sympy.core.numbersr   r   sympy.core.powerr   r	   sympy.core.singletonr
   r   sympy.core.sortingr   sympy.core.sympifyr   (sympy.functions.elementary.miscellaneousr    sympy.printing.pretty.stringpictr   r   $sympy.physics.quantum.anticommutatorr    sympy.physics.quantum.commutatorr   sympy.physics.quantum.qexprr   sympy.physics.quantum.hilbertr   sympy.physics.quantum.operatorr   r   r   !sympy.physics.quantum.matrixutilsr   r   !sympy.physics.quantum.matrixcacher   sympy.matrices.matrixbaser   sympy.utilities.iterablesr   __all__rE   rA   rD   r2   rO   r   r   r7   r   r   r    r!   r"   r#   r$   r%   r'   r&   r,   r-   r.   r/   r0   r1   r)   r(   r*   r+   r6   r   r4   r3   r5   rL  rO  r?   r?   r?   r@   <module>   sz    % 7 7U
$3'rE
UE9
