Mixing cython and Sage code

45 views
Skip to first unread message

saad khalid

unread,
Mar 21, 2018, 2:29:37 PM3/21/18
to sage-support
Hey everyone:

I'm currently in the process of converting some code from Mathematica to Sage, my primary motivation being that Mathematica is running it too slowly and I was hoping that I could somehow get some increase in speed with Sage. My thought was that this would be easiest if I were able to use cython along with Sage. Is this currently possible? For example, one of the Mathematica functions takes a polynomial in 2 variables as input and computes the value of the order in one of the variables (ie for x1^3 + x1*x2^2 + x2, the order for x1 would be 3). I wrote some Sage could that can do this, but then how can I use what the sage code computes with cython code? When I was trying to compile some cython code in Cocalc using %cython, it would not let me include any Sage code. For eg, I tried including the line:
R.<x1,x2> = RR[]

but it threw errors at me. Do you think I am approaching this speed up idea in a reasonable way? Or should I be trying to do it purely in Sage or purely in cython? Thanks!

Dima Pasechnik

unread,
Mar 21, 2018, 3:56:01 PM3/21/18
to sage-support
A large part of  the Sage library is written in Cython. Cython in Sage needs a bit more care. Did you read

The following works in CoCalc ipython notebook:

%cython
def tst():
    from sage.rings.real_mpfr import RR
    from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
    R2 = PolynomialRing(RR,'x1,x2')
    (x1,x2) = R2.gens()
    return x1**2-x2**3


Note that to get the needed import statements, you can run

import_statements('RR'), etc



----------------
Tp 
  

Ralf Stephan

unread,
Mar 23, 2018, 5:10:24 AM3/23/18
to sage-support
On Wednesday, March 21, 2018 at 7:29:37 PM UTC+1, saad khalid wrote:
...For example, one of the Mathematica functions takes a polynomial in 2 variables as input and computes the value of the order in one of the variables (ie for x1^3 + x1*x2^2 + x2, the order for x1 would be 3).

Not discouraging your efforts but did you try poly.degree(x1)?

Reply all
Reply to author
Forward
0 new messages