# Save tensor in file

I define the following $3+1$ manifold and chart:

n = 3
M = Manifold(1+n, 'M', structure='Lorentzian')
X.<t,r,th,ph> = M.chart(r"t r:(0,+oo) th:(0,pi):\theta ph:(0,2*pi):\phi")


with a variable $eps$ and function $h$:

eps = var('eps')
h = function('h')(r,th)


The metric of this space is:

gdd = M.metric()

gdd[0,0] = -eps;    gdd[1,1] = r;    gdd[2,2] = h;    gdd[3,3] = 1


With this metric, I calculate numerous tensors (Riemann, Ricci, ...), which take a long time to compute. Therefore, I would like to save those tensors in a single file and then import them back every time I need them. I have tried using

np.save('file.npy', gdd)

but when I open file.npy I read the following:

Error! /Users/.../file.npy is not UTF-8 encoded

Is there a way I can save various symbolic tensors (which depend on functions and variables, as the one shown above) in a file, and load them back separately?

edit retag close merge delete

Yes. However, if I save it this way:

tensors = {'metric': gdd}
outfile = open('file','wb')
pickle.dump(tensors,outfile)
outfile.close()


when I import it back as:

infile = open('file','rb')
infile.close()


and I print(new_dict), I get:

"Lorentzian metric g on the 4-dimensional Lorentzian manifold M"

I am not capable of recovering the whole tensor. If I save the metric as

tensors = {'metric': gdd[:]} or tensors = {'metric': gdd.expr())


I get errors...

Sort by » oldest newest most voted See the built-in save and load which are made for this purpose. In one session with gdd defined you can do

sage: save(gdd, 'gdd')


and in another you can do

sage: gdd = load('gdd.sobj')
sage: gdd[0,0]
-eps


It uses pickling internally. If you want you can specify a directory as part of the filename.

more

1

If I print gdd[0,0] or gdd[1,1], everything goes fine. However, when printing gdd[2,2], which is the one containing the function h, I get the error:

"TypeError: sequence item 0: expected str instance, bytes found"

and the kernel restarts:

"The kernel appears to have died. It will restart automatically."

If it works fine for you maybe the reason is that I have installed some packages that are in conflict with save and load...