Ask Your Question

Changing one letter in integrand causes sagemath/giac crash

asked 2022-02-19 07:00:53 +0200

Nasser gravatar image

updated 2022-02-19 07:10:59 +0200

I've been trying for a while to find why some integrals cause giac to crash. This is different from earlier question I asked.

This seem to be an interface issue between sagemath and giac.

Here is an integrand which causes giac to crash according to sagemath. Ok, may be due sagemath changing the form of the integrand. I do not know. (this takes about almost 10 minutes to crash, which I do not know why so long).

btw, is there a way to see what exactly sagemath sends to giac in the call if sagemath changes the form of the integrand? Is there a way to trace the call?

sage: var("x f e a b z")
sage: integrand = cot(f * x + e) * (a + b * sin(f * x + e) ^ 2) ^ (1 / 2)
sage: integrand
        sqrt(b*sin(f*x + e)^2 + a)*cot(f*x + e)
sage: integrate(integrand, x, algorithm="giac")
Giac crashed -- automatically restarting.
ValueError                                Traceback (most recent call last)
File /usr/lib/python3.10/site-packages/sage/interfaces/, in InterfaceElement.__getattr__(self, attrname)
   1215 try:
-> 1216     P = self._check_valid()
   1217 except ValueError:

File /usr/lib/python3.10/site-packages/sage/interfaces/, in ExpectElement._check_valid(self)
   1498     if P is None or P._session_number == BAD_SESSION or self._session_number == -1 or \
   1499                   P._session_number != self._session_number:
-> 1500         raise ValueError("The %s session in which this object was defined is no longer running."
   1501 except AttributeError:

ValueError: The giac session in which this object was defined is no longer running.

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
Input In [9], in <module>
----> 1 integrate(integrand, x, algorithm="giac")

File /usr/lib/python3.10/site-packages/sage/misc/, in integral(x, *args, **kwds)
    639 """
    640 Return an indefinite or definite integral of an object ``x``.
    762 """
    763 if hasattr(x, 'integral'):
--> 764     return x.integral(*args, **kwds)
    765 else:
    766     from sage.symbolic.ring import SR

File /usr/lib/python3.10/site-packages/sage/symbolic/expression.pyx:13138, in sage.symbolic.expression.Expression.integral (build/cythonized/sage/symbolic/expression.cpp:95254)()
  13136                 R = SR
  13137         return R(integral(f, v, a, b, **kwds))
> 13138     return integral(self, *args, **kwds)
  13140 integrate = integral

File /usr/lib/python3.10/site-packages/sage/symbolic/integration/, in integrate(expression, v, a, b, algorithm, hold)
   1045     if not integrator:
   1046         raise ValueError("Unknown algorithm: %s" % algorithm)
-> 1047     return integrator(expression, v, a, b)
   1048 if a is None:
   1049     return indefinite_integral(expression, v, hold=hold)

File /usr/lib/python3.10/site-packages/sage/symbolic/integration/, in giac_integrator(expression, v, a, b)
    256     return expression.integrate(v, a, b, hold=True)
    257 else:
--> 258     return result._sage_()

File /usr/lib/python3.10/site-packages/sage/interfaces/, in GiacElement._sage_(self, locals)
   1131 from sage.calculus.calculus import symbolic_expression_from_string, SR_parser_giac
   1133 result = repr(self) # string representation
-> 1135 if str(self.type()) not in ['DOM_LIST', 'vector', 'vecteur']:
   1137     # Merge the user-specified locals dictionary and the symbol_table
   1138     # (locals takes priority)
   1139     lsymbols = symbol_table['giac'].copy()
   1140     lsymbols.update(locals)

File /usr/lib/python3.10/site-packages/sage/interfaces/, in InterfaceElement.__getattr__(self, attrname)
   1216     P = self._check_valid()
   1217 except ValueError:
-> 1218     raise AttributeError(attrname)
   1219 if attrname[:1] == "_":
   1220     raise AttributeError

AttributeError: type

When I change e to say z the crash goes away! This answer returns immediately also.

sage: integrand = cot(f * x + z) * (a + b * sin(f * x + z) ^ 2) ^ (1 / 2)
sage: integrand
     sqrt(b*sin(f*x + z)^2 + a)*cot(f*x + z)

sage: integrate(integrand, x, algorithm="giac")
   (a*arctan(sqrt(b*sin(f*x + z)^2 + a)/sqrt(-a))/sqrt(-a) + sqrt(b*sin(f*x + z)^2 + a))/f

Note that the above used to work OK in 9.3. i.e. when using e, it used to work and return the same antiderivative shown above but with z replaced by e. I have report showing this worked before with giac. so something changed.

Notice that inside giac, e is the Euler constant. And I assume sagemath knows this of course and it changes internally e to some made up VAR symbol before calling giac and in return reverse this back to e in sagemath space.

Here is the same thing inside giac, both complete immediately.

2>> integrand:=sqrt(b*sin(f*x + e)^2 + a)*cot(f*x + e)
3>> integrate(integrand,x)

4>> integrand:=sqrt(b*sin(f*x + z)^2 + a)*cot(f*x + z)
5>> integrate(integrand,x)

No crash inside giac for same integrand using e or z

my question is: Why giac crashes when using e but not when using z? Surely the letter should not have made a difference? Is this a new interface problem? Why this same integral worked in 9.3 but not in 9.5? I am running the same test.

Just in case, I also created a ticket

edit retag flag offensive close merge delete


For debugging, use

%debug integrate(integrand, x, algorithm="giac")
FrédéricC gravatar imageFrédéricC ( 2022-02-19 08:40:03 +0200 )edit

And I assume sagemath knows this of course and it changes internally e to some made up VAR symbol before calling giac and in return reverse this back to e in sagemath space.

"Assume : make an ass of you and me"... Why in the name of Euclides are you using a letter conventionally used to denote a well-known constant to denote a plain ordinary variable ? Are you trying to confuse your readers ?

Consider :

sage: e.n()
sage: var("e")
sage: e.n()


TypeError: cannot evaluate symbolic expression numerically
sage: reset("e")
sage: e.n()

Where would Sage "change internally e to some made up VAR symbol" ?

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2022-02-19 11:30:12 +0200 )edit


