o
    jg:6                     @   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 g d
Zdd ZdddZdddZdd Zd ddZdd Zd!ddZd!ddZdd ZdS )"z1Primitive circuit operations on quantum circuits.    )reduce)default_sort_key)Tuple)Mul)Symbolsympify)numbered_symbols)Gate)	kmp_tablefind_subcircuitreplace_subcircuitconvert_to_symbolic_indicesconvert_to_real_indicesrandom_reducerandom_insertc                 C   s   d}d}g }| d | d |t| k rF| |d  | | kr.|d }| | |d }n|dkr7|| }n	| d |d }|t| k s|S )zBuild the 'partial match' table of the Knuth-Morris-Pratt algorithm.

    Note: This is applicable to strings or
    quantum circuits represented as tuples.
       r      )appendlen)wordposcndtable r   Z/var/www/html/zoom/venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitutils.pyr      s    





r   c                 C   s   t | tr| j} t |tr|j}t|dkst|t| kr dS |dk r(t| }|}d}t|}|| |k rg|| | ||  krE|d }n|| ||  }|| dkrW|| nd}|t|kra|S || |k s6dS )a  Finds the subcircuit in circuit, if it exists.

    Explanation
    ===========

    If the subcircuit exists, the index of the start of
    the subcircuit in circuit is returned; otherwise,
    -1 is returned.  The algorithm that is implemented
    is the Knuth-Morris-Pratt algorithm.

    Parameters
    ==========

    circuit : tuple, Gate or Mul
        A tuple of Gates or Mul representing a quantum circuit
    subcircuit : tuple, Gate or Mul
        A tuple of Gates or Mul to find in circuit
    start : int
        The location to start looking for subcircuit.
        If start is the same or past end, -1 is returned.
    end : int
        The last place to look for a subcircuit.  If end
        is less than 1 (one), then the length of circuit
        is taken to be end.

    Examples
    ========

    Find the first instance of a subcircuit:

    >>> from sympy.physics.quantum.circuitutils import find_subcircuit
    >>> from sympy.physics.quantum.gate import X, Y, Z, H
    >>> circuit = X(0)*Z(0)*Y(0)*H(0)
    >>> subcircuit = Z(0)*Y(0)
    >>> find_subcircuit(circuit, subcircuit)
    1

    Find the first instance starting at a specific position:

    >>> find_subcircuit(circuit, subcircuit, start=1)
    1

    >>> find_subcircuit(circuit, subcircuit, start=2)
    -1

    >>> circuit = circuit*subcircuit
    >>> find_subcircuit(circuit, subcircuit, start=2)
    4

    Find the subcircuit within some interval:

    >>> find_subcircuit(circuit, subcircuit, start=2, end=2)
    -1
    r   r   r   )
isinstancer   argsr   r   )circuit
subcircuitstartendr   indexr   r   r   r   r   8   s(   
8


r   Nc                 C   s   |dk rd}t | tr| j} t |tr|j}t |tr|j}n|du r%d}t| ||d}|dkrH| d| }| |t| t|  }|| | } | S )a  Replaces a subcircuit with another subcircuit in circuit,
    if it exists.

    Explanation
    ===========

    If multiple instances of subcircuit exists, the first instance is
    replaced.  The position to being searching from (if different from
    0) may be optionally given.  If subcircuit cannot be found, circuit
    is returned.

    Parameters
    ==========

    circuit : tuple, Gate or Mul
        A quantum circuit.
    subcircuit : tuple, Gate or Mul
        The circuit to be replaced.
    replace : tuple, Gate or Mul
        The replacement circuit.
    pos : int
        The location to start search and replace
        subcircuit, if it exists.  This may be used
        if it is known beforehand that multiple
        instances exist, and it is desirable to
        replace a specific instance.  If a negative number
        is given, pos will be defaulted to 0.

    Examples
    ========

    Find and remove the subcircuit:

    >>> from sympy.physics.quantum.circuitutils import replace_subcircuit
    >>> from sympy.physics.quantum.gate import X, Y, Z, H
    >>> circuit = X(0)*Z(0)*Y(0)*H(0)*X(0)*H(0)*Y(0)
    >>> subcircuit = Z(0)*Y(0)
    >>> replace_subcircuit(circuit, subcircuit)
    (X(0), H(0), X(0), H(0), Y(0))

    Remove the subcircuit given a starting search point:

    >>> replace_subcircuit(circuit, subcircuit, pos=1)
    (X(0), H(0), X(0), H(0), Y(0))

    >>> replace_subcircuit(circuit, subcircuit, pos=2)
    (X(0), Z(0), Y(0), H(0), X(0), H(0), Y(0))

    Replace the subcircuit:

    >>> replacement = H(0)*Z(0)
    >>> replace_subcircuit(circuit, subcircuit, replace=replacement)
    (X(0), H(0), Z(0), H(0), X(0), H(0), Y(0))
    r   Nr   )r!   r   )r   r   r   r   r   )r   r    replacer   locleftrightr   r   r   r      s    8


