--Copyright (c) 1991-2002, The Numerical ALgorithms Group Ltd.
--All rights reserved.
--
--Redistribution and use in source and binary forms, with or without
--modification, are permitted provided that the following conditions are
--met:
--
--    - Redistributions of source code must retain the above copyright
--      notice, this list of conditions and the following disclaimer.
--
--    - Redistributions in binary form must reproduce the above copyright
--      notice, this list of conditions and the following disclaimer in
--      the documentation and/or other materials provided with the
--      distribution.
--
--    - Neither the name of The Numerical ALgorithms Group Ltd. nor the
--      names of its contributors may be used to endorse or promote products
--      derived from this software without specific prior written permission.
--
--THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
--IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
--TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
--PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
--OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
--EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
--PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
--PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
--LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
--NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
--SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-- SPAD files for the integration world should be compiled in the
-- following order:
--
--   intaux  rderf  intrf  curve  curvepkg  divisor  pfo
--   intalg  intaf  EFSTRUC  rdeef  intef  irexpand  integrat
 
)abbrev package FSCINT FunctionSpaceComplexIntegration
++ Top-level complex function integration
++ Author: Manuel Bronstein
++ Date Created: 4 February 1988
++ Date Last Updated: 11 June 1993
++ Description:
++   \spadtype{FunctionSpaceComplexIntegration} provides functions for the
++   indefinite integration of complex-valued functions.
++ Keywords: function, integration.
FunctionSpaceComplexIntegration(R, F): Exports == Implementation where
  R : Join(EuclideanDomain, CharacteristicZero,
           RetractableTo Integer, LinearlyExplicitRingOver Integer)
  F : Join(TranscendentalFunctionCategory,
           AlgebraicallyClosedFunctionSpace R)
 
  SE  ==> Symbol
  G   ==> Complex R
  FG  ==> Expression G
  IR  ==> IntegrationResult F
 
  Exports ==> with
    internalIntegrate : (F, SE) -> IR
        ++ internalIntegrate(f, x) returns the integral of \spad{f(x)dx}
        ++ where x is viewed as a complex variable.
    internalIntegrate0: (F, SE) -> IR
        ++ internalIntegrate0 should be a local function, but is conditional.
    complexIntegrate  : (F, SE) -> F
        ++ complexIntegrate(f, x) returns the integral of \spad{f(x)dx}
        ++ where x is viewed as a complex variable.
 
  Implementation ==> add
    import IntegrationTools(R, F)
    import ElementaryIntegration(R, F)
    import ElementaryIntegration(G, FG)
    import AlgebraicManipulations(R, F)
    import AlgebraicManipulations(G, FG)
    import TrigonometricManipulations(R, F)
    import IntegrationResultToFunction(R, F)
    import IntegrationResultFunctions2(FG, F)
    import ElementaryFunctionStructurePackage(R, F)
    import ElementaryFunctionStructurePackage(G, FG)
    import InnerTrigonometricManipulations(R, F, FG)
 
    K2KG: Kernel F -> Kernel FG
 
    K2KG k                 == retract(tan F2FG first argument k)@Kernel(FG)
 
    complexIntegrate(f, x) ==
      removeConstantTerm(complexExpand internalIntegrate(f, x), x)
 
    if R has Join(ConvertibleTo Pattern Integer, PatternMatchable Integer)
      and F has Join(LiouvillianFunctionCategory, RetractableTo SE) then
        import PatternMatchIntegration(R, F)
        internalIntegrate0(f, x) ==
          intPatternMatch(f, x, lfintegrate, pmComplexintegrate)
 
    else internalIntegrate0(f, x) == lfintegrate(f, x)
 
    internalIntegrate(f, x) ==
      f := distribute(f, x::F)
      g : F
      any?(has?(operator #1, 'rtrig),
       [k for k in tower(g := realElementary(f, x))
        | member?(x, variables(k::F))]$List(Kernel F))$List(Kernel F) =>
          h := trigs2explogs(F2FG g, [K2KG k for k in tower f
                         | is?(k, 'tan) or is?(k, 'cot)], [x])
          real?(g := FG2F h) =>
            internalIntegrate0(rootSimp(rischNormalize(g, x).func), x)
          real?(g := FG2F(h := rootSimp(rischNormalize(h, x).func))) =>
                                                       internalIntegrate0(g, x)
          map(FG2F, lfintegrate(h, x))
      internalIntegrate0(rootSimp(rischNormalize(g, x).func), x)

)abbrev package FSINT FunctionSpaceIntegration
++ Top-level real function integration
++ Author: Manuel Bronstein
++ Date Created: 4 February 1988
++ Date Last Updated: 11 June 1993
++ Keywords: function, integration.
++ Description:
++   \spadtype{FunctionSpaceIntegration} provides functions for the
++   indefinite integration of real-valued functions.
++ Examples: )r INTEF INPUT
FunctionSpaceIntegration(R, F): Exports == Implementation where
  R : Join(EuclideanDomain, CharacteristicZero,
           RetractableTo Integer, LinearlyExplicitRingOver Integer)
  F : Join(TranscendentalFunctionCategory, PrimitiveFunctionCategory,
           AlgebraicallyClosedFunctionSpace R)
 
  B   ==> Boolean
  G   ==> Complex R
  K   ==> Kernel F
  P   ==> SparseMultivariatePolynomial(R, K)
  SE  ==> Symbol
  IR  ==> IntegrationResult F
  FG  ==> Expression G
 
  Exports ==> with
    integrate: (F, SE) -> Union(F, List F)
        ++ integrate(f, x) returns the integral of \spad{f(x)dx}
        ++ where x is viewed as a real variable.
 
  Implementation ==> add
    macro ALGOP == '%alg
    macro TANTEMP == '%temptan
    import IntegrationTools(R, F)
    import ElementaryIntegration(R, F)
    import ElementaryIntegration(G, FG)
    import AlgebraicManipulations(R, F)
    import TrigonometricManipulations(R, F)
    import IntegrationResultToFunction(R, F)
    import TranscendentalManipulations(R, F)
    import IntegrationResultFunctions2(FG, F)
    import FunctionSpaceComplexIntegration(R, F)
    import ElementaryFunctionStructurePackage(R, F)
    import InnerTrigonometricManipulations(R, F, FG)
    import PolynomialCategoryQuotientFunctions(IndexedExponents K,
                      K, R, SparseMultivariatePolynomial(R, K), F)
 
    K2KG      : K -> Kernel FG
    postSubst : (F, List F, List K, B, List K, SE) -> F
    rinteg    : (IR, F, SE, B, B) -> Union(F, List F)
    mkPrimh   : (F, SE, B, B) -> F
    trans?    : F -> B
    goComplex?: (B, List K, List K) -> B
    halfangle : F -> F
    Khalf     : K -> F
    tan2temp  : K -> K
 
    optemp:BasicOperator := operator(TANTEMP, 1)
 
    K2KG k     == retract(tan F2FG first argument k)@Kernel(FG)
    tan2temp k == kernel(optemp, argument k, height k)$K
 
    trans? f ==
      any?(is?(#1,'log) or is?(#1,'exp) or is?(#1,'atan),
           operators f)$List(BasicOperator)
 
    mkPrimh(f, x, h, comp) ==
      f := real f
      if comp then f := removeSinSq f
      g := mkPrim(f, x)
      h and trans? g => htrigs g
      g
 
    rinteg(i, f, x, h, comp) ==
      not elem? i => integral(f, x)$F
      empty? rest(l := [mkPrimh(f, x, h, comp) for f in expand i]) => first l
      l
 
-- replace tan(a/2)**2 by (1-cos a)/(1+cos a) if tan(a/2) is in ltan
    halfangle a ==
      a := 2 * a
      (1 - cos a) / (1 + cos a)
 
    Khalf k ==
      a := 2 * first argument k
      sin(a) / (1 + cos a)
 
-- ltan = list of tangents in the integrand after real normalization
    postSubst(f, lv, lk, comp, ltan, x) ==
      for v in lv for k in lk repeat
        if ((u := retractIfCan(v)@Union(K, "failed")) case K) then
           if has?(operator(kk := u::K), ALGOP) then
             f := univariate(f, kk, minPoly kk) (kk::F)
           f := eval(f, [u::K], [k::F])
      if not(comp or empty? ltan) then
        ltemp := [tan2temp k for k in ltan]
        f := eval(f, ltan, [k::F for k in ltemp])
        f := eval(f, TANTEMP, 2, halfangle)
        f := eval(f, ltemp, [Khalf k for k in ltemp])
      removeConstantTerm(f, x)
 
-- can handle a single unnested tangent directly, otherwise go complex for now
-- l is the list of all the kernels containing x
-- ltan is the list of all the tangents in l
    goComplex?(rt, l, ltan) ==
      empty? ltan => rt
      not empty? rest rest l
 
    integrate(f, x) ==
      R has complex or not real? f => complexIntegrate(f, x)
      f   := distribute(f, x::F)
      tf  := [k for k in tower f | member?(x, variables(k::F)@List(SE))]$List(K)
      ltf := select(is?(operator #1, 'tan), tf)
      ht  := any?(has?(operator #1, 'htrig), tf)
      rec := rischNormalize(realElementary(f, x), x)
      g   := rootSimp(rec.func)
      tg  := [k for k in tower g | member?(x, variables(k::F))]$List(K)
      ltg := select(is?(operator #1, 'tan), tg)
      rtg := any?(has?(operator #1, 'rtrig), tg)
      el  := any?(has?(operator #1, 'elem), tg)
      i:IR
      if (comp := goComplex?(rtg, tg, ltg)) then
        i := map(FG2F, lfintegrate(trigs2explogs(F2FG g,
                       [K2KG k for k in tf | is?(k, 'tan) or
                            is?(k, 'cot)], [x]), x))
      else i := lfintegrate(g, x)
      ltg := setDifference(ltg, ltf)   -- tan's added by normalization
      (u := rinteg(i, f, x, el and ht, comp)) case F =>
        postSubst(u::F, rec.vals, rec.kers, comp, ltg, x)
      [postSubst(h, rec.vals, rec.kers, comp, ltg, x) for h in u::List(F)]

