
    wg a                       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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( G d de)      Z* G d de*      Z+ G d de*      Z, G d de*      Z- G d de*      Z. G d  d!e*      Z/ G d" d#e      Z0 G d$ d%e      Z1 G d& d'e1      Z2 G d( d)e      Z3 G d* d+e3      Z4 G d, d-e3      Z5 G d. d/e3      Z6 G d0 d1e4e5      Z7 G d2 d3e4e6      Z8e7Z9e8Z: G d4 d5e3      Z; G d6 d7e;e5      Z< G d8 d9e;e6      Z=e=Z>e<Z? G d: d;e      Z@ G d< d=e@      ZA G d> d?e@      ZB G d@ dAe@      ZC G dB dCe@      ZD G dD dEeAeC      ZE G dF dGeAeD      ZF G dH dIeBeC      ZG G dJ dKeBeD      ZHeFZIeEZJeHZKeGZLdL ZMdM ZN G dN dOe      ZOdP ZP G dQ dR      ZQ G dS dT      ZR G dU dVeQ      ZS G dW dXe      ZT G dY dZe      ZUd[ ZVd\ ZWeWfd]ZXd^ ZYd_i fd`ZZ G da dbe%      Z[dc Z\doddZ]de Z^ G df dg      Z_ e_dh      Z`edodi       Zadj Zb G dk dle      Zcdm Zdyn)pz
Second quantization operators and states for bosons.

This follow the formulation of Fetter and Welecka, "Quantum Theory
of Many-Particle Systems."
    )defaultdict)Add)Basic)cacheit)Tuple)Expr)Function)Mul)I)Pow)Sdefault_sort_key)DummySymbol)sympify)sqrt)KroneckerDelta)zeros)
StrPrinter)has_dups)%Daggerr   BosonicOperatorAnnihilateBosonCreateBosonAnnihilateFermionCreateFermion	FockStateFockStateBraFockStateKetFockStateBosonKetFockStateBosonBraFockStateFermionKetFockStateFermionBraBBraBKetFBraFKetFFdBBdapply_operatorsInnerProductBosonicBasisVarBosonicBasisFixedBosonicBasis
Commutator
matrix_repcontractionwicksNOevaluate_deltasAntiSymmetricTensorsubstitute_dummiesPermutationOperatorsimplify_index_permutationsc                       e Zd Zy)SecondQuantizationErrorN__name__
__module____qualname__     ^/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/physics/secondquant.pyr=   r=   E       rC   r=   c                       e Zd Zy)AppliesOnlyToSymbolicIndexNr>   rB   rC   rD   rG   rG   I   rE   rC   rG   c                       e Zd Zy) ContractionAppliesOnlyToFermionsNr>   rB   rC   rD   rI   rI   M   rE   rC   rI   c                       e Zd Zy)ViolationOfPauliPrincipleNr>   rB   rC   rD   rK   rK   Q   rE   rC   rK   c                       e Zd Zy)$SubstitutionOfAmbigousOperatorFailedNr>   rB   rC   rD   rM   rM   U   rE   rC   rM   c                       e Zd Zy)WicksTheoremDoesNotApplyNr>   rB   rC   rD   rO   rO   Y   rE   rC   rO   c                   ,    e Zd ZdZd Zed        Zd Zy)r   a(  
    Hermitian conjugate of creation/annihilation operators.

    Examples
    ========

    >>> from sympy import I
    >>> from sympy.physics.secondquant import Dagger, B, Bd
    >>> Dagger(2*I)
    -2*I
    >>> Dagger(B(0))
    CreateBoson(0)
    >>> Dagger(Bd(0))
    AnnihilateBoson(0)

    c                     t        |      }| j                  |      }t        |t              r|S t        j                  | |      }|S N)r   eval
isinstancer   __new__)clsargrobjs       rD   rU   zDagger.__new__o   s<    clHHSMaHmmC%
rC   c           
         t        |dd      }| |       S t        |t              r|j                  r)t	        t        t        t        |j                               S |j                  r2t        t        t        t        t        |j                                     S |j                  r|S |j                  r/t        t        |j                  d         |j                  d         S |t        k(  r| S yy)as  
        Evaluates the Dagger instance.

        Examples
        ========

        >>> from sympy import I
        >>> from sympy.physics.secondquant import Dagger, B, Bd
        >>> Dagger(2*I)
        -2*I
        >>> Dagger(B(0))
        CreateBoson(0)
        >>> Dagger(Bd(0))
        AnnihilateBoson(0)

        The eval() method is called automatically.

        _dagger_Nr      )getattrrT   r   is_Addr   tuplemapr   argsis_Mulr
   reversed	is_Numberis_Powr   r   )rV   rW   daggers      rD   rS   zDagger.evalw   s    ( j$/8Oc5!zzE#fchh"7899zzE#fhsxx.@"ABCC}}
zz6#((1+.<<axt  rC   c                      | j                   d   S Nr   ra   selfs    rD   r[   zDagger._dagger_       yy|rC   N)r?   r@   rA   __doc__rU   classmethodrS   r[   rB   rC   rD   r   r   ]   s&    " " "HrC   r   c                       e Zd ZdZy)TensorSymbolTN)r?   r@   rA   is_commutativerB   rC   rD   rp   rp      s    NrC   rp   c                   b    e Zd ZdZd Zed        Zd Zed        Z	ed        Z
ed        Zd Zy	)
r8   a\  Stores upper and lower indices in separate Tuple's.

    Each group of indices is assumed to be antisymmetric.

    Examples
    ========

    >>> from sympy import symbols
    >>> from sympy.physics.secondquant import AntiSymmetricTensor
    >>> i, j = symbols('i j', below_fermi=True)
    >>> a, b = symbols('a b', above_fermi=True)
    >>> AntiSymmetricTensor('v', (a, i), (b, j))
    AntiSymmetricTensor(v, (a, i), (b, j))
    >>> AntiSymmetricTensor('v', (i, a), (b, j))
    -AntiSymmetricTensor(v, (a, i), (b, j))

    As you can see, the indices are automatically sorted to a canonical form.

    c                 R   	 t        || j                        \  }}t        || j                        \  }}t        |      }t        | }t        | }||z   dz  rt        j                  | |||       S t        j                  | |||      S # t        $ r t        j                  cY S w xY w)Nkey   )	_sort_anticommuting_fermions_sortkeyrK   r   Zeror   r   rp   rU   )rV   symbolupperlowersignusignls         rD   rU   zAntiSymmetricTensor.__new__   s    	73<<)LE573<<)LE5 uuEMQ ((feUCCC  ''VUEBB ) 	66M	s   4B
 
B&%B&c                 b   t        |      }t        |      }t        |t              rE|j                  j                  d      rd||fS |j                  j                  d      rd||fS d||fS |j                  j                  d      rd||fS |j                  j                  d      rd||fS d||fS )	zKey for sorting of indices.

        particle < hole < general

        FIXME: This is a bottle-neck, can we do it faster?
        above_fermi   below_fermi      
         )hashstrrT   r   assumptions0get)rV   indexhlabels       rD   rx   zAntiSymmetricTensor._sortkey   s     KE
eU#!!%%m4E1~%##''6E1~%E1~%!!-0q>!##M2q>!q>!rC   c                    d| j                   ddj                  | j                  d   D cg c]  }|j                   c}      ddj                  | j                  d   D cg c]  }|j                   c}      dS c c}w c c}w )N{z^{ r\   z}_{rv   z}})rz   joinra   name)rk   printeris      rD   _latexzAntiSymmetricTensor._latex   s_    KKGGdiil3aff34GGdiil3aff34
 	
33s   A?"Bc                      | j                   d   S )a  
        Returns the symbol of the tensor.

        Examples
        ========

        >>> from sympy import symbols
        >>> from sympy.physics.secondquant import AntiSymmetricTensor
        >>> i, j = symbols('i,j', below_fermi=True)
        >>> a, b = symbols('a,b', above_fermi=True)
        >>> AntiSymmetricTensor('v', (a, i), (b, j))
        AntiSymmetricTensor(v, (a, i), (b, j))
        >>> AntiSymmetricTensor('v', (a, i), (b, j)).symbol
        v

        r   ri   rj   s    rD   rz   zAntiSymmetricTensor.symbol       $ yy|rC   c                      | j                   d   S )a  
        Returns the upper indices.

        Examples
        ========

        >>> from sympy import symbols
        >>> from sympy.physics.secondquant import AntiSymmetricTensor
        >>> i, j = symbols('i,j', below_fermi=True)
        >>> a, b = symbols('a,b', above_fermi=True)
        >>> AntiSymmetricTensor('v', (a, i), (b, j))
        AntiSymmetricTensor(v, (a, i), (b, j))
        >>> AntiSymmetricTensor('v', (a, i), (b, j)).upper
        (a, i)


        r\   ri   rj   s    rD   r{   zAntiSymmetricTensor.upper  s    & yy|rC   c                      | j                   d   S )a  
        Returns the lower indices.

        Examples
        ========

        >>> from sympy import symbols
        >>> from sympy.physics.secondquant import AntiSymmetricTensor
        >>> i, j = symbols('i,j', below_fermi=True)
        >>> a, b = symbols('a,b', above_fermi=True)
        >>> AntiSymmetricTensor('v', (a, i), (b, j))
        AntiSymmetricTensor(v, (a, i), (b, j))
        >>> AntiSymmetricTensor('v', (a, i), (b, j)).lower
        (b, j)

        rv   ri   rj   s    rD   r|   zAntiSymmetricTensor.lower  r   rC   c                      d| j                   z  S )Nz	%s(%s,%s)ri   rj   s    rD   __str__zAntiSymmetricTensor.__str__,  s    TYY&&rC   N)r?   r@   rA   rm   rU   rn   rx   r   propertyrz   r{   r|   r   rB   rC   rD   r8   r8      sg    (C* " "0
  &  (  &'rC   r8   c                   P    e Zd ZdZdZdZd Zed        Zed        Z	d Z
d Zd	 Zy
)
SqOperatorz7
    Base class for Second Quantization operators.
    sqFc                 D    t        j                  | t        |            }|S rR   )r   rU   r   )rV   krY   s      rD   rU   zSqOperator.__new__9  s    mmC,
rC   c                      | j                   d   S )an  
        Returns the state index related to this operator.

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F, Fd, B, Bd
        >>> p = Symbol('p')
        >>> F(p).state
        p
        >>> Fd(p).state
        p
        >>> B(p).state
        p
        >>> Bd(p).state
        p

        r   ri   rj   s    rD   statezSqOperator.state=  s    * yy|rC   c                 2    | j                   j                  ryy)a@  
        Returns True if the state is a symbol (as opposed to a number).

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F
        >>> p = Symbol('p')
        >>> F(p).is_symbolic
        True
        >>> F(1).is_symbolic
        False

        FT)r   
