Last active
February 28, 2020 11:33
-
-
Save riedel/646d542f2d5948022bb896d859b19e4f to your computer and use it in GitHub Desktop.
SymPy IPython Printer trick
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sympy import * | |
class DefinitionSet(): | |
def __init__(self): | |
self.__dict__["__dict2__"]={} # for not fully bound ones --> __getattr__ | |
def __setattr__(self, name, value): | |
if name in self.__dict__ or name in self.__dict2__: | |
raise TypeError("Immutable: attribute \"%s\" exists"%name) | |
else: | |
s=self.subs(value) | |
if(value!=s): | |
display(Eq(Symbol(name),Eq(value,s,evaluate=False),evaluate=False)) | |
else: | |
display(Eq(Symbol(name),value,evaluate=False)) | |
if(isinstance(s, Expr) and bool(s.free_symbols)): | |
self.__dict2__[name]=s | |
else: | |
self.__dict__[name]=s | |
def __getattr__(self,name): | |
if name in self.__dict2__: | |
s=self.subs(self.__dict2__[name]) | |
if(s!=self.__dict2__[name]): | |
display(Eq(Symbol(name),Eq(self.__dict2__[name],s,evaluate=False),evaluate=False)) | |
self.__dict__[name]=s | |
del(self.__dict2__[name]) | |
return(s) | |
else: | |
return Symbol(name) | |
def subs(self,exp): | |
ret=exp | |
if(isinstance(exp, Expr)): | |
for i in ret.free_symbols: | |
if(i.name in self.__dict__): | |
ret=ret.subs(i,self.__dict__[i.name]) | |
if(i.name in self.__dict2__): | |
ret=ret.subs(i,self.__getattr__(i.name)) | |
return ret | |
class Symbolizer: | |
"""create symbols on the fly!?""" | |
def __setattr__(self, name, value): | |
raise TypeError("Use DefinitionSet to set \"%s\""%name) | |
def __getattr__(self,name): | |
return Symbol(name) | |
%config InteractiveShell.ast_node_interactivity="none" | |
ß = DefinitionSet() | |
ẞ = Symbolizer() | |
ß. a=1 | |
ß. b=sqrt(ẞ.a*ẞ.f) | |
ß. f=2 | |
ß. a_2=ẞ.b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment