
    \h^c                       S r SSKJr  SSKJr  SSKJr  SSKJr  SSK	J
r
  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJrJr  SSKJr  SSKJr  SSK J!r!  SSK"J#r#  SSK$J%r%  SSK&J'r'  SSK(J)r)  / SQr* " S S\+5      r, " S S\,5      r- " S S\,5      r. " S S\,5      r/ " S S \,5      r0 " S! S"\,5      r1 " S# S$\5      r2 " S% S&\5      r3 " S' S(\35      r4 " S) S*\5      r5 " S+ S,\55      r6 " S- S.\55      r7 " S/ S0\55      r8 " S1 S2\6\75      r9 " S3 S4\6\85      r:\9r;\:r< " S5 S6\55      r= " S7 S8\=\75      r> " S9 S:\=\85      r?\?r@\>rA " S; S<\5      rB " S= S>\B5      rC " S? S@\B5      rD " SA SB\B5      rE " SC SD\B5      rF " SE SF\C\E5      rG " SG SH\C\F5      rH " SI SJ\D\E5      rI " SK SL\D\F5      rJ\HrK\GrL\JrM\IrNSM rOSN rP " SO SP\5      rQSQ rR " SR SS5      rS " ST SU5      rT " SV SW\S5      rU " SX SY\5      rV " SZ S[\5      rWS\ rXS] rYS^ rZ\Y4S_ jr[S` r\Sa0 4Sb jr] " Sc Sd\'5      r^Se r_SqSf jr`Sg ra " Sh Si5      rb\b" Sj5      rc\SqSk j5       rdSl re " Sm Sn\5      rfSo rggp)rz
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)	conjugate)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                       \ rS rSrSrg)SecondQuantizationErrorF    N__name__
__module____qualname____firstlineno____static_attributes__r@       Q/var/www/auris/envauris/lib/python3.13/site-packages/sympy/physics/secondquant.pyr>   r>   F       rG   r>   c                       \ rS rSrSrg)AppliesOnlyToSymbolicIndexJ   r@   NrA   r@   rG   rH   rK   rK   J   rI   rG   rK   c                       \ rS rSrSrg) ContractionAppliesOnlyToFermionsN   r@   NrA   r@   rG   rH   rN   rN   N   rI   rG   rN   c                       \ rS rSrSrg)ViolationOfPauliPrincipleR   r@   NrA   r@   rG   rH   rQ   rQ   R   rI   rG   rQ   c                       \ rS rSrSrg)$SubstitutionOfAmbigousOperatorFailedV   r@   NrA   r@   rG   rH   rT   rT   V   rI   rG   rT   c                       \ rS rSrSrg)WicksTheoremDoesNotApplyZ   r@   NrA   r@   rG   rH   rW   rW   Z   rI   rG   rW   c                   4    \ rS rSrSrS r\S 5       rS rSr	g)r   ^   z
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                     [        U5      nU R                  U5      n[        U[        5      (       a  U$ [        R                  " X5      nU$ N)r   eval
isinstancer   __new__)clsargrobjs       rH   r_   Dagger.__new__p   s=    clHHSMaHmmC%
rG   c           
      V   [        USS5      nUb  U" 5       $ [        U[        5      (       a  UR                  (       a  [	        U5      $ [        U[
        5      (       a  UR                  (       a)  [        [        [        [        UR                  5      5      6 $ UR                  (       a2  [        [        [        [        [        UR                  5      5      5      6 $ UR                  (       a  U$ UR                   (       a/  [#        [        UR                  S   5      UR                  S   5      $ U[$        :X  a  U* $ [        U[&        5      (       aU  [)        S UR                   5       5      (       a3  UR*                  " UR                   Vs/ s H  n[        U5      PM     sn6 $ ggs  snf )a  
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      c              3   8   #    U  H  oR                   v   M     g 7fr\   )is_commutative).0as     rH   	<genexpr>Dagger.eval.<locals>.<genexpr>   s     6X##Xs   )getattrr^   r   ri   r   r   is_Addr   tuplemapr   argsis_Mulr
   reversed	is_Numberis_Powr   r   r	   allfunc)r`   ra   daggerrk   s       rH   r]   Dagger.evalx   s.   ( j$/8Oc6""s'9'9S>!c5!!zzE#fchh"7899zzE#fhsxx.@"ABCC}}
zz6#((1+.<<axtc8$$6SXX666xxSXX!>X&)X!>?? 7  "?s   F&c                      U R                   S   $ Nr   rr   selfs    rH   rf   Dagger._dagger_       yy|rG   r@   N)
rB   rC   rD   rE   __doc__r_   classmethodr]   rf   rF   r@   rG   rH   r   r   ^   s&    " ' 'RrG   r   c                       \ rS rSrSrSrg)TensorSymbol   Tr@   N)rB   rC   rD   rE   ri   rF   r@   rG   rH   r   r      s    NrG   r   c                   Z    \ rS rSrSrS rS r\S 5       r\S 5       r	\S 5       r
S rS	rg
)r9      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                 ,    [        U[        S9u  p$[        U[        S9u  p5[        U5      n[        U6 n[        U6 nXE-   S-  (       a  [        R                  XX#5      * $ [        R                  XX#5      $ ! [         a    [        R                  s $ f = f)Nkey   )	_sort_anticommuting_fermions_sqkey_indexrQ   r   Zeror   r   r   r_   )r`   symbolupperlowersignusignls         rH   r_   AntiSymmetricTensor.__new__   s    	7<)LE7<)LE uuMQ ((eCCC  ''UBB ) 	66M	s    A6 6BBc                 4   SU R                   < SSR                  U R                  S    Vs/ s H  o!R                  U5      PM     sn5      < SSR                  U R                  S    Vs/ s H  o!R                  U5      PM     sn5      < S3$ s  snf s  snf )N{z^{ rg   z}_{r   z}})r   joinrr   _print)r   printeris      rH   _latexAntiSymmetricTensor._latex   sm    KKGG1>AnnQ'>?GG1>AnnQ'>?
 	
>>s   B+Bc                      U R                   S   $ )av  
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   r}   r~   s    rH   r   AntiSymmetricTensor.symbol       $ yy|rG   c                      U R                   S   $ )at  
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)


rg   r}   r~   s    rH   r   AntiSymmetricTensor.upper   s    & yy|rG   c                      U R                   S   $ )as  
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)

r   r}   r~   s    rH   r   AntiSymmetricTensor.lower  r   rG   c                      SU R                   -  $ )Nz	%s(%s,%s)r}   r~   s    rH   __str__AntiSymmetricTensor.__str__  s    TYY&&rG   r@   N)rB   rC   rD   rE   r   r_   r   propertyr   r   r   r   rF   r@   rG   rH   r9   r9      sS    (C*
  &  (  &'rG   r9   c                   X    \ rS rSrSrSrSrS r\S 5       r	\S 5       r
S rS	 rS
 rSrg)
SqOperatori  z/
Base class for Second Quantization operators.
sqFc                 F    [         R                  " U [        U5      5      nU$ r\   )r   r_   r   )r`   krc   s      rH   r_   SqOperator.__new__&  s    mmC,
rG   c                      U R                   S   $ )z
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   r}   r~   s    rH   stateSqOperator.state*  s    * yy|rG   c                 <    U R                   R                  (       a  gg)z
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_Integerr~   s    rH   is_symbolicSqOperator.is_symbolicA  s    " ::  rG   c                     [         $ r\   )NotImplementedr~   s    rH   __repr__SqOperator.__repr__W  s    rG   c                 >    U R                   < SU R                  < S3$ )N())	op_symbolr   r~   s    rH   r   SqOperator.__str__Z  s    >>4::66rG   c                     [        S5      e)z 
Applies an operator to itself.
z&implement apply_operator in a subclass)NotImplementedErrorr   r   s     rH   apply_operatorSqOperator.apply_operator]  s     ""JKKrG   r@   N)rB   rC   rD   rE   r   r   ri   r_   r   r   r   r   r   r   rF   r@   rG   rH   r   r     sP     IN  ,  *7LrG   r   c                       \ rS rSrSrg)r   id  r@   NrA   r@   rG   rH   r   r   d  rI   rG   r   c                       \ rS rSrSrg)Annihilatorih  r@   NrA   r@   rG   rH   r   r   h  rI   rG   r   c                       \ rS rSrSrg)Creatoril  r@   NrA   r@   rG   rH   r   r   l  rI   rG   r   c                   4    \ rS rSrSrSrS rS rS rS r	Sr
g	)
r   ip  z
Bosonic annihilation operator.