is_Integerrj   s    rD   is_symboliczSqOperator.is_symbolicT  s    " ::  rC   c                     t         S rR   )NotImplementedrj   s    rD   __repr__zSqOperator.__repr__j  s    rC   c                 :    | j                   d| j                  dS )N())	op_symbolr   rj   s    rD   r   zSqOperator.__str__m  s    >>4::66rC   c                     t        d      )z0
        Applies an operator to itself.
        z&implement apply_operator in a subclass)NotImplementedErrorrk   r   s     rD   apply_operatorzSqOperator.apply_operatorp  s     ""JKKrC   N)r?   r@   rA   rm   r   rq   rU   r   r   r   r   r   r   rB   rC   rD   r   r   0  sP     IN  ,  *7LrC   r   c                       e Zd Zy)r   Nr>   rB   rC   rD   r   r   w  rE   rC   r   c                       e Zd Zy)AnnihilatorNr>   rB   rC   rD   r   r   {  rE   rC   r   c                       e Zd Zy)CreatorNr>   rB   rC   rD   r   r     rE   rC   r   c                   ,    e Zd ZdZdZd Zd Zd Zd Zy)r   z
    Bosonic annihilation operator.

    Examples
    ========

    >>> from sympy.physics.secondquant import B
    >>> from sympy.abc import x
    >>> B(x)
    AnnihilateBoson(x)
    bc                 ,    t        | j                        S rR   )r   r   rj   s    rD   r[   zAnnihilateBoson._dagger_  s    4::&&rC   c                     | j                   s>t        |t              r.| j                  }t	        ||         }||j                  |      z  S t        | |      S )a  
        Apply state to self if self is not symbolic and state is a FockStateKet, else
        multiply self by state.

        Examples
        ========

        >>> from sympy.physics.secondquant import B, BKet
        >>> from sympy.abc import x, y, n
        >>> B(x).apply_operator(y)
        y*AnnihilateBoson(x)
        >>> B(0).apply_operator(BKet((n,)))
        sqrt(n)*FockStateBosonKet((n - 1,))

        )r   rT   r    r   r   downr
   rk   r   elementamps       rD   r   zAnnihilateBoson.apply_operator  sN      Jul$CjjGuW~&Cuzz'***tU##rC   c                      d| j                   z  S )NzAnnihilateBoson(%s)r   rj   s    rD   r   zAnnihilateBoson.__repr__  s    $tzz11rC   c                 n    | j                   t        j                  u ryd| j                   j                  z  S )Nzb_{0}zb_{%s}r   r   ry   r   rk   r   s     rD   r   zAnnihilateBoson._latex  (    ::djjoo--rC   N	r?   r@   rA   rm   r   r[   r   r   r   rB   rC   rD   r   r     s"    
 I'$.2.rC   r   c                   ,    e Zd ZdZdZd Zd Zd Zd Zy)r   z$
    Bosonic creation operator.
    zb+c                 ,    t        | j                        S rR   )r   r   rj   s    rD   r[   zCreateBoson._dagger_  s    tzz**rC   c                     | j                   sAt        |t              r1| j                  }t	        ||   dz         }||j                  |      z  S t        | |      S )  
        Apply state to self if self is not symbolic and state is a FockStateKet, else
        multiply self by state.

        Examples
        ========

        >>> from sympy.physics.secondquant import B, Dagger, BKet
        >>> from sympy.abc import x, y, n
        >>> Dagger(B(x)).apply_operator(y)
        y*CreateBoson(x)
        >>> B(0).apply_operator(BKet((n,)))
        sqrt(n)*FockStateBosonKet((n - 1,))
        r\   )r   rT   r    r   r   upr
   r   s       rD   r   zCreateBoson.apply_operator  sS     Jul$CjjGuW~)*Cuxx(((tU##rC   c                      d| j                   z  S )NzCreateBoson(%s)r   rj   s    rD   r   zCreateBoson.__repr__  s     4::--rC   c                 n    | j                   t        j                  u ryd| j                   j                  z  S )Nz{b^\dagger_{0}}z{b^\dagger_{%s}}r   r   s     rD   r   zCreateBoson._latex  (    ::%&88rC   Nr   rB   rC   rD   r   r     s"     I+$,.9rC   r   c                   b    e Zd Zed        Zed        Zed        Zed        Zed        Zd Z	y)FermionicOperatorc                 ~    | j                   d   j                  }|j                  d      ry|j                  d      ryy)a  
        Is this FermionicOperator restricted with respect to fermi level?

        Returns
        =======

        1  : restricted to orbits above fermi
        0  : no restriction
        -1 : restricted to orbits below fermi

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F, Fd
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> F(a).is_restricted
        1
        >>> Fd(a).is_restricted
        1
        >>> F(i).is_restricted
        -1
        >>> Fd(i).is_restricted
        -1
        >>> F(p).is_restricted
        0
        >>> Fd(p).is_restricted
        0

        r   r   r   r\   ra   r   r   )rk   asss     rD   is_restrictedzFermionicOperator.is_restricted  s9    F iil''77=!77=!rC   c                 T    | j                   d   j                  j                  d       S )a!  
        Does the index of this FermionicOperator allow values above fermi?

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> F(a).is_above_fermi
        True
        >>> F(i).is_above_fermi
        False
        >>> F(p).is_above_fermi
        True

        Note
        ====

        The same applies to creation operators Fd

        r   r   r   rj   s    rD   is_above_fermiz FermionicOperator.is_above_fermi  s&    6 99Q<,,00???rC   c                 T    | j                   d   j                  j                  d       S )a  
        Does the index of this FermionicOperator allow values below fermi?

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> F(a).is_below_fermi
        False
        >>> F(i).is_below_fermi
        True
        >>> F(p).is_below_fermi
        True

        The same applies to creation operators Fd

        r   r   r   rj   s    rD   is_below_fermiz FermionicOperator.is_below_fermi+  s&    0 99Q<,,00???rC   c                 8    | j                   xr | j                   S )a  
        Is the index of this FermionicOperator restricted to values below fermi?

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> F(a).is_only_below_fermi
        False
        >>> F(i).is_only_below_fermi
        True
        >>> F(p).is_only_below_fermi
        False

        The same applies to creation operators Fd
        )r   r   rj   s    rD   is_only_below_fermiz%FermionicOperator.is_only_below_fermiE      . "">4+>+>'>>rC   c                 8    | j                   xr | j                   S )a  
        Is the index of this FermionicOperator restricted to values above fermi?

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> F(a).is_only_above_fermi
        True
        >>> F(i).is_only_above_fermi
        False
        >>> F(p).is_only_above_fermi
        False

        The same applies to creation operators Fd
        )r   r   rj   s    rD   is_only_above_fermiz%FermionicOperator.is_only_above_fermi^  r   rC   c                     t        |       }t        | j                  d         }| j                  rd||fS | j                  rd||fS t        | t              rd||fS t        | t              rd||fS y )Nr   r\         rv   )r   r   ra   is_only_q_creatoris_only_q_annihilatorrT   r   r   )rk   r   r   s      rD   rx   zFermionicOperator._sortkeyw  sx    JDIIaL!!!eQ;%%eQ;dK(eQ;dG$eQ; %rC   N)
r?   r@   rA   r   r   r   r   r   r   rx   rB   rC   rD   r   r     sn    ' 'R @ @8 @ @2 ? ?0 ? ?0rC   r   c                   l    e Zd ZdZdZd Zd Zed        Zed        Z	ed        Z
ed        Zd	 Zd
 Zy)r   z*
    Fermionic annihilation operator.
    fc                 ,    t        | j                        S rR   )r   r   rj   s    rD   r[   zAnnihilateFermion._dagger_  s    TZZ((rC   c                 X   t        |t              r| j                  }|j                  |      S t        |t              rb|j                         \  }}t        |d   t              r0| j                  }t	        ||d   j                  |      gz   |dd z    S t	        | |      S t	        | |      S r   r   r\   N)rT   r#   r   r   r
   args_cncrk   r   r   c_partnc_parts        rD   r   z AnnihilateFermion.apply_operator  s     e01jjG::g&&s##nn.OFG'!*&9:**Vwqzw'?&@@712;NPP4'' tU##rC   c                     | j                   ryy)a  
        Can we create a quasi-particle?  (create hole or create particle)
        If so, would that be above or below the fermi surface?

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> F(a).is_q_creator
        0
        >>> F(i).is_q_creator
        -1
        >>> F(p).is_q_creator
        -1

        r   r   r   rj   s    rD   is_q_creatorzAnnihilateFermion.is_q_creator      . rC   c                     | j                   ryy)a  
        Can we destroy a quasi-particle?  (annihilate hole or annihilate particle)
        If so, would that be above or below the fermi surface?

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F
        >>> a = Symbol('a', above_fermi=1)
        >>> i = Symbol('i', below_fermi=1)
        >>> p = Symbol('p')

        >>> F(a).is_q_annihilator
        1
        >>> F(i).is_q_annihilator
        0
        >>> F(p).is_q_annihilator
        1

        r\   r   r   rj   s    rD   is_q_annihilatorz"AnnihilateFermion.is_q_annihilator      . rC   c                     | j                   S )a  
        Always create a quasi-particle?  (create hole or create particle)

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> F(a).is_only_q_creator
        False
        >>> F(i).is_only_q_creator
        True
        >>> F(p).is_only_q_creator
        False

        r   rj   s    rD   r   z#AnnihilateFermion.is_only_q_creator      , '''rC   c                     | j                   S )a  
        Always destroy a quasi-particle?  (annihilate hole or annihilate particle)

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import F
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> F(a).is_only_q_annihilator
        True
        >>> F(i).is_only_q_annihilator
        False
        >>> F(p).is_only_q_annihilator
        False

        r   rj   s    rD   r   z'AnnihilateFermion.is_only_q_annihilator  r   rC   c                      d| j                   z  S )NzAnnihilateFermion(%s)r   rj   s    rD   r   zAnnihilateFermion.__repr__  s    &33rC   c                 n    | j                   t        j                  u ryd| j                   j                  z  S )Nza_{0}za_{%s}r   r   s     rD   r   zAnnihilateFermion._latex  r   rC   Nr?   r@   rA   rm   r   r[   r   r   r   r   r   r   r   r   rB   rC   rD   r   r     sr     I)$<  4  4 ( (. ( (.4.rC   r   c                   l    e Zd ZdZdZd Zd Zed        Zed        Z	ed        Z
ed        Zd	 Zd
 Zy)r   z&
    Fermionic creation operator.
    zf+c                 ,    t        | j                        S rR   )r   r   rj   s    rD   r[   zCreateFermion._dagger_$  s     ,,rC   c                 @   t        |t              r| j                  }|j                  |      S t        |t              rV|j                         \  }}t        |d   t              r0| j                  }t	        ||d   j                  |      gz   |dd z    S t	        | |      S r   )rT   r#   r   r   r
   r   r   s        rD   r   zCreateFermion.apply_operator'  s     e01jjG88G$$s##nn.OFG'!*&9:**Vwqz}}W'=&>>LNN4rC   c                     | j                   ryy)a  
        Can we create a quasi-particle?  (create hole or create particle)
        If so, would that be above or below the fermi surface?

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import Fd
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> Fd(a).is_q_creator
        1
        >>> Fd(i).is_q_creator
        0
        >>> Fd(p).is_q_creator
        1

        r\   r   r   rj   s    rD   r   zCreateFermion.is_q_creatorB  r   rC   c                     | j                   ryy)a  
        Can we destroy a quasi-particle?  (annihilate hole or annihilate particle)
        If so, would that be above or below the fermi surface?

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import Fd
        >>> a = Symbol('a', above_fermi=1)
        >>> i = Symbol('i', below_fermi=1)
        >>> p = Symbol('p')

        >>> Fd(a).is_q_annihilator
        0
        >>> Fd(i).is_q_annihilator
        -1
        >>> Fd(p).is_q_annihilator
        -1

        r   r   r   rj   s    rD   r   zCreateFermion.is_q_annihilator]  r   rC   c                     | j                   S )a  
        Always create a quasi-particle?  (create hole or create particle)

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import Fd
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> Fd(a).is_only_q_creator
        True
        >>> Fd(i).is_only_q_creator
        False
        >>> Fd(p).is_only_q_creator
        False

        r   rj   s    rD   r   zCreateFermion.is_only_q_creatorx  r   rC   c                     | j                   S )a  
        Always destroy a quasi-particle?  (annihilate hole or annihilate particle)

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import Fd
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> Fd(a).is_only_q_annihilator
        False
        >>> Fd(i).is_only_q_annihilator
        True
        >>> Fd(p).is_only_q_annihilator
        False

        r   rj   s    rD   r   z#CreateFermion.is_only_q_annihilator  r   rC   c                      d| j                   z  S )NzCreateFermion(%s)r   rj   s    rD   r   zCreateFermion.__repr__  s    "TZZ//rC   c                 n    | j                   t        j                  u ryd| j                   j                  z  S )Nz{a^\dagger_{0}}z{a^\dagger_{%s}}r   r   s     rD   r   zCreateFermion._latex  r   rC   Nr   rB   rC   rD   r   r     sr     I- 6  4  4 ( (. ( (.09rC   r   c                   >    e Zd ZdZdZd Zd Zd Zd Zd Z	d Z
