Ask Your Question

Save tensor in file

asked 2021-11-07 23:09:57 +0200

keko gravatar image

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'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 flag offensive close merge delete


Max Alekseyev gravatar imageMax Alekseyev ( 2021-11-07 23:45:43 +0200 )edit

Yes. However, if I save it this way:

tensors = {'metric': gdd}
outfile = open('file','wb')

when I import it back as:

infile = open('file','rb')
new_dict = pickle.load(infile)['metric']

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...

keko gravatar imagekeko ( 2021-11-08 11:19:20 +0200 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2021-11-08 18:56:33 +0200

rburing gravatar image

updated 2021-11-08 19:02:58 +0200

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]

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

edit flag offensive delete link more



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...

keko gravatar imagekeko ( 2021-11-09 09:27:46 +0200 )edit

@keko this looks like a bug to me, reported as trac ticket #32843.

rburing gravatar imagerburing ( 2021-11-09 20:22:34 +0200 )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

1 follower


Asked: 2021-11-07 23:09:57 +0200

Seen: 430 times

Last updated: Nov 08 '21