Ask Your Question
4

Can I create a sage file, and import it as a Python module?

asked 2016-06-28 18:14:23 +0100

silvia_n_nets gravatar image

I am trying to create a file that produces some data using sage specific modules (eg graphs. ). Is there a way that I can save this file and then import it in a Python shell and / or in a Sage shell?

The problems I have encountered so far are:

  • if I try to save the file as filename.py and import it as a module in a Python or Sage shell, Python/ Sage won't recognize the sage specific functions (which makes sense)
  • if I try to save the file as filename.sage and import it as a module in a Sage shell, I get the error "No module named filename"

I am working from an Ubuntu terminal.

Thank you!

edit retag flag offensive close merge delete

Comments

I just know that the standard way to import a file is :

sage: load /path/to/foo.py

or

sage: attach /path/to/foo.py.

But I guess I need to read more about Python

MargaretMitchel gravatar imageMargaretMitchel ( 2016-06-30 16:24:06 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted
5

answered 2016-06-28 23:54:50 +0100

slelievre gravatar image

The solution is to use a filename.py file.

For the sage specific syntax, find the corresponding Python code using preparse.

Find the sage specific functions to import using import_statements.

For example, suppose that your sage file has

R.<x> = PolynomialRing(QQ)

which is not correct Python syntax. Check how to turn that into correct Python.

sage: preparse('R.<x> = PolynomialRing(QQ)')
"R = PolynomialRing(QQ, names=('x',)); (x,) = R._first_ngens(1)"

so in filename.py you would write

R = PolynomialRing(QQ, names=('x',))
(x,) = R._first_ngens(1)

instead of

R.<x> = PolynomialRing(QQ)

You would also need the import statements, which you find with

sage: import_statements('PolynomialRing')
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
sage: import_statements('QQ')
...
from sage.rings.rational_field import QQ

So your python file would really have

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.rational_field import QQ

R = PolynomialRing(QQ, names=('x',))
(x,) = R._first_ngens(1)
edit flag offensive delete link more

Comments

2

For the syntax, you can run sage -preparse file.sage from the command line and it will do all of the syntax conversions for you. It will also add the line from sage.all import * at the top, though you have to then run this with Sage's version of Python (or tell Python where to find sage.all).

jaebond gravatar imagejaebond ( 2016-07-26 20:46:34 +0100 )edit

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 2016-06-28 18:14:23 +0100

Seen: 3,473 times

Last updated: Jun 28 '16