d	 Zy
)r   z
    Many particle Fock state with a sequence of occupation numbers.

    Anywhere you can have a FockState, you can also have S.Zero.
    All code must check for this!

    Base class to represent FockStates.
    Fc                 p    t        t        t        |            }t        j                  | t        |       }|S )a[  
        occupations is a list with two possible meanings:

        - For bosons it is a list of occupation numbers.
          Element i is the number of particles in state i.

        - For fermions it is a list of occupied orbits.
          Element 0 is the state that was occupied first, element i
          is the i'th occupied state.
        )listr`   r   r   rU   r   )rV   occupationsrY   s      rD   rU   zFockState.__new__  s/     3w45mmC!45
rC   c                 <    t        |      }| j                  d   |   S rh   )intra   rk   r   s     rD   __getitem__zFockState.__getitem__  s    Fyy|ArC   c                      d| j                   z  S )NzFockState(%r)ri   rj   s    rD   r   zFockState.__repr__  s    DII..rC   c                 Z    t        | dd      | j                         t        | dd      S )Nlbracketr   rbracket)r]   _labelsrj   s    rD   r   zFockState.__str__  s*    "4R8$,,.'RVXbdfJghhrC   c                      | j                   d   S rh   ri   rj   s    rD   r  zFockState._labels  rl   rC   c                 2    t        | j                  d         S rh   lenra   rj   s    rD   __len__zFockState.__len__  s    499Q<  rC   c                 x    t        | dd      |j                  | j                               t        | dd      S )Nlbracket_latexr   rbracket_latex)r]   _printr  r   s     rD   r   zFockState._latex  sC    "4)92>t||~@^`ghln~  AC  aD  E  	ErC   N)r?   r@   rA   rm   rq   rU   r  r   r   r  r  r   rB   rC   rD   r   r     s3     N/i!ErC   r   c                       e Zd ZdZd Zd Zy)
BosonStatez1
    Base class for FockStateBoson(Ket/Bra).
    c                     t        |      }t        | j                  d         }||   t        j                  z   ||<   | j                  |      S )a  
        Performs the action of a creation operator.

        Examples
        ========

        >>> from sympy.physics.secondquant import BBra
        >>> b = BBra([1, 2])
        >>> b
        FockStateBosonBra((1, 2))
        >>> b.up(1)
        FockStateBosonBra((1, 3))
        r   )r  r  ra   r   One	__class__rk   r   new_occss      rD   r   zBosonState.up  sD     F		!%qkAEE)~~h''rC   c                     t        |      }t        | j                  d         }||   t        j                  k(  rt        j                  S ||   t        j
                  z
  ||<   | j                  |      S )a"  
        Performs the action of an annihilation operator.

        Examples
        ========

        >>> from sympy.physics.secondquant import BBra
        >>> b = BBra([1, 2])
        >>> b
        FockStateBosonBra((1, 2))
        >>> b.down(1)
        FockStateBosonBra((1, 1))
        r   )r  r  ra   r   ry   r  r   r!  s      rD   r   zBosonState.down  s]     F		!%A;!&& 66M"1+-HQK>>(++rC   N)r?   r@   rA   rm   r   r   rB   rC   rD   r  r    s    (&,rC   r  c                   v    e Zd ZdZdZddZd Zd Zed        Z	ed        Z
d Zd	 Zed
        Zd Zd Zd Zy)FermionStatez3
    Base class for FockStateFermion(Ket/Bra).
    r   c                    t        t        t        |            }t        |      dkD  r	 t	        |t
              \  }}nd}|| _	        | j                  |      |kD  rt        j                  S |dz  r't        j                  t        j                  | |      z  S t        j                  | |      S # t        $ r t        j                  cY S w xY w)Nr\   rt   r   rv   )r  r`   r   r  rw   r   rK   r   ry   fermi_level_count_holesNegativeOner   rU   )rV   r	  r'  signs       rD   rU   zFermionState.__new__  s    3w45{a&BT'+#d
 D%K(;666M!8==!2!23!DDD$$S+66 - vvs   B- -C	C	c                    || j                   d   v }| j                  |      r#|rt        j                  S | j	                  |      S | j                  |      r#|r| j                  |      S t        j                  S |r+t        dd      }t        ||      | j                  |      z  S t        dd      }t        ||      | j	                  |      z  S )a  
        Performs the action of a creation operator.

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

        If below fermi we try to remove a hole,
        if above fermi we try to create a particle.

        If general index p we return ``Kronecker(p,i)*self``
        where ``i`` is a new symbol with restriction above or below.

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import FKet
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        >>> FKet([]).up(a)
        FockStateFermionKet((a,))

        A creator acting on vacuum below fermi vanishes

        >>> FKet([]).up(i)
        0


        r   r   Tr   ar   )	ra   _only_above_fermir   ry   
_add_orbit_only_below_fermi_remove_orbitr   r   rk   r   presentholeparticles        rD   r   zFermionState.up.  s    @ tyy|#!!!$vvq))##A&))!,,vvSd3%a.t/A/A!/DDD $7%a24??13EEErC   c                    || j                   d   v }| j                  |      r#|r| j                  |      S t        j                  S | j                  |      r#|rt        j                  S | j                  |      S |r+t        dd      }t        ||      | j                  |      z  S t        dd      }t        ||      | j                  |      z  S )ag  
        Performs the action of an annihilation operator.

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

        If below fermi we try to create a hole,
        If above fermi we try to remove a particle.

        If general index p we return ``Kronecker(p,i)*self``
        where ``i`` is a new symbol with restriction above or below.

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.physics.secondquant import FKet
        >>> a = Symbol('a', above_fermi=True)
        >>> i = Symbol('i', below_fermi=True)
        >>> p = Symbol('p')

        An annihilator acting on vacuum above fermi vanishes

        >>> FKet([]).down(a)
        0

        Also below fermi, it vanishes, unless we specify a fermi level > 0

        >>> FKet([]).down(i)
        0
        >>> FKet([],4).down(i)
        FockStateFermionKet((i,))

        r   r   Tr,  r-  r.  )	ra   r/  r2  r   ry   r1  r0  r   r   r3  s        rD   r   zFermionState.downb  s    F tyy|#!!!$))!,,vv##A&vvq))Sd3%a.tq/AAA $7%a243E3Ea3HHHrC   c                 r    |j                   r|| j                  k  S |j                  j                  d      ryy)z
        Tests if given orbit is only below fermi surface.

        If nothing can be concluded we return a conservative False.
        r   TF	is_numberr'  r   r   rV   r   s     rD   r1  zFermionState._only_below_fermi  s2     ;;''>>m,rC   c                     |j                   r|| j                  kD  S |j                  j                  d      ry| j                   S )z
        Tests if given orbit is only above fermi surface.

        If fermi level has not been set we return True.
        If nothing can be concluded we return a conservative False.
        r   Tr9  r;  s     rD   r/  zFermionState._only_above_fermi  s<     ;;s&&>>m,??""rC   c                     t        | j                  d         }|j                  |      }||= |dz  r-t        j                  | j                  || j                        z  S | j                  || j                        S )zX
        Removes particle/fills hole in orbit i. No input tests performed here.
        r   rv   )r  ra   r   r   r)  r   r'  )rk   r   r"  poss       rD   r2  zFermionState._remove_orbit  si     		!%nnQSM19==$:J:J!KKK>>(D,<,<==rC   c                 \    | j                  |f| j                  d   z   | j                        S )zW
        Adds particle/creates hole in orbit i. No input tests performed here.
        r   )r   ra   r'  r  s     rD   r0  zFermionState._add_orbit  s*     ~~qdTYYq\143C3CDDrC   c                 b    t        |D cg c]  }| j                  |      s| c}      S c c}w )zG
        Returns the number of identified hole states in list.
        )r  r1  )rV   r  r   s      rD   r(  zFermionState._count_holes  s*    
 t@!s'<'<Q'?A@AA@s   ,,c                 b    t        |D cg c]  }|| j                  k  r| n| c}      S c c}w rR   )r_   r'  )rk   r  r   s      rD   _negate_holeszFermionState._negate_holes  s/    $GQA!1!11qbq8GHHGs   ,c                     | j                   r d| j                  d   d| j                   dS d| j                  d   dS )NzFockStateKet(r   z, fermi_level=r   )r'  ra   rj   s    rD   r   zFermionState.__repr__  s<    9=1tGWGWXX  *.177rC   c                 >    | j                  | j                  d         S rh   )rB  ra   rj   s    rD   r  zFermionState._labels  s    !!$))A,//rC   N)r   )r?   r@   rA   rm   r'  rU   r   r   rn   r1  r/  r2  r0  r(  rB  r   r  rB   rC   rD   r%  r%    sz     K7*2Fh6Ip 
 
 # #
>E B BI80rC   r%  c                        e Zd ZdZdZdZdZdZy)r    z"
    Representation of a ket.
    |>z\left|z\right\rangleN)r?   r@   rA   rm   r  r  r  r  rB   rC   rD   r    r      s     HHN%NrC   r    c                   &    e Zd ZdZdZdZdZdZd Zy)r   z"
    Representation of a bra.
    <rF  z\left\langlez\right|c                 f    t        |t              rt        | |      S t        j                  | |      S rR   )rT   r    r.   r   __mul__)rk   others     rD   rK  zFockStateBra.__mul__  s*    e\*e,,<<e,,rC   N)	r?   r@   rA   rm   r  r  r  r  rK  rB   rC   rD   r   r     s"     HH$NN-rC   r   c                       e Zd ZdZd Zy)r!   z
    Many particle Fock state with a sequence of occupation numbers.

    Occupation numbers can be any integer >= 0.

    Examples
    ========

    >>> from sympy.physics.secondquant import BKet
    >>> BKet([1, 2])
    FockStateBosonKet((1, 2))
    c                 &    t        | j                   S rR   )r"   ra   rj   s    rD   r[   zFockStateBosonKet._dagger_       $)),,rC   Nr?   r@   rA   rm   r[   rB   rC   rD   r!   r!     s    -rC   r!   c                       e Zd ZdZd Zy)r"   z
    Describes a collection of BosonBra particles.

    Examples
    ========

    >>> from sympy.physics.secondquant import BBra
    >>> BBra([1, 2])
    FockStateBosonBra((1, 2))
    c                 &    t        | j                   S rR   )r!   ra   rj   s    rD   r[   zFockStateBosonBra._dagger_  rO  rC   NrP  rB   rC   rD   r"   r"     s    	-rC   r"   c                       e Zd ZdZd Zy)r#   aR  
    Many-particle Fock state with a sequence of occupied orbits.

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

    Each state can only have one particle, so we choose to store a list of
    occupied orbits rather than a tuple with occupation numbers (zeros and ones).

    states below fermi level are holes, and are represented by negative labels
    in the occupation list.

    For symbolic state labels, the fermi_level caps the number of allowed hole-
    states.

    Examples
    ========

    >>> from sympy.physics.secondquant import FKet
    >>> FKet([1, 2])
    FockStateFermionKet((1, 2))
    c                 &    t        | j                   S rR   )r$   ra   rj   s    rD   r[   zFockStateFermionKet._dagger_,      "DII..rC   NrP  rB   rC   rD   r#   r#     s    ,/rC   r#   c                       e Zd ZdZd Zy)r$   z
    See Also
    ========

    FockStateFermionKet

    Examples
    ========

    >>> from sympy.physics.secondquant import FBra
    >>> FBra([1, 2])
    FockStateFermionBra((1, 2))
    c                 &    t        | j                   S rR   )r#   ra   rj   s    rD   r[   zFockStateFermionBra._dagger_>  rU  rC   NrP  rB   rC   rD   r$   r$   0  s    /rC   r$   c                    t        | t              s| S | j                         \  }}t        |      }|dv r| S |d   }|d   }t        |t              rut        |t
              rO|j                  r| S |j                  |      }|dk(  rt        j                  S t        t        ||dd z   |gz          S t        |t              rt        |j                  t
              r|j                  j                  r|j                  j                  r| S |}t        |j                        D ]$  }|j                  j                  |      }|dk(  s$ n |dk(  rt        j                  S t        t        ||dd z   |gz          S | S t        |t               r<t#        ||      }|dk(  rt        j                  S t        t        ||dd z   |gz          S | S | S )a  
    Take a Mul instance with operators and apply them to states.

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

    This method applies all operators with integer state labels
    to the actual states.  For symbolic state labels, nothing is done.
    When inner products of FockStates are encountered (like <a|b>),
    they are converted to instances of InnerProduct.

    This does not currently work on double inner products like,
    <a|b><c|d>.

    If the argument is not a Mul, it is simply returned as is.
    )r   r\   r   r   N)rT   r
   r   r  r    r   r   r   r   ry   
