# Save boolean polynomial ring to file and read it again [closed]

I have BooleanPolynomialRing of 256 variables and I need many thick polynomials. Generate them is very time consuming so I want to save them to file and when needed read again. Is there some good way? Till now I have found out something like this (simplified)

variables=[]
for i in range(1,257):
variables.append('x'+str(i))
R = BooleanPolynomialRing(names=variables)
R.inject_variables()
fw = open('/home/pro/Desktop/polynomials.txt', 'w')
polynomial = R.random_element(degree=2,terms=+infinity)
fw.write(str(polynomial) + "\n")
fr = open('/home/pro/Desktop/polynomials.txt', 'r')


How can I convert string back to polynomial?

Thanks f.close()

edit retag reopen merge delete

### Closed for the following reason the question is answered, right answer was accepted by Pro close date 2015-11-04 22:18:13.453496

Sort by » oldest newest most voted

Instead of using strings, you can directly save the Sage object:

sage: polynomial.save('/home/pro/Desktop/polynomials.sobj')


Then you can load it as follows:

sage: P = load('/home/pro/Desktop/polynomials.sobj')


EDIT

You can save several polynomials in the same file by saving a list of polynomials (but since lists have no save method, you have to use the save function). For example, if P1,P2,P3 are polynomials, you can do:

sage: L = [P1, P2, P3]
sage: save(L, '/home/pro/Desktop/polynomials.sobj')


and then recover it as before:

sage: L = load('/home/pro/Desktop/polynomials.sobj')


and you can then get your polynomials back:

sage: P1, P2, P3 = L

more

So I need one file for every polynomial right? Is there a way to save multiple polynomials to one file? This may not be the best way to recover a polynomial from its string representation but it appears to work.

Say p = R.random_element(degree=2,terms=+infinity), then s = str(p) gives you its representation as a string. To recover p you can try q = R( eval(s)). Then p==q should evaluate to True.

Now, if you are reading a file fr with a polynomial per line, you can try the following to recover the polynomials.

vars = ['x'+str(i) for i in range(10)]
R= BooleanPolynomialRing(names=vars)
R.inject_variables()
polys = [ R(eval(l[:-1])) for l in fr]


more