                 /** Simplification of Psi functions **/

/*K: Psi; digamma; polygamma */
/*A: John Gottschalk */
/*S: University of Western Australia */
/*D: September 1985 */
/*P: XDelete, XLexpr and XSets are automatically loaded as needed. */

/*W: The notation Psi[$n,$x] must not be used. */
/*F: Extend PsiCan to allow polygamma functions. */

If[~P[_XLoadonce[Loaded]],<XLoadonce]

_Cmpl[Init] :: Loadonce[XSets]
_DelE[Init] :: Loadonce[XDelete]
_Projfind[Init] :: Loadonce[XProjfind]

/*: PsiCan[$expr] 
	finds the Psi function in $expr with the lowest argument
	and writes all other Psi functions in terms of this using the recurrence
	equation for digamma functions. */
PsiCan[$expr] :: (Lcl[%allpsi,%arg,%expr,%likepsi,%Rep,%reps,%Minpsi,%minpsi];\
      %Minpsi[$x] :: (Ar[Len[$x],$x[$1][1]]; {Ap[Min,%%]}; Ap[Psi,%%]);\
      %Rep[Psi[$x],Psi[$z]] :: If[$x~=$z,Psi[$x] -> Psi[$z]+\
			           Sum[1/(%#p+$z),{%#p,0,$x-$z-1}]];\
      %expr : S[$expr,Psi[$x] --> Psi[Ex[$x]]]; %reps : {};\
      %allpsi : Projfind['Psi,%expr];\
      Loop[,(%arg : %allpsi[1,1];\
	     %likepsi : Projfind['Psi,%allpsi,Intp[$1[1]-%arg] & \
				   Numbp[$1[1]-%arg]];\
	     %minpsi : %Minpsi[%likepsi];\
	     %reps : Cat[%reps,Map[%Rep[$1,%minpsi],%likepsi]];\
	     %allpsi : Cmpl[%likepsi,%allpsi]),\
           Len[%allpsi] > 0];\
      S[%expr,DelE[Null,%reps]])

_XPsiCan[Loaded] : 1

/*E: 
SMP 1.5.0

#I[1]::  <XPsiCan

#I[2]::  ex : Psi[5/2]+r Psi[7/2] +Psi[(2g+3)/2]-Psi[g+1/2]

						    3 + 2g
#O[2]:   r Psi[7/2] + Psi[5/2] - Psi[1/2 + g] + Psi[------]
						      2

#I[3]::  PsiCan[ex]

	    1
#O[3]:   ------- + r (2/5 + Psi[5/2]) + Psi[5/2]
	 1/2 + g
*/