_apply_Mulr   baseexpr   ranger   r.   )mr   r   n_nclastnext_to_lastresultr   s           rD   rZ  rZ  G  s   " ajjlOFGw<Dv~r{r{dL),
3++H)88>F{ vv)#"0E0P*RSSL#.l//<$((33#((44 !%!&|'7'7!8 &A%1%6%6%E%Ef%MF%{ %& "Q;#$66M#-cFWSb\4IVH4T.V#WWHL,7%lD9Q;66M%cFWSb\,AVH,L&NOOHrC   c                     | j                         } | j                  t              }t        |      D cg c]  }|t	        |      f }}| j                  |      S c c}w )z
    Take a SymPy expression with operators and states and apply the operators.

    Examples
    ========

    >>> from sympy.physics.secondquant import apply_operators
    >>> from sympy import sympify
    >>> apply_operators(sympify(3)+4)
    7
    )expandatomsr
   iterrZ  subs)emulsr^  	subs_lists       rD   r-   r-     sP     	

A773<D-1$Z8!Z]#8I866) 9s   Ac                   V    e Zd ZdZdZd Zed        Zed        Z	ed        Z
d Zd Zy	)
r.   a>  
    An unevaluated inner product between a bra and ket.

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

    Currently this class just reduces things to a product of
    Kronecker Deltas.  In the future, we could introduce abstract
    states like ``|a>`` and ``|b>``, and leave the inner product unevaluated as
    ``<a|b>``.

    Tc                     t        |t              st        d      t        |t              st        d      | j	                  ||      S )Nzmust be a brazmust be a ket)rT   r   	TypeErrorr    rS   )rV   brakets      rD   rU   zInnerProduct.__new__  s=    #|,O,,#|,O,,xxS!!rC   c                     t         j                  }t        |j                  d   |j                  d         D ]  \  }}|t	        ||      z  }|dk(  s |S  |S rh   )r   r  zipra   r   )rV   rn  ro  rb  r   js         rD   rS   zInnerProduct.eval  s\    SXXa[1 	DAqnQ**F{		 rC   c                      | j                   d   S )z!Returns the bra part of the stater   ri   rj   s    rD   rn  zInnerProduct.bra       yy|rC   c                      | j                   d   S )z!Returns the ket part of the stater\   ri   rj   s    rD   ro  zInnerProduct.ket  rt  rC   c                 p    t        | j                        }t        | j                        }|d d d|dd  S )Nr   rF  r\   )reprrn  ro  )rk   sbraskets      rD   r   zInnerProduct.__repr__  s3    DHH~DHH~s)T!"X..rC   c                 "    | j                         S rR   )r   rj   s    rD   r   zInnerProduct.__str__  s    }}rC   N)r?   r@   rA   rm   rq   rU   rn   rS   r   rn  ro  r   r   rB   rC   rD   r.   r.     sY     N"      /
rC   r.   c                     t        t        |            }t        t        |            D ]@  }t        t        |            D ]'  }t        t	        ||         | z  ||   z        |||f<   ) B |S )a  
    Find the representation of an operator in a basis.

    Examples
    ========

    >>> from sympy.physics.secondquant import VarBosonicBasis, B, matrix_rep
    >>> b = VarBosonicBasis(5)
    >>> o = B(0)
    >>> matrix_rep(o, b)
    Matrix([
    [0, 1,       0,       0, 0],
    [0, 0, sqrt(2),       0, 0],
    [0, 0,       0, sqrt(3), 0],
    [0, 0,       0,       0, 2],
    [0, 0,       0,       0, 0]])
    )r   r  r]  r-   r   )opbasisr-  r   rr  s        rD   r3   r3     sv    $ 	c%jA3u: Ds5z" 	DA%fU1X&6r&9%(&BCAadG	DD HrC   c                       e Zd ZdZy)r/   z<
    Base class for a basis set of bosonic Fock states.
    N)r?   r@   rA   rm   rB   rC   rD   r/   r/     s     	rC   r/   c                   :    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
y	)
r0   a  
    A single state, variable particle number basis set.

    Examples
    ========

    >>> from sympy.physics.secondquant import VarBosonicBasis
    >>> b = VarBosonicBasis(5)
    >>> b
    [FockState((0,)), FockState((1,)), FockState((2,)),
     FockState((3,)), FockState((4,))]
    c                 2    || _         | j                          y rR   )n_max_build_states)rk   r  s     rD   __init__zVarBosonicBasis.__init__  s    