sage: e._giac_init_()
sage: var("e")
sage: e._giac_init_()
sage: reset("e")
sage: e._giac_init_()

This should be clearer now...

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2022-02-19 11:52:06 +0200 )edit

There is, indeed, a real prolem with Sage<-->Giac translations. Consider :

sage: {u:u._giac_() for u in integrand.variables()}
{a: sage20
 b: sage21
 e: sage22
 f: sage23
 x: sage24

and compare with :

sage: {u:u._giac_() for u in integrand.subs({e:z}).variables()}
{a: sage25
 b: sage26
 f: sage27
 x: sage28
 z: sage29

Off-by-one error in translator's stack management ?

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2022-02-19 12:19:43 +0200 )edit

Hello! Just read a little bit a bout this issue. Unfortunately, I cannot reproduce Emmanuel's output. For

{u:u._giac_() for u in integrand.variables()}

I got the answer

{a: sageVARa, b: sageVARb, e: sageVARe, f: sageVARf, x: sageVARx}

Similarly, for

{u:u._giac_() for u in integrand.subs({e:z}).variables()}

I got the answer

{a: sageVARa, b: sageVARb, f: sageVARf, x: sageVARx, z: sageVARz}

Did I miss some step or something?

dsejas gravatar imagedsejas ( 2022-02-19 15:28:32 +0200 )edit

1 Answer

Sort by » oldest newest most voted

answered 2022-02-19 21:48:00 +0200

Emmanuel Charpentier gravatar image

Not an answer, but a comment : giac's answer seems wrong.

Integrating integrand then differentiating it wrt x should give back, if not the same expression, at least an expression equal to Integrand. Checking formally such an equality isn't obvious ; however, one can plot the expressions and get numerical hints.

Comparing the integrand to the two expressions returned by fricas, the one returned by maxima, the one returned by mathematica and the one obtained via giac, one gets :

plot([integrand.subs(D), foo[0].diff(x).subs(D)-1/5, foo[1].diff(x).subs(D)+1/5, integrand.subs(D).integrate(x).diff(x)+2/5, mathematica.Integrate(integrand,x).sage().diff(x).subs(D)-2/5, giac.integrate(*map(lambda u:u._giac_(), (integrand, x)))._sage_().diff(x).subs(D)+3/5], (-pi, pi), ymin=-5, ymax=5, legend_label=["I", "F0", "F1", "Mx", "Ma", "G"])

image description

All those expressions seem equal except for the one returned by giac.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2022-02-19 07:00:53 +0200

Seen: 88 times

Last updated: Feb 19