r   c                 C   s"   i }| D ]
}t | | ||< q|S Nr   )mappingnew_mapkeyr   r   r   _sympify_qubit_map   s   r,   c                 C   s  t | tr| j} tddd}t|}i }dd }|dur+t |ts)d| }t||}|dur@t |t js>d| }t||}|durUt |tsSd	d
|  }t||}t	|}||}	d}
| D ]e}t |t
rt|j|||d}|\}}}}|| ||}	n6t |ttfrt||||d}|\}}}}|| ||}	n||	v r|	| }nt|}|||< ||	|< |}t |t
r|j| }|
|f }
qa|
|||fS )aL  Returns the circuit with symbolic indices and the
    dictionary mapping symbolic indices to real indices.

    The mapping is 1 to 1 and onto (bijective).

    Parameters
    ==========

    seq : tuple, Gate/Integer/tuple or Mul
        A tuple of Gate, Integer, or tuple objects, or a Mul
    start : Symbol
        An optional starting symbolic index
    gen : object
        An optional numbered symbol generator
    qubit_map : dict
        An existing mapping of symbolic indices to real indices

    All symbolic indices have the format 'i#', where # is
    some number >= 0.
    ir   )prefixr!   c                 S   s   dd }t t||  S )Nc                 S   s   | d | d fS )Nr   r   r   )itemr   r   r   <lambda>  s    zIconvert_to_symbolic_indices.<locals>.create_inverse_map.<locals>.<lambda>)dictmapitems)symb_to_real_map	rev_itemsr   r   r   create_inverse_map  s   z7convert_to_symbolic_indices.<locals>.create_inverse_mapNz+Expected Symbol for starting index, got %r.zExpected a generator, got %r.z$Expected dict for existing map, got z%r.r   )	qubit_mapr!   gen)r   r   r   r	   nextr   	TypeError	__class__r1   r,   r
   r   updatetupler   )seqr!   r8   r7   	index_gencur_ndxndx_mapr6   msginv_mapsym_seqr/   resultsym_itemr*   r   r   r   r      sn   










r   c                 C   s   t | tr| j} t |tsd| }t|t|}d}| D ].}t |tr+t|j|}nt |tt	fr8t||}n|| }t |trF|j
| }||f }q|S )a  Returns the circuit with real indices.

    Parameters
    ==========

    seq : tuple, Gate/Integer/tuple or Mul
        A tuple of Gate, Integer, or tuple objects or a Mul
    qubit_map : dict
        A dictionary mapping symbolic indices to real indices.

    Examples
    ========

    Change the symbolic indices to real integers:

    >>> from sympy import symbols
    >>> from sympy.physics.quantum.circuitutils import convert_to_real_indices
    >>> from sympy.physics.quantum.gate import X, Y, H
    >>> i0, i1 = symbols('i:2')
    >>> index_map = {i0 : 0, i1 : 1}
    >>> convert_to_real_indices(X(i0)*Y(i1)*H(i0)*X(i1), index_map)
    (X(0), Y(1), H(0), X(1))
    z$Expected dict for qubit_map, got %r.r   )r   r   r   r1   r:   r,   r
   r   r=   r   r;   )r>   r7   rB   real_seqr/   	real_itemr   r   r   r   M  s"   




r   c                 C   sp   ddl m} |s
| S t| tr| j} t|}||}|r1|t|}||}t| |dkr/n|s| S t	| |S )a  Shorten the length of a quantum circuit.

    Explanation
    ===========

    random_reduce looks for circuit identities in circuit, randomly chooses
    one to remove, and returns a shorter yet equivalent circuit.  If no
    identities are found, the same circuit is returned.

    Parameters
    ==========

    circuit : Gate tuple of Mul
        A tuple of Gates representing a quantum circuit
    gate_ids : list, GateIdentity
        List of gate identities to find in circuit
    seed : int or list
        seed used for _randrange; to override the random selection, provide a
        list of integers: the elements of gate_ids will be tested in the order
        given by the list

    r   
_randranger   )
sympy.core.randomrJ   r   r   r   flatten_idsr   popr   r   )r   gate_idsseedrJ   ids	randranger-   idr   r   r   r     s   


r   c                 C   sh   ddl m} |s
| S t| tr| j} ||}|t| d }||t| }t| } || ||< t| S )a  Insert a circuit into another quantum circuit.

    Explanation
    ===========

    random_insert randomly chooses a location in the circuit to insert
    a randomly selected circuit from amongst the given choices.

    Parameters
    ==========

    circuit : Gate tuple or Mul
        A tuple or Mul of Gates representing a quantum circuit
    choices : list
        Set of circuit choices
    seed : int or list
        seed used for _randrange; to override the random selections, give
        a list two integers, [i, j] where i is the circuit location where
        choice[j] will be inserted.

    Notes
    =====

    Indices for insertion should be [0, n] if n is the length of the
    circuit.
    r   rI   r   )rK   rJ   r   r   r   r   listr=   )r   choicesrO   rJ   rQ   r%   choicer   r   r   r     s   
r   c                 C   s$   dd }t || g } | jtd | S )Nc                 S   s   | t |jtd S )Nr+   )sortedequivalent_idsr   )accan_idr   r   r   r0     s    zflatten_ids.<locals>.<lambda>rV   )r   sortr   )rP   collapser   r   r   rL     s   rL   )r   r   )Nr   )NNNr(   )__doc__	functoolsr   sympy.core.sortingr   sympy.core.containersr   sympy.core.mulr   sympy.core.symbolr   sympy.core.sympifyr   sympy.utilitiesr	   sympy.physics.quantum.gater
   __all__r   r   r   r,   r   r   r   r   rL   r   r   r   r   <module>   s&    
 
XU
a
5
2/