rC   c                     g | _         t        | j                        D ]'  }| j                   j                  t	        |g             ) t        | j                         | _        y rR   )r}  r]  r  appendr!   r  n_basisr  s     rD   r  zVarBosonicBasis._build_states  sJ    
tzz" 	6AJJ/45	64::rC   c                 8    | j                   j                  |      S )a  
        Returns the index of state in basis.

        Examples
        ========

        >>> from sympy.physics.secondquant import VarBosonicBasis
        >>> b = VarBosonicBasis(3)
        >>> state = b.state(1)
        >>> b
        [FockState((0,)), FockState((1,)), FockState((2,))]
        >>> state
        FockStateBosonKet((1,))
        >>> b.index(state)
        1
        r}  r   r   s     rD   r   zVarBosonicBasis.index  s    " zz&&rC   c                      | j                   |   S )z
        The state of a single basis.

        Examples
        ========

        >>> from sympy.physics.secondquant import VarBosonicBasis
        >>> b = VarBosonicBasis(5)
        >>> b.state(3)
        FockStateBosonKet((3,))
        r}  r  s     rD   r   zVarBosonicBasis.state  s     zz!}rC   c                 $    | j                  |      S rR   r   r  s     rD   r  zVarBosonicBasis.__getitem__%      zz!}rC   c                 ,    t        | j                        S rR   r  r}  rj   s    rD   r  zVarBosonicBasis.__len__(      4::rC   c                 ,    t        | j                        S rR   rw  r}  rj   s    rD   r   zVarBosonicBasis.__repr__+      DJJrC   N)r?   r@   rA   rm   r  r  r   r   r  r  r   rB   rC   rD   r0   r0     s*    ''& rC   r0   c                   @    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zy
)r1   aV  
    Fixed particle number basis set.

    Examples
    ========

    >>> from sympy.physics.secondquant import FixedBosonicBasis
    >>> b = FixedBosonicBasis(2, 2)
    >>> state = b.state(1)
    >>> b
    [FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]
    >>> state
    FockStateBosonKet((1, 1))
    >>> b.index(state)
    1
    c                 `    || _         || _        | j                          | j                          y rR   )n_particlesn_levels_build_particle_locationsr  )rk   r  r  s      rD   r  zFixedBosonicBasis.__init__@  s)    & &&(rC   c                 p   t        | j                        D cg c]  }d|z  	 }}d| j                  z  }d}t        |dd  |      D ]  \  }}d|d|d}||z   } dd	j	                  |      z  }d
|d|d|d}	t        |	      }
| j                  dk(  r|
D cg c]  }|f }
}|
| _        y c c}w c c}w )Nzi%izfor i0 in range(%i)r   r\   zfor z
 in range(z + 1) z(%s)z, [ ])r]  r  r  rq  r   rS   particle_locations)rk   r   tup
first_loopother_loopscurprevtemp
tup_string	list_comprb  items               rD   r  z+FixedBosonicBasis._build_particle_locationsF  s    "'(8(8"9:Quqy::*T]]:
SWc* 	-IC14d;D%,K	- diin,
$.
KH	iq *01$tg1F1"( ; 2s   B.
B3c                     g | _         | j                  D ]J  }| j                  dgz  }|D ]  }||xx   dz  cc<    | j                   j                  t	        |             L t        | j                         | _        y )Nr   r\   )r}  r  r  r  r!   r  r  )rk   tuple_of_indicesocc_numberslevels       rD   r  zFixedBosonicBasis._build_statesT  sw    
 $ 7 7 	>--+K) (E"a'"(JJ/<=		>
 4::rC   c                 8    | j                   j                  |      S )zReturns the index of state in basis.

        Examples
        ========

        >>> from sympy.physics.secondquant import FixedBosonicBasis
        >>> b = FixedBosonicBasis(2, 3)
        >>> b.index(b.state(3))
        3
        r  r   s     rD   r   zFixedBosonicBasis.index]  s     zz&&rC   c                      | j                   |   S )a  Returns the state that lies at index i of the basis

        Examples
        ========

        >>> from sympy.physics.secondquant import FixedBosonicBasis
        >>> b = FixedBosonicBasis(2, 3)
        >>> b.state(3)
        FockStateBosonKet((1, 0, 1))
        r  r  s     rD   r   zFixedBosonicBasis.statej  s     zz!}rC   c                 $    | j                  |      S rR   r   r  s     rD   r  zFixedBosonicBasis.__getitem__w  r  rC   c                 ,    t        | j                        S rR   r  rj   s    rD   r  zFixedBosonicBasis.__len__z  r  rC   c                 ,    t        | j                        S rR   r  rj   s    rD   r   zFixedBosonicBasis.__repr__}  r  rC   N)r?   r@   rA   rm   r  r  r  r   r   r  r  r   rB   rC   rD   r1   r1   /  s/     )'' rC   r1   c                   <    e Zd ZdZdZed        Zd Zd Zd Z	d Z
y)	r2   ab  
    The Commutator:  [A, B] = A*B - B*A

    The arguments are ordered according to .__cmp__()

    Examples
    ========

    >>> from sympy import symbols
    >>> from sympy.physics.secondquant import Commutator
    >>> A, B = symbols('A,B', commutative=False)
    >>> Commutator(B, A)
    -Commutator(A, B)

    Evaluate the commutator with .doit()

    >>> comm = Commutator(A,B); comm
    Commutator(A, B)
    >>> comm.doit()
    A*B - B*A


    For two second quantization operators the commutator is evaluated
    immediately:

    >>> from sympy.physics.secondquant import Fd, F
    >>> a = symbols('a', above_fermi=True)
    >>> i = symbols('i', below_fermi=True)
    >>> p,q = symbols('p,q')

    >>> Commutator(Fd(a),Fd(i))
    2*NO(CreateFermion(a)*CreateFermion(i))

    But for more complicated expressions, the evaluation is triggered by
    a call to .doit()

    >>> comm = Commutator(Fd(p)*Fd(q),F(i)); comm
    Commutator(CreateFermion(p)*CreateFermion(q), AnnihilateFermion(i))
    >>> comm.doit(wicks=True)
    -KroneckerDelta(i, p)*CreateFermion(q) +
     KroneckerDelta(i, q)*CreateFermion(p)

    Fc           	      D   |r|st         j                  S ||k(  rt         j                  S |j                  s|j                  rt         j                  S |j                         }t	        |t
              r't        |j                  D cg c]  } | ||       c} S |j                         }t	        |t
              r't        |j                  D cg c]  } | ||       c} S |j                         \  }}|j                         \  }}t        |      t        |      z   }|r?t        t        |  | t        j                  |      t        j                  |                  S t	        |t              rt	        |t              rt	        |t              r0t	        |t              r t        |j                  |j                        S t	        |t              rAt	        |t              r1t         j                   t        |j                  |j                        z  S t         j                  S t	        |t"              r-t	        |t"              rt%        ||z        t%        ||z        z
  S |j'                         |j'                         kD  rt         j                    | ||      z  S yc c}w c c}w )aQ  
        The Commutator [A,B] is on canonical form if A < B.

        Examples
        ========

        >>> from sympy.physics.secondquant import Commutator, F, Fd
        >>> from sympy.abc import x
        >>> c1 = Commutator(F(x), Fd(x))
        >>> c2 = Commutator(Fd(x), F(x))
        >>> Commutator.eval(c1, c2)
        0
        N)r   ry   rq   rd  rT   r   ra   r   r  r
   
_from_argsr   r   r   r   r   r)  r   r5   sort_key)	rV   r-  r   termcancacbncbr   s	            rD   rS   zCommutator.eval  s    a66M666Mq//66M
 HHJa!&&9$T19::HHJa!&&9$Q9::
 **,C**,CbDH$sF|S)<cnnS>Q%RSS
 a)jO.L![)jO.L%aggqww77![)jO.L}}^AGGQWW%EEEvva*+
1>O0P1:ac
**
 ::<!**,&==Q** '= : :s   JJc                 L   | j                   d   }| j                   d   }|j                  d      rB |j                  di |} |j                  di |}	 t        ||z        t        ||z        z
  S  ||z  ||z  z
  j                  di |S # t        $ r Y &t
        $ r Y 0w xY w)a  
        Enables the computation of complex expressions.

        Examples
        ========

        >>> from sympy.physics.secondquant import Commutator, F, Fd
        >>> from sympy import symbols
        >>> i, j = symbols('i,j', below_fermi=True)
        >>> a, b = symbols('a,b', above_fermi=True)
        >>> c = Commutator(Fd(a)*F(i),Fd(b)*F(j))
        >>> c.doit(wicks=True)
        0
        r   r\   r5   rB   )ra   r   doitr5   rI   rO   )rk   hintsr-  r   s       rD   r  zCommutator.doit  s     IIaLIIaL99WAAQqSzE!A#J..  !ac	(%(( 4 + s   B 	B#B#"B#c                 H    d| j                   d   d| j                   d   dS )NzCommutator(r   ,r\   r   ri   rj   s    rD   r   zCommutator.__repr__
  s    &*iilDIIaLAArC   c                 H    d| j                   d   d| j                   d   dS )Nr  r   r  r\   r  ri   rj   s    rD   r   zCommutator.__str__  s     IIaL$))A,77rC   c           	      v    dt        | j                  D cg c]  }|j                  |       c}      z  S c c}w )Nz\left[%s,%s\right])r_   ra   r  )rk   r   rW   s      rD   r   zCommutator._latex  s;    %+/99/6$'GNN3/6 )7 7 	7 /6s   6
N)r?   r@   rA   rm   rq   rn   rS   r  r   r   r   rB   rC   rD   r2   r2     s7    *X N9+ 9+v)<B87rC   r2   c                   |    e Zd ZdZdZd Zed        Zed        Zd Z	d Z
d Zd	 Zd
 Zd Zd Zd Zd Zd Zd Zy)r6   a  
    This Object is used to represent normal ordering brackets.

    i.e.  {abcd}  sometimes written  :abcd:

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

    Applying the function NO(arg) to an argument means that all operators in
    the argument will be assumed to anticommute, and have vanishing
    contractions.  This allows an immediate reordering to canonical form
    upon object creation.

    Examples
    ========

    >>> from sympy import symbols
    >>> from sympy.physics.secondquant import NO, F, Fd
    >>> p,q = symbols('p,q')
    >>> NO(Fd(p)*F(q))
    NO(CreateFermion(p)*AnnihilateFermion(q))
    >>> NO(F(q)*Fd(p))
    -NO(CreateFermion(p)*AnnihilateFermion(q))


    Note
    ====

    If you want to generate a normal ordered equivalent of an expression, you
    should use the function wicks().  This class only indicates that all
    operators inside the brackets anticommute, and have vanishing contractions.
    Nothing more, nothing less.

    Fc                    t        |      }|j                         }|j                  r&t        |j                  D cg c]
  } | |       c} S |j
                  r1|j                         \  }}|rt        | }|s|S t        j                  }g }d}|D ]A  }t        |t              r|j                  |j                         d}1|j                  |       C |r| | t        |       z  S t        |d   t              rt        	 t!        |      \  }}	|	dz  r"t        j&                  |z   | t        |       z  S |	r| | t        |       z  S 	 |t        j                  k7  r| | t        |       z  S t)        j*                  | t        |       S t        |t              r|S |S c c}w # t"        $ r t        j$                  cY S w xY w)ar  
        Use anticommutation to get canonical form of operators.

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

        Employ associativity of normal ordered product: {ab{cd}} = {abcd}
        but note that {ab}{cd} /= {abcd}.

        We also employ distributivity: {ab + cd} = {ab} + {cd}.

        Canonical form also implies expand() {ab(c+d)} = {abc} + {abd}.

        FTr   rv   )r   rd  r^   r   ra   rb   r   r
   r   r  rT   r6   extendr  r   r   rw   rK   ry   r)  r   rU   )
rV   rW   r  r   seqcoeffnewseqfounditfacr*  s
             rD   rU   z
NO.__new__:  s   " cljjl::9#d)9:::: ,,.KFCV L FG 'c2&MM#((+"GMM#&' Sf... #a&/2));C@ axe+Sf->>>Sf... ~Sf...<<S&\22c2J 
g :> - vvs   F F% %G Gc                 N    | j                   d   j                   d   j                  S )a<  
        Return 0 if the leftmost argument of the first argument is a not a
        q_creator, else 1 if it is above fermi or -1 if it is below fermi.

        Examples
        ========

        >>> from sympy import symbols
        >>> from sympy.physics.secondquant import NO, F, Fd

        >>> a = symbols('a', above_fermi=True)
        >>> i = symbols('i', below_fermi=True)
        >>> NO(Fd(a)*Fd(i)).has_q_creators
        1
        >>> NO(F(i)*F(a)).has_q_creators
        -1
        >>> NO(Fd(i)*F(a)).has_q_creators           #doctest: +SKIP
        0

        r   )ra   r   rj   s    rD   has_q_creatorszNO.has_q_creators  s#    , yy|  #000rC   c                 N    | j                   d   j                   d   j                  S )a3  
        Return 0 if the rightmost argument of the first argument is a not a
        q_annihilator, else 1 if it is above fermi or -1 if it is below fermi.

        Examples
        ========

        >>> from sympy import symbols
        >>> from sympy.physics.secondquant import NO, F, Fd

        >>> a = symbols('a', above_fermi=True)
        >>> i = symbols('i', below_fermi=True)
        >>> NO(Fd(a)*Fd(i)).has_q_annihilators
        -1
        >>> NO(F(i)*F(a)).has_q_annihilators
        1
        >>> NO(Fd(a)*F(i)).has_q_annihilators
        0

        r   r   )ra   r   rj   s    rD   has_q_annihilatorszNO.has_q_annihilators  s#    , yy|  $555rC   c                     |j                  dd      r| j                         S | j                  t        |        | j                  d   j
                  di |      S )a  
        Either removes the brackets or enables complex computations
        in its arguments.

        Examples
        ========

        >>> from sympy.physics.secondquant import NO, Fd, F
        >>> from textwrap import fill
        >>> from sympy import symbols, Dummy
        >>> p,q = symbols('p,q', cls=Dummy)
        >>> print(fill(str(NO(Fd(p)*F(q)).doit())))
        KroneckerDelta(_a, _p)*KroneckerDelta(_a,
        _q)*CreateFermion(_a)*AnnihilateFermion(_a) + KroneckerDelta(_a,
        _p)*KroneckerDelta(_i, _q)*CreateFermion(_a)*AnnihilateFermion(_i) -
        KroneckerDelta(_a, _q)*KroneckerDelta(_i,
        _p)*AnnihilateFermion(_a)*CreateFermion(_i) - KroneckerDelta(_i,
        _p)*KroneckerDelta(_i, _q)*AnnihilateFermion(_i)*CreateFermion(_i)
        remove_bracketsTr   rB   )r   _remove_bracketsrU   typera   r  )rk   r  s     rD   r  zNO.doit  sP    ( 99&-((**<<T
,=DIIaL,=,=,F,FGGrC   c                 H   g }| j                         D ]  }| |   j                  s| |   j                  j                  }t	        | |   j                  t
              r|j                  dd       d|d<   t        di |}|j                  dd       d|d<   t        di |}t        | |         }| |   j                  ||      t        || |   j                        z  | |   j                  ||      t        || |   j                        z  z   }|j                  | |   |f       t        | |          |rYt        | j                  |            }t	        |t              r.t        |j                  D 	cg c]  }	|	j!                          c}	 S y| j                  d   S c c}	w )z
        Returns the sorted string without normal order brackets.

        The returned string have the property that no nonzero
        contractions exist.
        r   NTr   r   )r   )r-  )iter_q_creatorsr   r   r   rT   r   popr  rU   r   r  rM   r6   rg  r   ra   r  )
rk   subslistr   assumebelowaboverV   splitrb  r  s
             rD   r  zNO._remove_brackets  s    %%' 	HAAw''a33 d1gmmU3 JJ}d3,0F=)!00EJJ}d3,0F=)!00EtAw-CQU3(Q>?q'//#u5(Q>??  OOT!We$45>tAwGG1	H2 		(+,F&#&V[[ATTYY[ABB ' 99Q< Bs   4Fc                 ,    t        | j                        S )aG  
        Returns a sum of NO objects that contain no ambiguous q-operators.

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

        If an index q has range both above and below fermi, the operator F(q)
        is ambiguous in the sense that it can be both a q-creator and a q-annihilator.
        If q is dummy, it is assumed to be a summation variable and this method
        rewrites it into a sum of NO terms with unambiguous operators:

        {Fd(p)*F(q)} = {Fd(a)*F(b)} + {Fd(a)*F(i)} + {Fd(j)*F(b)} -{F(i)*Fd(j)}

        where a,b are above and i,j are below fermi level.
        )r6   r  rj   s    rD   _expand_operatorszNO._expand_operators  s      $''((rC   c                     t        |t              rJ|j                  t        |             }t	        | D cg c]  }| j
                  d   j
                  |     c}S | j
                  d   j
                  |   S c c}w rh   )rT   sliceindicesr  r]  ra   )rk   r   r  s      rD   r  zNO.__getitem__  se    aiiD	*G27/BQDIIaL%%a(BB99Q<$$Q'' Cs   #A7c                 F    t        | j                  d   j                        S rh   r  rj   s    rD   r  z
NO.__len__  s    499Q<$$%%rC   c              #      K   | j                   d   j                   }t        t        |      dz
  dd      }|D ]  }||   j                  r|  y yw)a  
        Iterates over the annihilation operators.

        Examples
        ========

        >>> from sympy import symbols
        >>> i, j = symbols('i j', below_fermi=True)
        >>> a, b = symbols('a b', above_fermi=True)
        >>> from sympy.physics.secondquant import NO, F, Fd
        >>> no = NO(Fd(a)*F(i)*F(b)*Fd(j))

        >>> no.iter_q_creators()
        <generator object... at 0x...>
        >>> list(no.iter_q_creators())
        [0, 1]
        >>> list(no.iter_q_annihilators())
        [3, 2]

        r   r\   r   N)ra   r]  r  r   rk   opsrf  r   s       rD   iter_q_annihilatorszNO.iter_q_annihilators  sU     * iilSX\2r* 	A1v&&		s   AAc              #      K   | j                   d   j                   }t        dt        |            }|D ]  }||   j                  r|  y yw)a
  
        Iterates over the creation operators.

        Examples
        ========

        >>> from sympy import symbols
        >>> i, j = symbols('i j', below_fermi=True)
        >>> a, b = symbols('a b', above_fermi=True)
        >>> from sympy.physics.secondquant import NO, F, Fd
        >>> no = NO(Fd(a)*F(i)*F(b)*Fd(j))

        >>> no.iter_q_creators()
        <generator object... at 0x...>
        >>> list(no.iter_q_creators())
        [0, 1]
        >>> list(no.iter_q_annihilators())
        [3, 2]

        r   N)ra   r]  r  r   r  s       rD   r  zNO.iter_q_creators/  sO     , iilQC! 	A1v""		s   AAc                     | j                   d   } |j                  |j                   d| |j                   |dz   d z    }t        |      S )aS  
        Returns a NO() without FermionicOperator at index i.

        Examples
        ========

        >>> from sympy import symbols
        >>> from sympy.physics.secondquant import F, NO
        >>> p, q, r = symbols('p,q,r')

        >>> NO(F(p)*F(q)*F(r)).get_subNO(1)
        NO(AnnihilateFermion(p)*AnnihilateFermion(r))

        r   Nr\   )ra   _new_rawargsr6   )rk   r   arg0muls       rD   	get_subNOzNO.get_subNOM  sJ     yy|d$))BQ-$))AEF2C"CE#wrC   c                 D    d|j                  | j                  d         z  S )Nz\left\{%s\right\}r   )r  ra   r   s     rD   r   z	NO._latex`  s    &		!)EEErC   c                 &    d| j                   d   z  S )NzNO(%s)r   ri   rj   s    rD   r   zNO.__repr__c  s    $))A,&&rC   c                 &    d| j                   d   z  S )Nz:%s:r   ri   rj   s    rD   r   z