Examples
========

>>> from sympy.physics.secondquant import B
>>> from sympy.abc import x
>>> B(x)
AnnihilateBoson(x)
bc                 ,    [        U R                  5      $ r\   )r   r   r~   s    rH   rf   AnnihilateBoson._dagger_  s    4::&&rG   c                     U R                   (       dA  [        U[        5      (       a,  U R                  n[	        X   5      nX1R                  U5      -  $ [        X5      $ )aH  
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   r^   r!   r   r   downr
   r   r   elementamps       rH   r   AnnihilateBoson.apply_operator  sK      Jul$C$CjjGu~&Czz'***t##rG   c                      SU R                   -  $ )NzAnnihilateBoson(%s)r   r~   s    rH   r   AnnihilateBoson.__repr__  s    $tzz11rG   c                 z    U R                   [        R                  L a  gSUR                  U R                   5      -  $ )Nzb_{0}zb_{%s}r   r   r   r   r   r   s     rH   r   AnnihilateBoson._latex  -    ::gnnTZZ888rG   r@   NrB   rC   rD   rE   r   r   rf   r   r   r   rF   r@   rG   rH   r   r   p  s"    
 I'$.29rG   r   c                   4    \ rS rSrSrSrS rS rS rS r	Sr
g	)
r   i  z
Bosonic creation operator.
zb+c                 ,    [        U R                  5      $ r\   )r   r   r~   s    rH   rf   CreateBoson._dagger_  s    tzz**rG   c                     U R                   (       dD  [        U[        5      (       a/  U R                  n[	        X   S-   5      nX1R                  U5      -  $ [        X5      $ )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,))
rg   )r   r^   r!   r   r   upr
   r   s       rH   r   CreateBoson.apply_operator  sP     Jul$C$CjjGu~)*Cxx(((t##rG   c                      SU R                   -  $ )NzCreateBoson(%s)r   r~   s    rH   r   CreateBoson.__repr__  s     4::--rG   c                 z    U R                   [        R                  L a  gSUR                  U R                   5      -  $ )Nz{b^\dagger_{0}}z{b^\dagger_{%s}}r   r   s     rH   r   CreateBoson._latex  -    ::%&

)CCCrG   r@   Nr   r@   rG   rH   r   r     s#     I+$,.DrG   r   c                   j    \ rS rSr\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r	S r
Srg	)
FermionicOperatori  c                     U R                   S   R                  nUR                  S5      (       a  gUR                  S5      (       a  gg)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   below_fermiabove_fermirg   rr   assumptions0get)r   asss     rH   is_restrictedFermionicOperator.is_restricted  s?    F iil''77=!!77=!!rG   c                 \    U R                   S   R                  R                  S5      (       + $ )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   r~   s    rH   is_above_fermi FermionicOperator.is_above_fermi  s&    6 99Q<,,00???rG   c                 \    U R                   S   R                  R                  S5      (       + $ )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   r~   s    rH   is_below_fermi FermionicOperator.is_below_fermi  s&    0 99Q<,,00???rG   c                 J    U R                   =(       a    U R                  (       + $ )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   r~   s    rH   is_only_below_fermi%FermionicOperator.is_only_below_fermi2      . "">4+>+>'>>rG   c                 J    U R                   =(       a    U R                  (       + $ )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   r~   s    rH   is_only_above_fermi%FermionicOperator.is_only_above_fermiK  r   rG   c                    [        U 5      n[        U R                  S   5      nU R                  (       a  SX!4$ U R                  (       a  SX!4$ [        U [        5      (       a  SX!4$ [        U [        5      (       a  SX!4$ g )Nr   rg         r   )hashstrrr   is_only_q_creatoris_only_q_annihilatorr^   r   r   )r   hlabels      rH   _sortkeyFermionicOperator._sortkeyd  sv    JDIIaL!!!e;%%e;dK((e;dG$$e; %rG   r@   N)rB   rC   rD   rE   r   r   r   r   r   r   r  rF   r@   rG   rH   r   r     sn    ' 'R @ @8 @ @2 ? ?0 ? ?0rG   r   c                   t    \ rS rSrSrSrS rS r\S 5       r	\S 5       r
\S 5       r\S	 5       rS
 rS rSrg)r   ir  z"
Fermionic annihilation operator.
fc                 ,    [        U R                  5      $ r\   )r   r   r~   s    rH   rf   AnnihilateFermion._dagger_y  s    TZZ((rG   c                 n   [        U[        5      (       a  U R                  nUR                  U5      $ [        U[        5      (       ad  UR                  5       u  p4[        US   [        5      (       a/  U R                  n[	        X4S   R                  U5      /-   USS -   6 $ [	        X5      $ [	        X5      $ r   r   rg   N)r^   r$   r   r   r
   args_cncr   r   r   c_partnc_parts        rH   r    AnnihilateFermion.apply_operator|  s     e011jjG::g&&s###nn.OF'!*&9::**Vqzw'?&@@712;NPP4'' t##rG   c                 (    U R                   (       a  gg)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   r~   s    rH   is_q_creatorAnnihilateFermion.is_q_creator      . rG   c                 (    U R                   (       a  gg)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

rg   r   r   r~   s    rH   is_q_annihilator"AnnihilateFermion.is_q_annihilator      . rG   c                     U R                   $ )ad  
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   r~   s    rH   r  #AnnihilateFermion.is_only_q_creator      , '''rG   c                     U R                   $ )ay  
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   r~   s    rH   r  'AnnihilateFermion.is_only_q_annihilator  r%  rG   c                      SU R                   -  $ )NzAnnihilateFermion(%s)r   r~   s    rH   r   AnnihilateFermion.__repr__   s    &33rG   c                 z    U R                   [        R                  L a  gSUR                  U R                   5      -  $ )Nza_{0}za_{%s}r   r   s     rH   r   AnnihilateFermion._latex  r   rG   r@   NrB   rC   rD   rE   r   r   rf   r   r   r  r  r  r  r   r   rF   r@   rG   rH   r   r   r  sr     I)$<  4  4 ( (. ( (.49rG   r   c                   t    \ rS rSrSrSrS rS r\S 5       r	\S 5       r
\S 5       r\S	 5       rS
 rS rSrg)r   i
  z
Fermionic creation operator.
zf+c                 ,    [        U R                  5      $ r\   )r   r   r~   s    rH   rf   CreateFermion._dagger_  s     ,,rG   c                 X   [        U[        5      (       a  U R                  nUR                  U5      $ [        U[        5      (       aY  UR                  5       u  p4[        US   [        5      (       a/  U R                  n[	        X4S   R                  U5      /-   USS -   6 $ [	        X5      $ r  )r^   r$   r   r   r
   r  r  s        rH   r   CreateFermion.apply_operator  s     e011jjG88G$$s###nn.OF'!*&9::**Vqz}}W'=&>>LNN4rG   c                 (    U R                   (       a  gg)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

rg   r   r  r~   s    rH   r  CreateFermion.is_q_creator/  r!  rG   c                 (    U R                   (       a  gg)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  r~   s    rH   r  CreateFermion.is_q_annihilatorJ  r  rG   c                     U R                   $ )ah  
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'  r~   s    rH   r  CreateFermion.is_only_q_creatore  r%  rG   c                     U R                   $ )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#  r~   s    rH   r  #CreateFermion.is_only_q_annihilator}  r%  rG   c                      SU R                   -  $ )NzCreateFermion(%s)r   r~   s    rH   r   CreateFermion.__repr__  s    "TZZ//rG   c                 z    U R                   [        R                  L a  gSUR                  U R                   5      -  $ )Nz{a^\dagger_{0}}z{a^\dagger_{%s}}r   r   s     rH   r   CreateFermion._latex  r   rG   r@   Nr-  r@   rG   rH   r   r   
  ss     I- 6  4  4 ( (. ( (.0DrG   r   c                   F    \ rS rSrSrSrS rS rS rS r	S r
S	 rS
 rSrg)r   i  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                 r    [        [        [        U5      5      n[        R                  " U [        U6 5      nU$ )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.
)listrq   r   r   r_   r   )r`   occupationsrc   s      rH   r_   FockState.__new__  s/     3w45mmC!45
rG   c                 <    [        U5      nU R                  S   U   $ r|   )intrr   r   r   s     rH   __getitem__FockState.__getitem__  s    Fyy|ArG   c                      SU R                   -  $ )NzFockState(%r)r}   r~   s    rH   r   FockState.__repr__  s    DII..rG   c                 `    [        U SS5      < U R                  5       < [        U SS5      < 3$ )Nlbracketr   rbracket)rn   _labelsr~   s    rH   r   FockState.__str__  s*    "4R8$,,.'RVXbdfJghhrG   c                      U R                   S   $ r|   r}   r~   s    rH   rN  FockState._labels  r   rG   c                 2    [        U R                  S   5      $ r|   lenrr   r~   s    rH   __len__FockState.__len__  s    499Q<  rG   c                 ~    [        U SS5      < UR                  U R                  5       5      < [        U SS5      < 3$ )Nlbracket_latexr   rbracket_latex)rn   r   rN  r   s     rH   r   FockState._latex  sC    "4)92>t||~@^`ghln~  AC  aD  E  	ErG   r@   N)rB   rC   rD   rE   r   ri   r_   rG  r   r   rN  rU  r   rF   r@   rG   rH   r   r     s3     N/i!ErG   r   c                   $    \ rS rSrSrS rS rSrg)
BosonStatei  z)
Base class for FockStateBoson(Ket/Bra).
c                     [        U5      n[        U R                  S   5      nX!   [        R                  -   X!'   U R                  U5      $ )z
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   )rE  rA  rr   r   One	__class__r   r   new_occss      rH   r   BosonState.up  s@     F		!%kAEE)~~h''rG   c                     [        U5      n[        U R                  S   5      nX!   [        R                  :X  a  [        R                  $ X!   [        R
                  -
  X!'   U R                  U5      $ )z
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   )rE  rA  rr   r   r   r^  r_  r`  s      rH   r   BosonState.down  sW     F		!%;!&& 66M"+-HK>>(++rG   r@   N)rB   rC   rD   rE   r   r   r   rF   r@   rG   rH   r\  r\    s    (&,rG   r\  c                       \ rS rSrSrSrSS jrS rS r\	S 5       r
\	S 5       rS	 rS
 r\	S 5       rS rS rS rSrg)FermionStatei  z+
Base class for FockStateFermion(Ket/Bra).
r   c                    [        [        [        U5      5      n[        U5      S:  a   [	        U[
        S9u  pOSnX l	        U R                  U5      U:  a  [        R                  $ US-  (       a&  [        R                  [        R                  X5      -  $ [        R                  X5      $ ! [         a    [        R                  s $ f = f)Nrg   r   r   r   )rA  rq   r   rT  r   r   rQ   r   r   fermi_level_count_holesNegativeOner   r_   )r`   rB  rh  signs       rH   r_   FermionState.__new__  s    3w45{a&B\'3#d
 D%K(;666M!8==!2!23!DDD$$S66 - vvs   B- -C
	C
c                    XR                   S   ;   nU R                  U5      (       a(  U(       a  [        R                  $ U R	                  U5      $ U R                  U5      (       a(  U(       a  U R                  U5      $ [        R                  $ U(       a'  [        SSS9n[        X5      U R                  U5      -  $ [        SSS9n[        X5      U R	                  U5      -  $ )aE  
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   rk   r   )	rr   _only_above_fermir   r   
_add_orbit_only_below_fermi_remove_orbitr   r   r   r   presentholeparticles        rH   r   FermionState.up  s    @ yy|#!!!$$vvq))##A&&))!,,vvSd3%a.t/A/A!/DDD $7%a24??13EEErG   c                    XR                   S   ;   nU R                  U5      (       a(  U(       a  U R                  U5      $ [        R                  $ U R                  U5      (       a(  U(       a  [        R                  $ U R                  U5      $ U(       a'  [        SSS9n[        X5      U R                  U5      -  $ [        SSS9n[        X5      U R                  U5      -  $ )a  
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   Trn  rk   ro  )	rr   rp  rs  r   r   rr  rq  r   r   rt  s        rH   r   FermionState.downO  s    F yy|#!!!$$))!,,vv##A&&vvq))Sd3%a.tq/AAA $7%a243E3Ea3HHHrG   c                     UR                   (       a  XR                  :*  $ UR                  R                  S5      (       a  gg)zp
Tests if given orbit is only below fermi surface.

If nothing can be concluded we return a conservative False.
r   TF	is_numberrh  r   r   r`   r   s     rH   rr  FermionState._only_below_fermi  s3     ;;''>>m,,rG   c                     UR                   (       a  XR                  :  $ UR                  R                  S5      (       a  gU R                  (       + $ )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   Tr|  r~  s     rH   rp  FermionState._only_above_fermi  s=     ;;&&>>m,,??""rG   c                     [        U R                  S   5      nUR                  U5      nX#	 US-  (       a,  [        R                  U R                  X R                  5      -  $ U R                  X R                  5      $ )zH
Removes particle/fills hole in orbit i. No input tests performed here.
r   r   )rA  rr   indexr   rj  r_  rh  )r   r   ra  poss       rH   rs  FermionState._remove_orbit  sc     		!%nnQM19==:J:J!KKK>>(,<,<==rG   c                 \    U R                  U4U R                  S   -   U R                  5      $ )zG
Adds particle/creates hole in orbit i. No input tests performed here.
r   )r_  rr   rh  rF  s     rH   rq  FermionState._add_orbit  s*     ~~qdTYYq\143C3CDDrG   c                 r    [        U Vs/ s H  o R                  U5      (       d  M  UPM     sn5      $ s  snf )zC
Returns the number of identified hole states in occupations list.
)rT  rr  )r`   rB  r   s      rH   ri  FermionState._count_holes  s,    
 {G{!.C.CA.FA{GHHGs   44c                     [        U Vs/ s H.  o R                  U5      (       a  UR                  (       a  U* OUPM0     sn5      $ s  snf )z
Returns the occupations list where states below the fermi level have negative labels.

For symbolic state labels, no sign is included.
)rp   rr  r}  )r   rB  r   s      rH   _negate_holesFermionState._negate_holes  s@     VabVaQR22155!++qb1LVabccbs   5Ac                     U R                   (       a"  SU R                  S   < SU R                   < S3$ SU R                  S   < S3$ )NzFockStateKet(r   z, fermi_level=r   )rh  rr   r~   s    rH   r   FermionState.__repr__  s?    9=1tGWGWXX  *.177rG   c                 >    U R                  U R                  S   5      $ r|   )r  rr   r~   s    rH   rN  FermionState._labels  s    !!$))A,//rG   r@   N)r   )rB   rC   rD   rE   r   rh  r_   r   r   r   rr  rp  rs  rq  ri  r  r   rN  rF   r@   rG   rH   rf  rf    sz     K7*2Fh6Ip 
 
 # #
>E I Id80rG   rf  c                   (    \ rS rSrSrSrSrSrSrSr	g)	r!   i  z
Representation of a ket.
|>z\left|z\right\rangler@   N)
rB   rC   rD   rE   r   rL  rM  rX  rY  rF   r@   rG   rH   r!   r!     s     HHN%NrG   r!   c                   .    \ rS rSrSrSrSrSrSrS r	Sr
g	)
r    i  z
Representation of a bra.
<r  z\left\langlez\right|c                 n    [        U[        5      (       a  [        X5      $ [        R                  " X5      $ r\   )r^   r!   r/   r   __mul__)r   others     rH   r  FockStateBra.__mul__  s)    e\**,,<<,,rG   r@   N)rB   rC   rD   rE   r   rL  rM  rX  rY  r  rF   r@   rG   rH   r    r      s"     HH$NN-rG   r    c                       \ rS rSrSrS rSrg)r"   i  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                 &    [        U R                  6 $ r\   )r#   rr   r~   s    rH   rf   FockStateBosonKet._dagger_       $)),,rG   r@   NrB   rC   rD   rE   r   rf   rF   r@   rG   rH   r"   r"     s    -rG   r"   c                       \ rS rSrSrS rSrg)r#   i  z
Describes a collection of BosonBra particles.

Examples
========

>>> from sympy.physics.secondquant import BBra
>>> BBra([1, 2])
FockStateBosonBra((1, 2))
c                 &    [        U R                  6 $ r\   )r"   rr   r~   s    rH   rf   FockStateBosonBra._dagger_  r  rG   r@   Nr  r@   rG   rH   r#   r#     s    	-rG   r#   c                       \ rS rSrSrS rSrg)r$   i  a  
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                 &    [        U R                  6 $ r\   )r%   rr   r~   s    rH   rf   FockStateFermionKet._dagger_      "DII..rG   r@   Nr  r@   rG   rH   r$   r$     s    ,/rG   r$   c                       \ rS rSrSrS rSrg)r%   i"  z
See Also
========

FockStateFermionKet

Examples
========

>>> from sympy.physics.secondquant import FBra
>>> FBra([1, 2])
FockStateFermionBra((1, 2))
c                 &    [        U R                  6 $ r\   )r$   rr   r~   s    rH   rf   FockStateFermionBra._dagger_0  r  rG   r@   Nr  r@   rG   rH   r%   r%   "  s    /rG   r%   c                    [        U [        5      (       d  U $ U R                  5       u  p[        U5      nUS;   a  U $ US   nUS   n[        U[        5      (       Ga  [        U[
        5      (       aT  UR                  (       a  U $ UR                  U5      nUS:X  a  [        R                  $ [        [        XSS -   U/-   6 5      $ [        U[        5      (       a  [        UR                  [
        5      (       a  UR                  R                  (       a  UR                  R                  (       a  U $ Un[        UR                  5       H&  nUR                  R                  U5      nUS:X  d  M&    O   US:X  a  [        R                  $ [        [        XSS -   U/-   6 5      $ U $ [        U[         5      (       a;  [#        XT5      nUS:X  a  [        R                  $ [        [        XSS -   U/-   6 5      $ U $ U $ )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   rg   r   r   N)r^   r
   r  rT  r!   r   r   r   r   r   
_apply_Mulr   baseexpr   ranger    r/   )mr  r  n_nclastnext_to_lastresultr   s           rH   r  r  9  s   " ajjlOFw<Dv~r{r{dL)),
33++H)88>F{ vv)#"0E0P*RSSL#..l//<<$((33#((44 !%!&|'7'7!8A%1%6%6%E%Ef%MF%{ % "9 "Q;#$66M#-cFSb\4IVH4T.V#WWHL,77%l9Q;66M%cFSb\,AVH,L&NOOHrG   c                     U R                  5       n U R                  [        5      n[        U5       Vs/ s H  o"[	        U5      4PM     nnU R                  U5      $ s  snf )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
   iterr  subs)emulsr  	subs_lists       rH   r.   r.   z  sO     	

A773<D-1$Z8ZZ]#ZI866) 9s   Ac                   ^    \ rS rSrSrSrS r\S 5       r\	S 5       r
\	S 5       rS rS	 rS
rg)r/   i  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                     [        U[        5      (       d  [        S5      e[        U[        5      (       d  [        S5      eU R	                  X5      $ )Nzmust be a brazmust be a ket)r^   r    	TypeErrorr!   r]   )r`   brakets      rH   r_   InnerProduct.__new__  sA    #|,,O,,#|,,O,,xx!!rG   c                     [         R                  n[        UR                  S   UR                  S   5       H  u  pEU[	        XE5      -  nUS:X  d  M    U$    U$ r|   )r   r^  ziprr   r   )r`   r  r  r  r   js         rH   r]   InnerProduct.eval  sS    SXXa[1DAnQ**F{	 2 rG   c                      U R                   S   $ )z!Returns the bra part of the stater   r}   r~   s    rH   r  InnerProduct.bra       yy|rG   c                      U R                   S   $ )z!Returns the ket part of the staterg   r}   r~   s    rH   r  InnerProduct.ket  r  rG   c                 t    [        U R                  5      n[        U R                  5      nUS S < SUSS  < 3$ )Nr   r  rg   )reprr  r  )r   sbraskets      rH   r   InnerProduct.__repr__  s3    DHH~DHH~s)T!"X..rG   c                 "    U R                  5       $ r\   )r   r~   s    rH   r   InnerProduct.__str__  s    }}rG   r@   N)rB   rC   rD   rE   r   ri   r_   r   r]   r   r  r  r   r   rF   r@   rG   rH   r/   r/     sY     N"      /
rG   r/   c                     [        [        U5      5      n[        [        U5      5       H@  n[        [        U5      5       H%  n[        [	        X   5      U -  X   -  5      X#U4'   M'     MB     U$ )ai  
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   rT  r  r.   r   )opbasisrk   r   r  s        rH   r4   r4     sb    $ 	c%jA3u:s5z"A%fUX&6r&9%(&BCAdG #  HrG   c                       \ rS rSrSrSrg)r0   i  z4
Base class for a basis set of bosonic Fock states.
r@   N)rB   rC   rD   rE   r   rF   r@   rG   rH   r0   r0     s     	rG   r0   c                   B    \ rS rSrSrS rS rS rS rS r	S r
S	 rS
rg)r1   i  z
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                 0    Xl         U R                  5         g r\   )n_max_build_states)r   r  s     rH   __init__VarBosonicBasis.__init__  s    
rG   c                     / U l         [        U R                  5       H(  nU R                   R                  [	        U/5      5        M*     [        U R                   5      U l        g r\   )r  r  r  appendr"   rT  n_basisrF  s     rH   r  VarBosonicBasis._build_states  sE    
tzz"AJJ/45 #4::rG   c                 8    U R                   R                  U5      $ )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     rH   r  VarBosonicBasis.index  s    " zz&&rG   c                      U R                   U   $ )z
The state of a single basis.

Examples
========

>>> from sympy.physics.secondquant import VarBosonicBasis
>>> b = VarBosonicBasis(5)
>>> b.state(3)
FockStateBosonKet((3,))
r  rF  s     rH   r   VarBosonicBasis.state	  s     zz!}rG   c                 $    U R                  U5      $ r\   r   rF  s     rH   rG  VarBosonicBasis.__getitem__      zz!}rG   c                 ,    [        U R                  5      $ r\   rT  r  r~   s    rH   rU  VarBosonicBasis.__len__      4::rG   c                 ,    [        U R                  5      $ r\   r  r  r~   s    rH   r   VarBosonicBasis.__repr__      DJJrG   )r  r  r  N)rB   rC   rD   rE   r   r  r  r  r   rG  rU  r   rF   r@   rG   rH   r1   r1     s*    ''& rG   r1   c                   H    \ rS rSrSrS rS rS rS rS r	S r
S	 rS
 rSrg)r2   i!  a"  
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                 \    Xl         X l        U R                  5         U R                  5         g r\   )n_particlesn_levels_build_particle_locationsr  )r   r  r  s      rH   r  FixedBosonicBasis.__init__2  s%    & &&(rG   c                    [        U R                  5       Vs/ s H  nSU-  PM
     nnSU R                  -  nSn[        USS  U5       H  u  pVSU< SU< S3nXG-   nM     SS	R	                  U5      -  nS
U< SU< SU< S3n	[        U	5      n
U R                  S:X  a  U
 Vs/ s H  o4PM     n
nXl        g s  snf s  snf )Nzi%izfor i0 in range(%i)r   rg   zfor z
 in range(z + 1) z(%s)z, [ ])r  r  r  r  r   r]   particle_locations)r   r   tup
first_loopother_loopscurprevtemp
tup_string	list_compr  items               rH   r  +FixedBosonicBasis._build_particle_locations8  s    "'(8(8"9:"9Quqy"9:*T]]:
SWc*IC14d;D%,K + diin,
$.
KH	iq *01&$g&F1"( ; 2s   B8#B=c                     / U l         U R                   HL  nU R                  S/-  nU H  nX#==   S-  ss'   M     U R                   R                  [	        U5      5        MN     [        U R                   5      U l        g )Nr   rg   )r  r  r  r  r"   rT  r  )r   tuple_of_indicesocc_numberslevels       rH   r  FixedBosonicBasis._build_statesF  sk    
 $ 7 7--+K)"a'" *JJ/<=	 !8
 4::rG   c                 8    U R                   R                  U5      $ )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     rH   r  FixedBosonicBasis.indexO  s     zz&&rG   c                      U R                   U   $ )zReturns 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  rF  s     rH   r   FixedBosonicBasis.state\  s     zz!}rG   c                 $    U R                  U5      $ r\   r   rF  s     rH   rG  FixedBosonicBasis.__getitem__i  r  rG   c                 ,    [        U R                  5      $ r\   r  r~   s    rH   rU  FixedBosonicBasis.__len__l  r  rG   c                 ,    [        U R                  5      $ r\   r  r~   s    rH   r   FixedBosonicBasis.__repr__o  r  rG   )r  r  r  r  r  N)rB   rC   rD   rE   r   r  r  r  r  r   rG  rU  r   rF   r@   rG   rH   r2   r2   !  s/     )'' rG   r2   c                   D    \ rS rSrSrSr\S 5       rS rS r	S r
S rS	rg
)r3   is  a  
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           	         U(       a  U(       d  [         R                  $ X:X  a  [         R                  $ UR                  (       d  UR                  (       a  [         R                  $ UR                  5       n[	        U[
        5      (       a(  [        UR                   Vs/ s H
  o0" X25      PM     sn6 $ UR                  5       n[	        U[
        5      (       a(  [        UR                   Vs/ s H
  o0" X5      PM     sn6 $ UR                  5       u  pEUR                  5       u  pg[        U5      [        U5      -   nU(       aA  [        [        U6 U " [        R                  " U5      [        R                  " U5      5      5      $ [	        U[        5      (       a  [	        U[        5      (       a  [	        U[        5      (       a5  [	        U[        5      (       a   [        UR                  UR                  5      $ [	        U[        5      (       aF  [	        U[        5      (       a1  [         R                   [        UR                  UR                  5      -  $ [         R                  $ [	        U["        5      (       a0  [	        U["        5      (       a  [%        X-  5      [%        X!-  5      -
  $ UR'                  5       UR'                  5       :  a  [         R                   U " X!5      -  $ gs  snf s  snf )a  
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   r   ri   r  r^   r   rr   r  rA  r
   
_from_argsr   r   r   r   r   rj  r   r6   sort_key)	r`   rk   r   termcancacbncbr  s	            rH   r]   Commutator.eval  s    a66M666Mq//66M
 HHJa!&&9&$T&9::HHJa!&&9&$Q&9::
 **,**,bDH$sF|S)<cnnS>Q%RSS
 a))jO.L.L![))jO.L.L%aggqww77![))jO.L.L}}^AGGQWW%EEEvva*++
1>O0P0P:ac
**
 ::<!**,&==Q** '= : :s   K#+K(c                 R   U R                   S   nU R                   S   nUR                  S5      (       a@  UR                  " S0 UD6nUR                  " S0 UD6n [        X#-  5      [        X2-  5      -
  $ X#-  X2-  -
  R                  " S0 UD6$ ! [         a     N%[
         a     N0f = f)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   rg   r6   r@   )rr   r   doitr6   rN   rW   )r   hintsrk   r   s       rH   r   Commutator.doit  s     IIaLIIaL99WAAQSzE!#J.. ac	(%(( 4 + s   B 
B&	B&%B&c                 L    SU R                   S   < SU R                   S   < S3$ )NzCommutator(r   ,rg   r   r}   r~   s    rH   r   Commutator.__repr__  s    &*iilDIIaLAArG   c                 L    SU R                   S   < SU R                   S   < S3$ )Nr  r   r$  rg   r  r}   r~   s    rH   r   Commutator.__str__  s     IIaL$))A,77rG   c           	      z    S[        U R                   Vs/ s H  o!R                  U5      PM     sn5      -  $ s  snf )Nz\left[%s,%s\right])rp   rr   r   )r   r   ra   s      rH   r   Commutator._latex  s=    %+/99/6+4CNN39/6 )7 7 	7 /6s   8
r@   N)rB   rC   rD   rE   r   ri   r   r]   r   r   r   r   rF   r@   rG   rH   r3   r3   s  s7    *X N9+ 9+v)<B87rG   r3   c                       \ rS rSrSrSrS r\S 5       r\S 5       r	S r
S rS	 rS
 rS rS rS rS rS rS rS rSrg)r7   i  ab  
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                    [        U5      nUR                  5       nUR                  (       a(  [        UR                   Vs/ s H
  o " U5      PM     sn6 $ UR
                  (       GaU  UR                  5       u  p4U(       a  [        U6 nU(       d  U$ O[        R                  n/ nSnU HH  n[        U[        5      (       a  UR                  UR                  5        SnM7  UR                  U5        MJ     U(       a  XP" [        U6 5      -  $ [        US   [        5      (       a  [        e [!        U5      u  piU	S-  (       a"  [        R&                  U-  U " [        U6 5      -  $ U	(       a  XP" [        U6 5      -  $  U[        R                  :w  a  XP" [        U6 5      -  $ [(        R*                  " U [        U6 5      $ [        U[        5      (       a  U$ U$ s  snf ! ["         a    [        R$                  s $ f = f)a2  
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   r   )r   r  ro   r   rr   rs   r  r
   r   r^  r^   r7   extendr  r   r   r   rQ   r   rj  r   r_   )
r`   ra   r  r  seqcoeffnewseqfounditfacrk  s
             rH   r_   
NO.__new__,  s   " cljjl::9#d)9::::: ,,.KFV L   FGc2&&MM#((+"GMM#&  Sf... #a&/22));C@ axe+Sf->>>Sf... ~Sf...<<S&\22c2J 
g :> - vvs    G*G G76G7c                 N    U R                   S   R                   S   R                  $ )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   )rr   r  r~   s    rH   has_q_creatorsNO.has_q_creatorsu  s#    , yy|  #000rG   c                 N    U R                   S   R                   S   R                  $ )a  
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   )rr   r  r~   s    rH   has_q_annihilatorsNO.has_q_annihilators  s#    , yy|  $555rG   c                     UR                  SS5      (       a  U R                  5       $ U R                  [        U 5      U R                  S   R
                  " S0 UD65      $ )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   r@   )r   _remove_bracketsr_   typerr   r   )r   r!  s     rH   r   NO.doit  sP    ( 99&--((**<<T
DIIaL,=,=,F,FGGrG   c                 b   / nU R                  5        GH  nX   R                  (       d  M  X   R                  R                  n[	        X   R                  [
        5      (       a  UR                  SS5        SUS'   [        S0 UD6nUR                  SS5        SUS'   [        S0 UD6n[        X   5      nX   R                  Xd5      [        X@U   R                  5      -  X   R                  Xe5      [        XPU   R                  5      -  -   nUR                  X   U45        GM  [        X   5      e   U(       a`  [        U R                  U5      5      n[	        U[        5      (       a0  [        UR                   V	s/ s H  oR!                  5       PM     sn	6 $ gU R                  S   $ s  sn	f )z
Returns the sorted string without normal order brackets.

The returned string have the property that no nonzero
contractions exist.
r   NTr   r   )r   )rk   )iter_q_creatorsr  r   r   r^   r   popr<  r_   r   r  rT   r7   r  r   rr   r   )
r   subslistr   assumebelowabover`   splitr  r  s
             rH   r;  NO._remove_brackets  s{    %%'Aw'''33 dgmmU33 JJ}d3,0F=)!00EJJ}d3,0F=)!00Etw-C3(Q>?'//#5(Q>??  OOTWe$45>twGG1 (2 		(+,F&#&&V[[A[TYY[[ABB ' 99Q< Bs   ?F,c                 ,    [        U R                  5      $ )a  
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.
)r7   r;  r~   s    rH   _expand_operatorsNO._expand_operators  s      $''((rG   c                    [        U[        5      (       aL  UR                  [        U 5      5      n[	        U6  Vs/ s H  oR
                  S   R
                  U   PM      sn$ U R
                  S   R
                  U   $ s  snf r|   )r^   sliceindicesrT  r  rr   )r   r   rL  s      rH   rG  NO.__getitem__  sj    aiiD	*G27/B/QIIaL%%a(/BB99Q<$$Q'' Cs   %A>c                 F    [        U R                  S   R                  5      $ r|   rS  r~   s    rH   rU  
NO.__len__  s    499Q<$$%%rG   c              #      #    U R                   S   R                   n[        [        U5      S-
  SS5      nU H  nX   R                  (       a  Uv   M    g   g7f)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   rg   r   N)rr   r  rT  r  r   opsr  r   s       rH   iter_q_annihilatorsNO.iter_q_annihilators  sM     * iilSX\2r*Av&&	 s   AAc              #      #    U R                   S   R                   n[        S[        U5      5      nU H  nX   R                  (       a  Uv   M    g   g7f)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)rr   r  rT  r  rQ  s       rH   r?  NO.iter_q_creators!  sG     , iilQC!Av""	 s   AAc                     U R                   S   nUR                  " UR                   SU UR                   US-   S -   6 n[        U5      $ )a  
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   Nrg   )rr   _new_rawargsr7   )r   r   arg0muls       rH   	get_subNONO.get_subNO?  sH     yy|$))BQ-$))AEF2C"CE#wrG   c                 D    SUR                  U R                  S   5      -  $ )Nz\left\{%s\right\}r   )r   rr   r   s     rH   r   	NO._latexR  s    &		!)EEErG   c                 &    SU R                   S   -  $ )NzNO(%s)r   r}   r~   s    rH   r   NO.__repr__U  s    $))A,&&rG   c                 &    SU R                   S   -  $ )Nz:%s:r   r}   r~   s    rH   r   
NO.__str__X  s    		!$$rG   r@   N)rB   rC   rD   rE   r   ri   r_   r   r4  r7  r   r;  rH  rG  rU  rS  r?  r[  r   r   r   rF   r@   rG   rH   r7   r7     sx    !D NGR 1 1. 6 6.H2( T)$(&:<&F'%rG   r7   c           	      j   [        U[        5      (       Ga  [        U [        5      (       Ga  [        U [        5      (       Ga]  [        U[        5      (       GaG  UR                  R
                  R                  S5      (       a  [        R                  $ U R                  R
                  R                  S5      (       a  [        R                  $ UR                  R
                  R                  S5      (       a   [        U R                  UR                  5      $ U R                  R
                  R                  S5      (       a   [        U R                  UR                  5      $ [        U R                  UR                  5      [        UR                  [        SSS95      -  $ [        U[        5      (       Ga]  [        U [        5      (       GaG  UR                  R
                  R                  S5      (       a  [        R                  $ U R                  R
                  R                  S5      (       a  [        R                  $ UR                  R
                  R                  S5      (       a   [        U R                  UR                  5      $ U R                  R
                  R                  S5      (       a   [        U R                  UR                  5      $ [        U R                  UR                  5      [        UR                  [        SSS95      -  $ [        R                  $ S X4 5       n[        U6 e)	a6  
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   rk   Tro  r   rn  c              3   B   #    U  H  n[        U[        5      v   M     g 7fr\   )r^   r   )rj   r   s     rH   rl   contraction.<locals>.<genexpr>  s     @1j-..s   )r^   r   r   r   r   r   r   r   r   r   r   rN   )rk   r   ts      rH   r5   r5   \  s/   J !&''Jq:K,L,La*++
1m0L0Lww##''66vvww##''66vvww##''66%aggqww77ww##''66%aggqww77"177AGG4"177E#4,HIJ Ka*++
1m0L0Lww##''66vvww##''66vvww##''66%aggqww77ww##''66%aggqww77"177AGG4"177E#4,HIJ K vv A@.22rG   c                 "    U R                  5       $ )z4Generates key for canonical sorting of SQ operators.)r  )sq_operators    rH   _sqkey_operatorri    s    !!rG   c                    [        U 5      n[        U 5      n[        U [        5      (       aL  U R                  R                  S5      (       a  SX!4$ U R                  R                  S5      (       a  SX!4$ SX!4$ U R                  R                  S5      (       a  SX!4$ U R                  R                  S5      (       a  SX!4$ SX!4$ )	zkKey for sorting of indices.

particle < hole < general

FIXME: This is a bottle-neck, can we do it faster?
r      r         
         )r  r  r^   r   r   r   )r  r	  r
  s      rH   r   r     s     	UAJE%!!-00>!##M22>!>!m,,E~						.	.E~E~rG   c                 H   SnSn[        [        [        U 5      S-
  5      5      n[        [        [        U 5      S-
  SS5      5      n[        [        X5      5      n[	        [        [        X`5      5      5      nU(       d  SnU H5  nXh   n	XhS-      n
X:X  a  [        X/5      eX:  d  M&  SnX/XhUS-   & US-   nM7     U(       a  ODU H5  nXh   n	XhS-      n
X:X  a  [        X/5      eX:  d  M&  SnX/XhUS-   & US-   nM7     U(       d  M  U Vs/ s H  oU   PM	     n nX4$ s  snf )a  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   rg   r  r   Tr   )rA  r  rT  rq   dictr  rQ   )string1r   verifiedrk  rngrevkeyskey_valr   leftrightr   s               rH   r   r     sA   , HD
uS\A%&
'C
uS\A%r2.
/CC!"D4D*+,GA7DQKE}/>>| !&q1uax  A7DQKE}/>>| !&q1uax  h, %)*Dq
DG*? +s   Dc                    [         4n[        X5      (       a3  U R                  " U R                   Vs/ s H  n[	        U5      PM     sn6 $ [        U [
        5      (       Gai  / n0 nU R                   HU  nUR                   H  nXd;   a  XF==   S-  ss'   M  SXF'   M     [        U[        5      (       d  MD  UR                  U5        MW     U H  nUR                  R                  (       aW  XGR                     (       aD  U R                  UR                  UR                  5      n [        U5      S:  a  [	        U 5      s  $ Mu  UR                  R                  (       ah  XGR                     (       aU  UR                  (       aD  U R                  UR                  UR                  5      n [        U5      S:  a  [	        U 5      s  $ M  M     U $ U $ s  snf )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)
rg   r   )r   r^   rx   rr   r8   r
   free_symbolsr   r  killable_index	is_Symbolr  preferred_indexrT  !indices_contain_equal_information)r  accepted_functionsra   deltasrL  r   sds           rH   r8   r8     s~   N 	 !((vv?,?@@	As		 A^^<J!OJ!"GJ	 $
 !^,,a   A ))g6F6F.GFF1++Q->->?v;?*1-- ###--':K:K2L99FF1,,a.>.>?v;?*1-- #    E @s   GFc                   ^^^^^^  U(       al  UR                  SS5      mUR                  SS5      mUR                  SS5      m [        T5      m[        T5      m[        T 5      mUU4S jnUU4S jnUU 4S jn/ n/ n/ nU R                  [        5      n	U(       d  [	        U	[
        S9n	S	=n
=pU	 H  nUR                  nUR                  S
5      (       a  U(       a  W" U
5      nU
S-  n
UnOCUR                  S5      (       a  U(       a  W" U5      nUS-  nUnOU(       a  W" U5      nUS-  nUnU(       a  UR                  [        W40 UD65        M  UR                  U5        M     U R                  5       n [        R                  " U 5      n/ nU GHk  n[        U5      n[        U5      n
[        U5      n[        U5      n0 nU Hq  nUR                  R                  S5      (       a  [        U5      UU'   M3  UR                  R                  S
5      (       a  [        U
5      UU'   Mc  [        U5      UU'   Ms     / n/ nUR                  5        Hy  u  nnUU:X  a  M  UU;   aR  UU   U;   a3  [        S5      nUR                  UU45        UR                  UU45        MP  UR                  S	UU45        Mf  UR                  UU45        M{     UR!                  U5        UR                  UR#                  U5      5        GMn     [        U6 $ )a  
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)

rD  r   rC  generalc                 R   >  TU    $ ! [          a    S[        U T-
  5      -   s $ f = f)Ni_
IndexErrorr  )number	len_belowletters_belows    rH   _isubstitute_dummies.<locals>._i	  7    6$V,, 6c&9"45556    &&c                 R   >  TU    $ ! [          a    S[        U T-
  5      -   s $ f = f)Na_r  )r  	len_aboveletters_aboves    rH   _asubstitute_dummies.<locals>._a	  r  r  c                 R   >  TU    $ ! [          a    S[        U T-
  5      -   s $ f = f)Np_r  )r  len_generalletters_generals    rH   _psubstitute_dummies.<locals>._p	  s7    8&v.. 8c&;"67778r  r   r   r   rg   r   x)r   rT  r  r   sortedr   r   r  r  r   	make_argsr  _get_ordered_dummiesnextitemsinsertr,  r  )!exprnew_indicespretty_indicesr  r  r  abovesbelowsgeneralsdummiesrk   r   pr  assumsyml1terms	new_termsr  orderedsubsdictrA  
final_subsr   vr  r  r  r  r  r  r  s!                              @@@@@@rH   r:   r:   i	  s   F &**7B7&**7B7(,,Y;&	&	/*	6	6	8 FFHjjG&67 MAM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0"1g##M22"1g"1g  
NN$DAqAvH} A;(*c
AOOQF+%%q!f- %%a!Q0A'# %$ 	
#8,-E F 	?rG   c                       \ rS rSrSrS rSrg)
KeyPrinteri
  z7Printer for which only equal objects are equal in printc                 8    SUR                   UR                  4-  $ )Nz(%s_%i))namedummy_index)r   r  s     rH   _print_DummyKeyPrinter._print_Dummy
  s    DIIt'7'7888rG   r@   N)rB   rC   rD   rE   r   r  rF   r@   rG   rH   r  r  
  s
    A9rG   r  c                 8    [        5       nUR                  U 5      $ r\   )r  doprint)r  r  s     rH   __kprintr  
  s    A99T?rG   c                 2  ^
^^^^ [         R                  " U 5      nU Vs0 s H  o3UR                  [        5      _M     snmU Vs0 s H  o3[	        U5      _M     snm[        5       R                  " TR                  5       6 n0 mU HV  nUR                  R                  S5      (       a  STU'   M*  UR                  R                  S5      (       a  STU'   MQ  STU'   MX     U Vs0 s H  oU[	        U5      _M     snm
U
UUU4S jn[        [        [        U[        [        Xd5      5      5      5      5      m[        UU4S jS9n[        [!        TR                  5       5      5      (       a  [#        [
        5      nTR%                  5        H  u  pYX   R'                  U5        M     U V	s/ s H  n	[)        X   5      S	:  d  M  U	PM     sn	 H  n	X	 M     [        U5       V	s/ s H  oU	   PM	     nn	[+        XU5      nU$ s  snf s  snf s  snf s  sn	f s  sn	f )
aW
  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           	      6  >^ T Vs/ s H  oTU   ;   d  M  UPM     nn[        5       R                  " U Vs/ s H  nTU   PM
     sn6 nUS   nUTU   L a  TU   R                  5       nUR                  U 5        U Vs/ s H  nTU   PM
     nnU H+  nU Vs/ s H  nUR	                  TU   TU   5      PM     nnM-     U Vs/ s H  nUR	                  TU    TU    5      PM     nn[        [        [        X$5      5      5      n[        U5      (       a   UR                  5         TU    [        U5      4$ [        [        [        X&5      5      5      mUR                  U4S jS9  UR                  5         / nU GHf  n[        U[        5      (       aD  XR                  ;   a  UR                  S5        XR                  ;   a  UR                  S5        M[  M]  [        U[         5      (       a  UR                  S5        M  [        U["        5      (       a  UR                  S5        M  [        U[$        5      (       an  U Vs/ s H  oR'                  U 5      (       d  M  UPM     n	nU	 H<  n[        U[         5      (       a  UR                  S5        M+  UR                  S5        M>     GM0  Sn
 XA   R)                  TU    U
S-   5      n
U
S:X  a  GMV  UR                  U
5        M6     TU    [        U5      US   US   4$ s  snf s  snf s  snf s  snf s  snf s  snf )Nr   c                    > TU    $ r\   r@   )r  keydicts    rH   <lambda>4_get_ordered_dummies.<locals>._key.<locals>.<lambda>
  s	    WQZrG   r   ulrg   r   )setunioncopyremovereplacerr  rA  r  r   sortrp   r^   r9   r   r  r   r   r   r7   hasfind)r  r1  	dumstruct
other_dumsmasked_facsd2
all_maskedpos_valr  rR  facposr  dum_reprfac_dumfac_reprmasks              @rH   _key"_get_ordered_dummies.<locals>._keyl
  s   %,CWcWS\0AcW	CU[[9"E9C73<9"EF
m% **,J!1:<#<B*-*  KKd2h?*  -K  #.0"-3 {{8A;Q8"- 	 04I ;<= JOO7E*--- tC	678/0C#233		>NN3'		>NN3' "C))s#C--s#C$$%(7SrFF1IS7B!"g..s+s+	  (-228A;
KF|NN6*	 ) 2 Qz*GAJDDe D"E
 =-04 8s-   K=K=L?L"L"L LLc                    > TU    $ r\   r@   )r  dumkeys    rH   r  &_get_ordered_dummies.<locals>.<lambda>
  s	    F1IrG   r   r   )r
   r  r  r   r  r  r  valuesr   r   rr  rA  r  rq   r  r   r  r   r  addrT  _determine_ambiguous)rZ  verboserr   r1  all_dumsr  r  r  	unorderedr   r  r  r  r  r  s             @@@@@rH   r  r  
  s   D ==D157#SYYu%%7G/35thsm#t5Hu{{GNN,-HD>>m,,DG^^..DGDG  )1118A;1H3E 3Eh $s8T#d*=%>?@AFH"56FV]]_%&&$	LLNDALQ #'Bi3y|+<q+@1iBA C -39,=?,=ql,=	?%c9=M[ 85 2z C @s#   H H%H
*HH"Hc                    [        5       nU H  nX4-  nM	     [        U5      U-
  nU(       dF  U Vs/ s H  ofUS   ;   d  M  UPM     nnUS   nUR                  U5        US   R                  U5        [        R                  n/ n	U Vs/ s H  ofU;   d  M
  UPM     sn H)  n[        R                  5       n
U	R                  Xj45        M+     U R                  U	5      n[        U5      n[        R                  U5        U Hp  nU Vs/ s H  ofU;   d  M
  UPM     nnUR                  5         / nU H:  nXg;   a!  UR                  UR                  5       5        M)  UR                  U5        M<     UnMr     U$ s  snf s  snf s  snf r|   )r  r  r  _symbol_factory_counter_nextr  r  r  _set_counterreverser@  )r  r  ambiguous_groupsall_ambiguousr  all_orderedr  groupstored_counterrA  nondumnewtermneworderordered_groupr  s                  rH   r  r  
  sl   $ EM#  $g,.K %BW-=a-@(@!WB!H""1%$--NH!7'Q+%5q'7 &&($ 8 ii!G#G,H  0 "%-=Xe!X=Azm//12a 	 
  " N3 C 8 >s#   E5E5		E:E:	E?E?c                   6    \ rS rSrS rS r\S 5       rS rSr	g)_SymbolFactoryi
  c                     SU l         Xl        g r|   _counterVar_label)r   r
  s     rH   r  _SymbolFactory.__init__
  s    rG   c                     Xl         g)z
Sets counter to value.
Nr  )r   values     rH   r  _SymbolFactory._set_counter
  s
     !rG   c                     U R                   $ )z
What counter is currently at.
r   r~   s    rH   r  _SymbolFactory._counter
  s    
 rG   c                 x    [        SU R                  U R                  4-  5      nU =R                  S-  sl        U$ )z9
Generates the next symbols and increments counter by 1.
z%s%irg   )r   r  r  )r   r  s     rH   r  _SymbolFactory._next
  s8     6T[[$*:*:;;<ArG   r  N)
rB   rC   rD   rE   r  r  r   r  r  rF   r@   rG   rH   r  r  
  s%    !    rG   r  z_]"]_c                 B   U(       a
  U (       a  / nO[        [        U 6 5      /n[        [        U 5      S-
  5       H  n[        US-   [        U 5      5       H  n[	        X   X   5      nU(       d  M  XC-
  S-   S-  nU(       a  [
        R                  U-  nOUnXS-   U XS-   S -   nU(       a3  UR                  U[        [        U SU 6 [        UUS9-  5      -  5        M  UR                  U[        [        U SU 6 5      -  5        M     U(       d  M    O   [        U6 $ )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.

rg   r   Nkeep_only_fully_contracted)
r7   r
   r  rT  r5   r   rj  r  _get_contractionsr   )	rs  r	  r  r   r  crk  r.  oplists	            rH   r
  r
    s&    "gS']#$3w<!#$q1uc'l+AGJ
3Aq	QMM!OEE  !Qq)GEFO;MM%WRa[)*;V7Q+S S)T #T U
 MM%C!,=(>">?E ,H &%M %P <rG   c                    U (       d  [         R                  $ SSSSS.nUR                  U5        [        U [        5      (       a  US   (       a  [         R                  $ U $ [        U [
        5      (       a  US   (       a  [         R                  $ U $ U R                  SS9n U R                  5       n [        U [        5      (       am  US   (       a6  [        [        U R                   Vs/ s H  n[        U40 UD6PM     sn6 5      $ [        U R                   Vs/ s H  n[        U40 UD6PM     sn6 $ [        U [        5      (       a  / n/ nU R                   H8  nUR                  (       a  UR                  U5        M'  UR                  U5        M:     [        U5      nUS:X  a  U nOdUS:X  a  US   (       a  [         R                  $ U nOA[        US   [         5      (       a  ["        e[%        U5      n['        UUS   S	9n[        U6 U-  nUS
   (       a  UR                  5       nUS   (       a  [)        U5      nU$ U $ s  snf s  snf )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_deltasr  simplify_dummiesr	  r	  )r6   r  r   rg   r  r  r  )r   r   updater^   r7   r   r   r  r   r:   rr   r6   r
   ri   r  rT  r   r   rp   r
  r8   )	r  kw_argsoptsr  r  rs  factornr  s	            rH   r6   r6   A  s   > vv &+!&+	D 	KK !R,-66MH	A(	)	),-66MH 	
TA 	

A!S"#%cPQPVPV+WPVU4-C7-CPV+W&XYYQVVDVT%00VDEE !S ffF$$f%v&	 
 L 6F!V01vv '!*o66))GnG 'w+/0L+MPF&\&(F>]]_F+,$V,F H_ ,XDs   (H?Ic                   .    \ rS rSrSrSrS rS rS rSr	g)	r;   i  z[
Represents the index permutation operator P(ij).

P(ij)*f(i)*g(j) = f(i)*g(j) - f(j)*g(i)
Tc                 r    [        [        [        X45      [        S9u  p[        R
                  " XU5      nU$ )Nr   )r  rq   r   r   r   r_   )r`   r   r  rc   s       rH   r_   PermutationOperator.__new__  s/    c'A6*0@AmmCA&
rG   c                 :   U R                   S   nU R                   S   nUR                  U5      (       af  UR                  U5      (       aP  [        5       nUR                  X$5      nUR                  X25      nUR                  XC5      n[        R
                  U-  $ U$ )a  
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   rg   )rr   r  r   r  r   rj  )r   r  r   r  tmps        rH   get_permuted PermutationOperator.get_permuted  s{     IIaLIIaL88A;;488A;;'C99Q$D99Q?D99S$D==%%KrG   c                 H   ^ S[        U4S jU R                   5       5      -  $ )NzP(%s%s)c              3   F   >#    U  H  nTR                  U5      v   M     g 7fr\   )r   )rj   r   r   s     rH   rl   -PermutationOperator._latex.<locals>.<genexpr>  s      FIq!2!2Is   !)rp   rr   r   s    `rH   r   PermutationOperator._latex  s    5 FDII FFFFrG   r@   N)
rB   rC   rD   rE   r   ri   r_   r  r   rF   r@   rG   rH   r;   r;     s    
 N
4GrG   r;   c                 @  ^ U4S jmU4S jnU R                  5       n [        U [        5      (       Ga(  [        U R                  5      nU GH  n[        5       n[        5       nU(       a  UR                  5       nUR                  U5      nXU-  ;   a9   UR                  U5        U" XxUR                  5      n	UR                  XI-  5        OvUn
[        U5      nX:X  a  UR                  U5        ORXU-  ;   a9   UR                  U5        U" XxUR                  5      n	UR                  XI-  5        OUR                  U5        U(       a  M  XV-  nGM     [        U6 $ U $ ! [         a    UR                  U5         Nf = f! [         a    UR                  U5         Nf = f)aZ  
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                    > / nU R                    HE  nX1;   a  UR                  U5        M  UR                   (       d  M.  UR                  T" X15      5        MG     U$ )z4
Collects indices recursively in predictable order.
)rr   r  r,  )r  indr  ra   _get_indicess       rH   r#  1simplify_index_permutations.<locals>._get_indices  sJ     99Czc"888MM,s"89  rG   c                 $   >^ [        XUU4S jS9$ )Nc                 (   > [        T" U T5      5      $ r\   r   )r  r#  r"  s    rH   r  Jsimplify_index_permutations.<locals>._choose_one_to_keep.<locals>.<lambda>  s    '7Q8L'MrG   r   )min)rk   r   r"  r#  s     `rH   _choose_one_to_keep8simplify_index_permutations.<locals>._choose_one_to_keep  s    1MNNrG   )r  r^   r   r  rr   r@  r  r  KeyErrorr  r:   )r  permutation_operatorsr)  r  Pr  on_holdr  permutedkeep	permuted1r#  s              @rH   r<   r<     sl   FO ;;=D$DII&AIeGyy{>>$/w.1X. /tqvvFDMM!&) !)I1(;H ,D)!W_45!LL2  34166J!af-!d+9 %: 'EA 'B E{K3 $ 1x01"  ( 5#NN845s$   E9E?E<;E<?FFN)F)hr   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.complexesr   (sympy.functions.elementary.miscellaneousr   (sympy.functions.special.tensor_functionsr   sympy.matrices.denser   sympy.printing.strr   sympy.utilities.iterablesr   __all__	Exceptionr>   rK   rN   rQ   rT   rW   r   r   r9   r   r   r   r   r   r   r,   r-   r   r   r   r+   r*   r   r\  rf  r!   r    r"   r#   r$   r%   r&   r'   r(   r)   r  r.   r/   r4   r0   r1   r2   r3   r7   r5   ri  r   r   r8   r:   r  r  r  r  r  r  r
  r6   r;   r<   r@   rG   rH   <module>rH     s   $  " $ '   (      " / + & : 9 C & ) .&R	i 		!8 		'> 		 7 		+B 		6 	ET EP4 
o', o'dDL DLN	j 		* 		j 	09o{ 09d'D/7 'DR `
 `FU9); U9pRD%w RDh +E +E\,, ,,^K09 K0\&9 &-9 - -
L -"-
L -/, /6/, /" >B$/5 /d2	 	@  @ FO  O dQ7 Q7hR% R%j
E3P"4 /> 5pl^ */r eP9 9
Pf6r 2 !) 	9 	9xl^(G$ (GVZrG   