Ask Your Question
1

how to restore latex_name

asked 2026-04-01 22:53:54 +0200

Karl007 gravatar image

updated 2026-04-02 10:32:02 +0200

I wonder how to restore the latex_name attribute of a function or variable after saving to a file

my (updated) code is:

var('y')
fx = function('fx',latex_name=r'f_x')
eq=fx(y)+fx(y).diff(y)
save([y,fx,eq],'test')

check the latex expression:

> print(latex(eq)) 
f_x\left(y\right) + \frac{\partial}{\partial y}f_x\left(y\right)

In a new session I load the definitions and print the latex forms:

y,fx,eq=load('test')
print(latex(fx))
print(latex(eq))

with output

f_x
{\rm fx}\left(y\right) + \frac{\partial}{\partial y}{\rm fx}\left(y\right)

curiously the latex form of the function 'f_x' is preserved but it is not used in the symbolic expression 'eq', where only 'fx' appears.

So I thought I do the following: I define a new function and substitute the new function in eq

ffx = function('ffx',latex_name=r'f_x')
print( latex( eq.substitute_function(fx,ffx) ) )

but I still get fx in the output, it seems fx in eq is not the function fx , I cannot even substitute it against another function!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2026-04-02 11:44:50 +0200

Karl007 gravatar image

I have found a workaround: save the expression as a string and evaluate the string after reading it in in a new session.

Code block saving:

var('y')
fx = function('fx',latex_name=r'f_x')
eq=fx(y)+fx(y).diff(y)
eq_str = str(eq)
with open('test.txt', 'w') as f:
    eqs_str = f.write(eq_str)

Code block reading:

var('y')
fx = function('fx',latex_name=r'f_x')
with open('test.txt', 'r') as f:
    eq_str = f.read();
eq=sage_eval(eq_str, locals={'y':y, 'fx':fx})

then I get

print(latex(eq))
f_x\left(y\right) + \frac{\partial}{\partial y}f_x\left(y\right)

with the correct 'f_x' latex expression! The only drawback is that it is rather cumbersome to have to write down the locals-dictionary. I have around 15 variables and functions.

edit flag offensive delete link more

Comments

At last I also found a way to generate the locals dictionary:

Start the reading code block with

initial_globals = set(globals().keys());

then define your variables and funcitons and then do

my_globals=set(globals().keys()) - initial_globals;
my_locals = {name: globals()[name] for name in my_globals  }
my_locals.update({'x': x})

note you have to add the variable 'x' by hand, since it is predefined and will also be in initial_globals my_locas can then be used in

sage_eval(eq_str, locals=my_locals)
Karl007 gravatar imageKarl007 ( 2026-04-02 16:54:37 +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

Stats

Asked: 2026-04-01 22:53:54 +0200

Seen: 72 times

Last updated: Apr 02