NO.__str__f  s    		!$$rC   N)r?   r@   rA   rm   rq   rU   r   r  r  r  r  r  r  r  r  r  r  r   r   r   rB   rC   rD   r6   r6     sx    !D NGR 1 1. 6 6.H2( T)$(&:<&F'%rC   r6   c                    t        |t              rt        | t              rt        | t              rGt        |t              r6|j                  j
                  j                  d      rt        j                  S | j                  j
                  j                  d      rt        j                  S |j                  j
                  j                  d      r t        | j                  |j                        S | j                  j
                  j                  d      r t        | j                  |j                        S t        | j                  |j                        t        |j                  t        dd            z  S t        |t              rGt        | t              r6|j                  j
                  j                  d      rt        j                  S | j                  j
                  j                  d      rt        j                  S |j                  j
                  j                  d      r t        | j                  |j                        S | j                  j
                  j                  d      r t        | j                  |j                        S t        | j                  |j                        t        |j                  t        dd            z  S t        j                  S d | |fD        }t        | )	a  
    Calculates contraction of Fermionic operators a and b.

    Examples
    ========

    >>> from sympy import symbols
    >>> from sympy.physics.secondquant import F, Fd, contraction
    >>> p, q = symbols('p,q')
    >>> a, b = symbols('a,b', above_fermi=True)
    >>> i, j = symbols('i,j', below_fermi=True)

    A contraction is non-zero only if a quasi-creator is to the right of a
    quasi-annihilator:

    >>> contraction(F(a),Fd(b))
    KroneckerDelta(a, b)
    >>> contraction(Fd(i),F(j))
    KroneckerDelta(i, j)

    For general indices a non-zero result restricts the indices to below/above
    the fermi surface:

    >>> contraction(Fd(p),F(q))
    KroneckerDelta(_i, q)*KroneckerDelta(p, q)
    >>> contraction(F(p),Fd(q))
    KroneckerDelta(_a, q)*KroneckerDelta(p, q)

    Two creators or two annihilators always vanishes:

    >>> contraction(F(p),F(q))
    0
    >>> contraction(Fd(p),Fd(q))
    0

    r   r   r-  Tr.  r   r,  c              3   <   K   | ]  }t        |t                y wrR   )rT   r   ).0r   s     rD   	<genexpr>zcontraction.<locals>.<genexpr>  s     @1j-.@s   )rT   r   r   r   r   r   r   r   ry   r   r   rI   )r-  r   ts      rD   r4   r4   j  s   J !&'Jq:K,La*+
1m0Lww##''6vvww##''6vvww##''6%aggqww77ww##''6%aggqww77"177AGG4"177E#4,HIJ Ka*+
1m0Lww##''6vvww##''6vvww##''6%aggqww77ww##''6%aggqww77"177AGG4"177E#4,HIJ K vv AA@.22rC   c                 "    | j                         S )z4Generates key for canonical sorting of SQ operators.)rx   )sq_operators    rD   _sqkeyr    s    !!rC   c                 2   d}d}t        t        t        |       dz
              }t        t        t        |       dz
  dd            }t        t        ||             }t	        t        t        ||                   }|sd}|D ]8  }||   }	||dz      }
|	|
k(  rt        |	|
g      |	|
kD  s(d}|
|	g|||dz    |dz   }: |rn@|D ]8  }||   }	||dz      }
|	|
k(  rt        |	|
g      |	|
kD  s(d}|
|	g|||dz    |dz   }: |s|D cg c]  }||   	 } }| |fS c c}w )aR  Sort fermionic operators to canonical order, assuming all pairs anticommute.

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

    Uses a bidirectional bubble sort.  Items in string1 are not referenced
    so in principle they may be any comparable objects.   The sorting depends on the
    operators '>' and '=='.

    If the Pauli principle is violated, an exception is raised.

    Returns
    =======

    tuple (sorted_str, sign)

    sorted_str: list containing the sorted operators
    sign: int telling how many times the sign should be changed
          (if sign==0 the string was already sorted)
    Fr   r\   r   r   Trv   )r  r]  r  r`   dictrq  rK   )string1ru   verifiedr*  rngrevkeyskey_valr   leftrightr   s               rD   rw   rw     sl   , HD
uS\A%&
'C
uS\A%r2.
/CC!"D4D'*+,G 	 A7DQKEu}/u>>e| !&Qq1uax	   	 A7DQKEu}/u>>e| !&Qq1uax	  , %)*q
*G*T? +s   Dc                 <   t         f}t        | |      r0 | j                  | j                  D cg c]  }t	        |       c} S t        | t
              rBg }i }| j                  D ]L  }|j                  D ]  }||v r||xx   dz  cc<   d||<    t        |t              s<|j                  |       N |D ]  }|j                  j                  rQ||j                     rB| j                  |j                  |j                        } t        |      dkD  s]t	        |       c S |j                  j                  r]||j                     rN|j                  rB| j                  |j                  |j                        } t        |      dkD  st	        |       c S  | S | S c c}w )a  
    We evaluate KroneckerDelta symbols in the expression assuming Einstein summation.

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

    If one index is repeated it is summed over and in effect substituted with
    the other one. If both indices are repeated we substitute according to what
    is the preferred index.  this is determined by
    KroneckerDelta.preferred_index and KroneckerDelta.killable_index.

    In case there are no possible substitutions or if a substitution would
    imply a loss of information, nothing is done.

    In case an index appears in more than one KroneckerDelta, the resulting
    substitution depends on the order of the factors.  Since the ordering is platform
    dependent, the literal expression resulting from this function may be hard to
    predict.

    Examples
    ========

    We assume the following:

    >>> from sympy import symbols, Function, Dummy, KroneckerDelta
    >>> from sympy.physics.secondquant import evaluate_deltas
    >>> i,j = symbols('i j', below_fermi=True, cls=Dummy)
    >>> a,b = symbols('a b', above_fermi=True, cls=Dummy)
    >>> p,q = symbols('p q', cls=Dummy)
    >>> f = Function('f')
    >>> t = Function('t')

    The order of preference for these indices according to KroneckerDelta is
    (a, b, i, j, p, q).

    Trivial cases:

    >>> evaluate_deltas(KroneckerDelta(i,j)*f(i))       # d_ij f(i) -> f(j)
    f(_j)
    >>> evaluate_deltas(KroneckerDelta(i,j)*f(j))       # d_ij f(j) -> f(i)
    f(_i)
    >>> evaluate_deltas(KroneckerDelta(i,p)*f(p))       # d_ip f(p) -> f(i)
    f(_i)
    >>> evaluate_deltas(KroneckerDelta(q,p)*f(p))       # d_qp f(p) -> f(q)
    f(_q)
    >>> evaluate_deltas(KroneckerDelta(q,p)*f(q))       # d_qp f(q) -> f(p)
    f(_p)

    More interesting cases:

    >>> evaluate_deltas(KroneckerDelta(i,p)*t(a,i)*f(p,q))
    f(_i, _q)*t(_a, _i)
    >>> evaluate_deltas(KroneckerDelta(a,p)*t(a,i)*f(p,q))
    f(_a, _q)*t(_a, _i)
    >>> evaluate_deltas(KroneckerDelta(p,q)*f(p,q))
    f(_p, _p)

    Finally, here are some cases where nothing is done, because that would
    imply a loss of information:

    >>> evaluate_deltas(KroneckerDelta(i,p)*f(q))
    f(_q)*KroneckerDelta(_i, _p)
    >>> evaluate_deltas(KroneckerDelta(i,p)*f(i))
    f(_i)*KroneckerDelta(_i, _p)
    r\   r   )r   rT   funcra   r7   r
   free_symbolsr   r  killable_index	is_Symbolrg  preferred_indexr  !indices_contain_equal_information)rh  accepted_functionsrW   deltasr  r   sds           rD   r7   r7     s   N 	 !'(qvv?,?@@	As	  	!A^^ #<AJ!OJ!"GAJ	#
 !^,a 	!  	A ))ga6F6F.GFF1++Q->->?v;?*1--##--'!:K:K2L99FF1,,a.>.>?v;?*1--	  E @s   FFc                     |ri|j                  dd      |j                  dd      |j                  dd       t              t              t               fd}fd} fd}g }g }g }| j                  t              }	|st	        |	t
              }	d	x}
x}}|	D ]  }|j                  }|j                  d
      r|r |
      }|
dz  }
|}n4|j                  d      r|r |      }|dz  }|}n|r |      }|dz  }|}|r|j                  t        fi |       |j                  |        | j                         } t        j                  |       }g }|D ]R  }t        |      }t        |      }
t        |      }t        |      }i }|D ]d  }|j                  j                  d      rt        |      ||<   -|j                  j                  d
      rt        |
      ||<   Wt        |      ||<   f g }g }|j                         D ]p  \  }}||k(  r||v rN||   |v r2t        d      }|j                  ||f       |j                  ||f       I|j                  d	||f       ^|j                  ||f       r |j!                  |       |j                  |j#                  |             U t        | S )aG	  
    Collect terms by substitution of dummy variables.

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

    This routine allows simplification of Add expressions containing terms
    which differ only due to dummy variables.

    The idea is to substitute all dummy variables consistently depending on
    the structure of the term.  For each term, we obtain a sequence of all
    dummy variables, where the order is determined by the index range, what
    factors the index belongs to and its position in each factor.  See
    _get_ordered_dummies() for more information about the sorting of dummies.
    The index sequence is then substituted consistently in each term.

    Examples
    ========

    >>> from sympy import symbols, Function, Dummy
    >>> from sympy.physics.secondquant import substitute_dummies
    >>> a,b,c,d = symbols('a b c d', above_fermi=True, cls=Dummy)
    >>> i,j = symbols('i j', below_fermi=True, cls=Dummy)
    >>> f = Function('f')

    >>> expr = f(a,b) + f(c,d); expr
    f(_a, _b) + f(_c, _d)

    Since a, b, c and d are equivalent summation indices, the expression can be
    simplified to a single term (for which the dummy indices are still summed over)

    >>> substitute_dummies(expr)
    2*f(_a, _b)


    Controlling output:

    By default the dummy symbols that are already present in the expression
    will be reused in a different permutation.  However, if new_indices=True,
    new dummies will be generated and inserted.  The keyword 'pretty_indices'
    can be used to control this generation of new symbols.

    By default the new dummies will be generated on the form i_1, i_2, a_1,
    etc.  If you supply a dictionary with key:value pairs in the form:

        { index_group: string_of_letters }

    The letters will be used as labels for the new dummy symbols.  The
    index_groups must be one of 'above', 'below' or 'general'.

    >>> expr = f(a,b,i,j)
    >>> my_dummies = { 'above':'st', 'below':'uv' }
    >>> substitute_dummies(expr, new_indices=True, pretty_indices=my_dummies)
    f(_s, _t, _u, _v)

    If we run out of letters, or if there is no keyword for some index_group
    the default dummy generator will be used as a fallback:

    >>> p,q = symbols('p q', cls=Dummy)  # general indices
    >>> expr = f(p,q)
    >>> substitute_dummies(expr, new_indices=True, pretty_indices=my_dummies)
    f(_p_0, _p_1)

    r  r   r  generalc                 P    	 |    S # t         $ r dt        | z
        z   cY S w xY w)Ni_
IndexErrorr   )number	len_belowletters_belows    rD   _izsubstitute_dummies.<locals>._i	  7    6$V,, 6c&9"45556    %%c                 P    	 |    S # t         $ r dt        | z
        z   cY S w xY w)Na_r  )r  	len_aboveletters_aboves    rD   _azsubstitute_dummies.<locals>._a	  r  r  c                 P    	 |    S # t         $ r dt        | z
        z   cY S w xY w)Np_r  )r  len_generalletters_generals    rD   _pzsubstitute_dummies.<locals>._p	  s7    8&v.. 8c&;"67778r  rt   r   r   r\   r   x)r   r  re  r   sortedr   r   r  rd  r   	make_argsrf  _get_ordered_dummiesnextitemsinsertr  rg  )!exprnew_indicespretty_indicesr  r  r  abovesbelowsgeneralsdummiesr-  r   pr  assumsyml1terms	new_termsr  orderedsubsdictr  
final_subsr   vr  r  r  r  r  r  r  s!                              @@@@@@rD   r9   r9   ^	  s   F &**7B7&**7B7(,,Y;&	&	/*	6	6	8 FFHjjG&67 MAMA 99]#eQBYY}%eQBeQBIIeC)5)*IIaL-0 ;;=DMM$EI ".LLN&t, 	&A~~!!-0"1g##M2"1g"1g	& 
NN$ 	(DAqAvH} A;(*c
AOOQF+%%q!f- %%a!Q0A'#	($ 	
#8,-E".F 	?rC   c                       e Zd ZdZd Zy)
KeyPrinterz7Printer for which only equal objects are equal in printc                 8    d|j                   |j                  fz  S )Nz(%s_%i))r   dummy_index)rk   r$  s     rD   _print_DummyzKeyPrinter._print_Dummy
  s    DIIt'7'7888rC   N)r?   r@   rA   rm   r9  rB   rC   rD   r6  r6  
  s
    A9rC   r6  c                 8    t               }|j                  |       S rR   )r6  doprint)r$  r+  s     rD   __kprintr<  
  s    A99T?rC   c                   
 t        j                  |       }|D ci c]  }||j                  t               c}|D ci c]  }|t	        |       c} t               j                  j                          }i |D ]I  }|j                  j                  d      rd|<   $|j                  j                  d      rd|<   Ed|<   K |D ci c]  }|t	        |       c}

fd}t        t        t        |t        t        ||                              t        |fd      }t        t!        j                                     rt#        t
              }j%                         D ]  \  }}	||	   j'                  |        |D 	cg c]  }	t)        ||	         d	k  s|	 c}	D ]  }	||	=  t        |      D 	cg c]  }	||	   	 }}	t+        | ||      }|S c c}w c c}w c c}w c c}	w c c}	w )
a  Returns all dummies in the mul sorted in canonical order.

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

    The purpose of the canonical ordering is that dummies can be substituted
    consistently across terms with the result that equivalent terms can be
    simplified.

    It is not possible to determine if two terms are equivalent based solely on
    the dummy order.  However, a consistent substitution guided by the ordered
    dummies should lead to trivially (non-)equivalent terms, thereby revealing
    the equivalence.  This also means that if two terms have identical sequences of
    dummies, the (non-)equivalence should already be apparent.

    Strategy
    --------

    The canonical order is given by an arbitrary sorting rule.  A sort key
    is determined for each dummy as a tuple that depends on all factors where
    the index is present.  The dummies are thereby sorted according to the
    contraction structure of the term, instead of sorting based solely on the
    dummy symbol itself.

    After all dummies in the term has been assigned a key, we check for identical
    keys, i.e. unorderable dummies.  If any are found, we call a specialized
    method, _determine_ambiguous(), that will determine a unique order based
    on recursive calls to _get_ordered_dummies().

    Key description
    ---------------

    A high level description of the sort key:

        1. Range of the dummy index
        2. Relation to external (non-dummy) indices
        3. Position of the index in the first factor
        4. Position of the index in the second factor

    The sort key is a tuple with the following components:

        1. A single character indicating the range of the dummy (above, below
           or general.)
        2. A list of strings with fully masked string representations of all
           factors where the dummy is present.  By masked, we mean that dummies
           are represented by a symbol to indicate either below fermi, above or
           general.  No other information is displayed about the dummies at
           this point.  The list is sorted stringwise.
        3. An integer number indicating the position of the index, in the first
           factor as sorted in 2.
        4. An integer number indicating the position of the index, in the second
           factor as sorted in 2.

    If a factor is either of type AntiSymmetricTensor or SqOperator, the index
    position in items 3 and 4 is indicated as 'upper' or 'lower' only.
    (Creation operators are considered upper and annihilation operators lower.)

    If the masked factors are identical, the two factors cannot be ordered
    unambiguously in item 2.  In this case, items 3, 4 are left out.  If several
    indices are contracted between the unorderable factors, it will be handled by
    _determine_ambiguous()


    r   0r   12c           	         D cg c]  }| |   v s| }} t               j                  |D cg c]  }|   	 c} }|d   }||   u r|   j                         }|j                  |        |D cg c]  }|   	 }}|D ]'  }|D cg c]  }|j	                  |   |          }}) |D cg c]  }|j	                  |    |           }}t        t        t        ||                  }t        |      r |j                          |    t        |      fS t        t        t        ||                  |j                  fd       |j                          g }|D ]9  }t        |t              r@| |j                  v r|j                  d       | |j                  v sB|j                  d       Tt        |t               r|j                  d       vt        |t"              r|j                  d       t        |t$              r]|D cg c]  }|j'                  |       s| }	}|	D ]5  }t        |t               r|j                  d       %|j                  d       7 d}
	 ||   j)                  |    |
dz         }
|
dk(  r*|j                  |
       4 |    t        |      |d   |d   fS c c}w c c}w c c}w c c}w c c}w c c}w )Nr   c                     |    S rR   rB   )r  keydicts    rD   <lambda>z4_get_ordered_dummies.<locals>._key.<locals>.<lambda>w
  s    WQZ rC   rt   ulr\   r   )setunioncopyremovereplacer  r  rq  r   sortr_   rT   r8   r{   r  r|   r   r   r6   hasfind)r  r  	dumstruct
other_dumsmasked_facsd2
all_maskedpos_valr|  r  facposrC  dum_reprfac_dumfac_reprmasks              @rD   _keyz"_get_ordered_dummies.<locals>._keya
  s   %,CcWS\0AcC	C SU[[9"EC73<"EF
m% **,J!1:<#<< 	-B*-  KKd2h? -K -	- #.0 {{8A;Q8 0
 04I{ ;<= JOO7E*--- tC	:678/0 	+C#23		>NN3'		>NN3'C)s#C-s#C$%(7rBFF1I77 ,B!"g.s+s+	, (-228A;
KF|NN6*	 )	+2 Qz*GAJDDe D"E
 =-04 8s-   J:J:J?6KK	4KK(Kc                     |    S rR   rB   )r  dumkeys    rD   rD  z&_get_ordered_dummies.<locals>.<lambda>
  s    F1I rC   rt   rv   )r
   r  re  r   r<  rG  rH  valuesr   r   r  r  rq  r`   r  r   rf  r   r"  addr  _determine_ambiguous)r  verbosera   r  all_dumsr  rZ  rb  	unorderedr   rV  r\  rW  rX  rY  s             @@@@@rD   r   r   
  s   D ==D157#SYYu%%7G/35hsm#5Hsu{{GNN,-HD >>m,DG^^.DGDG )1118A;1H3Eh $s8T#dH*=%>?@AFH"56FV]]_%&$	LLN 	 DAqaLQ	 'B3y|+<q+@1B 	A!	 -39,=?qil?	?%c69=M[ 85 2z C @s#   G"G'G,G1)G1G6c                    t               }|D ]  }||z  }	 t        |      |z
  }|sA|D cg c]  }||d   v s| }}|d   }|j                  |       |d   j                  |       t        j                  }g }	|D cg c]	  }||v s| c}D ])  }t        j                         }
|	j                  ||
f       + | j                  |	      }t        |      }t        j                  |       |D ]f  }|D cg c]	  }||v s| }}|j                          g }|D ]7  }||v r |j                  |j                                '|j                  |       9 |}h |S c c}w c c}w c c}w rh   )rG  r^  rJ  _symbol_factory_counter_nextr  rg  r   _set_counterreverser  )r  r1  ambiguous_groupsall_ambiguousr*  all_orderedr  groupstored_counterr  nondumnewtermneworderordered_grouprb  s                  rD   r_  r_  
  s   $ EM# ! !g,.K %B-=a-@(@!BB!H""1%$--NH!7QQ+%5q7 % &&(F$% ii!G#G,H  0 " 	%-=e!== 	!AEzm//12a 		!
 	 N3 C 8 >s"   EE>	EE5	E#?E#c                   .    e Zd Zd Zd Zed        Zd Zy)_SymbolFactoryc                      d| _         || _        y rh   )_counterVar_label)rk   r   s     rD   r  z_SymbolFactory.__init__
  s    rC   c                     || _         y)z(
        Sets counter to value.
        Nru  )rk   values     rD   rg  z_SymbolFactory._set_counter
  s     !rC   c                     | j                   S )z/
        What counter is currently at.
        rx  rj   s    rD   re  z_SymbolFactory._counter
  s    
 rC   c                 x    t        d| j                  | j                  fz        }| xj                  dz  c_        |S )zI
        Generates the next symbols and increments counter by 1.
        z%s%ir\   )r   rv  ru  )rk   r  s     rD   rf  z_SymbolFactory._next
  s8     6T[[$*:*:;;<ArC   N)r?   r@   rA   r  rg  r   re  rf  rB   rC   rD   rs  rs  
  s%    !    rC   rs  z_]"]_c                    |r| rg }nt        t        |        g}t        t        |       dz
        D ]  }t        |dz   t        |             D ]  }t	        | |   | |         }|s||z
  dz   dz  }|rt
        j                  |z  }n|}| |dz   | | |dz   d z   }|r5|j                  |t        t        | d|  t        ||      z        z         |j                  |t        t        | d|        z          |s t        | S  t        | S )z
    Returns Add-object with contracted terms.

    Uses recursion to find all contractions. -- Internal helper function --

    Will find nonzero contractions in string1 between indices given in
    leftrange and rightrange.

    r\   rv   Nkeep_only_fully_contracted)
r6   r
   r]  r  r4   r   r)  r  _get_contractionsr   )	r  r~  rb  r   rr  cr*  r  oplists	            rD   r  r  
  sA    "gS']#$3w<!#$ &q1uc'l+ "	@AGAJ
3AA	QMM!OEE  !Qq)GAEFO;MM%WRa[)*;V7Q+S S)T #T U
 MM%C!,=(>">?E"	@H &<Q&P <rC   c                    | st         j                  S ddddd}|j                  |       t        | t              r|d   rt         j                  S | S t        | t
              r|d   rt         j                  S | S | j                  d      } | j                         } t        | t              rb|d   r3t        t        | j                  D cg c]  }t        |fi | c}       S t        | j                  D cg c]  }t        |fi | c} S t        | t              rg }g }| j                  D ]1  }|j                  r|j                  |       !|j                  |       3 t        |      }|dk(  r| }n\|dk(  r|d   rt         j                  S | }n?t        |d   t               rt"        t%        |      }t'        ||d   	      }t        | |z  }|d
   r|j                         }|d   rt)        |      }|S | S c c}w c c}w )a  
    Returns the normal ordered equivalent of an expression using Wicks Theorem.

    Examples
    ========

    >>> from sympy import symbols, Dummy
    >>> from sympy.physics.secondquant import wicks, F, Fd
    >>> p, q, r = symbols('p,q,r')
    >>> wicks(Fd(p)*F(q))
    KroneckerDelta(_i, q)*KroneckerDelta(p, q) + NO(CreateFermion(p)*AnnihilateFermion(q))

    By default, the expression is expanded:

    >>> wicks(F(p)*(F(q)+F(r)))
    NO(AnnihilateFermion(p)*AnnihilateFermion(q)) + NO(AnnihilateFermion(p)*AnnihilateFermion(r))

    With the keyword 'keep_only_fully_contracted=True', only fully contracted
    terms are returned.

    By request, the result can be simplified in the following order:
     -- KroneckerDelta functions are evaluated
     -- Dummy variables are substituted consistently across terms

    >>> p, q, r = symbols('p q r', cls=Dummy)
    >>> wicks(Fd(p)*(F(q)+F(r)), keep_only_fully_contracted=True)
    KroneckerDelta(_i, _q)*KroneckerDelta(_p, _q) + KroneckerDelta(_i, _r)*KroneckerDelta(_p, _r)

    FT)simplify_kronecker_deltasrd  simplify_dummiesr~  r~  )r5   r  r   r\   r}  rd  r  )r   ry   updaterT   r6   r   r  rd  r   r9   ra   r5   r
   rq   r  r  r   r   r_   r  r7   )	rh  kw_argsoptsr  r   r  factornrb  s	            rD   r5   r5   6  s   > vv &+!&+	D 	KK !R,-66MH	A(	),-66MH 	
TA 	

A!S"#%cPQPVPV+WU4-C7-C+W&XYYQVVDT%00DEE !S ff 	'F$$f%v&		'
 L 6F!V01vv '!*o6))GnG 'w+/0L+MPF&\&(F>]]_F+,$V,F H_ ,XDs   G96G>c                   &    e Zd ZdZdZd Zd Zd Zy)r:   zg
    Represents the index permutation operator P(ij).

    P(ij)*f(i)*g(j) = f(i)*g(j) - f(j)*g(i)
    Tc                 |    t        t        t        ||f      t              \  }}t	        j
                  | ||      }|S )Nrt   )r  r`   r   r   r   rU   )rV   r   rr  rY   s       rD   rU   zPermutationOperator.__new__  s5    c'Aq6*0@A1mmCA&
rC   c                 ,   | j                   d   }| j                   d   }|j                  |      rd|j                  |      rSt               }|j                  ||      }|j                  ||      }|j                  ||      }t        j
                  |z  S |S )aa  
        Returns -expr with permuted indices.

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

        >>> from sympy import symbols, Function
        >>> from sympy.physics.secondquant import PermutationOperator
        >>> p,q = symbols('p,q')
        >>> f = Function('f')
        >>> PermutationOperator(p,q).get_permuted(f(p,q))
        -f(q, p)

        r   r\   )ra   rM  r   rg  r   r)  )rk   r$  r   rr  tmps        rD   get_permutedz PermutationOperator.get_permuted  s}     IIaLIIaL88A;488A;'C99Q$D99Q?D99S!$D==%%KrC   c                      d| j                   z  S )NzP(%s%s)ri   r   s     rD   r   zPermutationOperator._latex  s    499$$rC   N)r?   r@   rA   rm   rq   rU   r  r   rB   rC   rD   r:   r:     s    
 N
4%rC   r:   c                    fdfd}| j                         } t        | t              rt        | j                        }|D ]  }t               }t               }|r|j                         }|j                  |      }|||z  v r;	 |j                  |        ||||j                        }	|j                  ||	z         nw|}
t        |      }|
|k(  r|j                  |       nS|||z  v r;	 |j                  |        ||||j                        }	|j                  ||	z         n|j                  |       |r||z  } t        | S | S # t        $ r |j                  |       Y w xY w# t        $ r |j                  |       Y w xY w)a  
    Performs simplification by introducing PermutationOperators where appropriate.

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

    Schematically:
        [abij] - [abji] - [baij] + [baji] ->  P(ab)*P(ij)*[abij]

    permutation_operators is a list of PermutationOperators to consider.

    If permutation_operators=[P(ab),P(ij)] we will try to introduce the
    permutation operators P(ij) and P(ab) in the expression.  If there are other
    possible simplifications, we ignore them.

    >>> from sympy import symbols, Function
    >>> from sympy.physics.secondquant import simplify_index_permutations
    >>> from sympy.physics.secondquant import PermutationOperator
    >>> p,q,r,s = symbols('p,q,r,s')
    >>> f = Function('f')
    >>> g = Function('g')

    >>> expr = f(p)*g(q) - f(q)*g(p); expr
    f(p)*g(q) - f(q)*g(p)
    >>> simplify_index_permutations(expr,[PermutationOperator(p,q)])
    f(p)*g(q)*PermutationOperator(p, q)

    >>> PermutList = [PermutationOperator(p,q),PermutationOperator(r,s)]
    >>> expr = f(p,r)*g(q,s) - f(q,r)*g(p,s) + f(q,s)*g(p,r) - f(p,s)*g(q,r)
    >>> simplify_index_permutations(expr,PermutList)
    f(p, r)*g(q, s)*PermutationOperator(p, q)*PermutationOperator(r, s)

    c                     g }| j                   D ]=  }||v r|j                  |       |j                   s&|j                   ||             ? |S )zD
        Collects indices recursively in predictable order.
        )ra   r  r  )r$  indrb  rW   _get_indicess       rD   r  z1simplify_index_permutations.<locals>._get_indices  sQ     99 	:Cczc"88MM,sC"89	: rC   c                 *    t        | |fd      S )Nc                 (    t         |             S rR   r   )r  r  r  s    rD   rD  zJsimplify_index_permutations.<locals>._choose_one_to_keep.<locals>.<lambda>  s    '7Q8L'M rC   rt   )min)r-  r   r  r  s     `rD   _choose_one_to_keepz8simplify_index_permutations.<locals>._choose_one_to_keep   s    1aMNNrC   )rd  rT   r   rG  ra   r  r  rJ  KeyErrorr^  r9   )r$  permutation_operatorsr  r/  Pr0  on_holdr  permutedkeep	permuted1r  s              @rD   r;   r;     s|   FO ;;=D$DII&  	(AIeGyy{>>$/uw.1X. /tXqvvFDMM!D&) !)I1(;H H,D)!UW_45!LL2  34166J!af-!d+9 : 'EA 	(B E{K3 $ 1x01"  ( 5#NN845s$   E,E+E('E(+FFN)F)erm   collectionsr   sympy.core.addr   sympy.core.basicr   sympy.core.cacher   sympy.core.containersr   sympy.core.exprr   sympy.core.functionr	   sympy.core.mulr
   sympy.core.numbersr   sympy.core.powerr   sympy.core.singletonr   sympy.core.sortingr   sympy.core.symbolr   r   sympy.core.sympifyr   (sympy.functions.elementary.miscellaneousr   (sympy.functions.special.tensor_functionsr   sympy.matrices.denser   sympy.printing.strr   sympy.utilities.iterablesr   __all__	Exceptionr=   rG   rI   rK   rM   rO   r   rp   r8   r   r   r   r   r   r   r+   r,   r   r   r   r*   r)   r   r  r%  r    r   r!   r"   r#   r$   r%   r&   r'   r(   rZ  r-   r.   r3   r/   r0   r1   r2   r6   r4   r  rw   r7   r9   r6  r<  r   r_  rs  rd  r  r5   r:   r;   rB   rC   rD   <module>r     s   $  " $ '   (      " / + & 9 C & ) .&R	i 		!8 		'> 		 7 		+B 		6 	@T @F4 
H', H'VDL DLN	j 		* 		j 	0.o{ 0.d'9/7 '9R `
 `FU.); U.pR9%w R9h +E +E\,, ,,^F09 F0R&9 &-9 - -
L -"-
L -/, /6/, /" >B$/5 /d2	 	@  @ FO  O dQ7 Q7hR% R%j
E3P"
 /5 5pl^ */r eP9 9
Pf6r 2 !) 	9 	9xl^(%$ (%VZrC   