Package: latexvm
Latex-VM (Virtual Machine)Latex-VM is a simple context environment for mathematical expressions in LaTeX. It supports variable and function declaration.Type AliasesTypeDefinitionVarnamestrExpressionStrstrEnvironmentVariablesDict[Varname, Any]APIclassActionResult:defok(self)->boolclassGraphSession:@staticmethoddefnew(env:EnvironmentVariables={},rules:Dict[str,str]={})->"GraphSession"defexecute(self,input:str,simplify:bool=False)->ActionResult[CalculatorAction,str]defget_env_functions(self)->EnvironmentVariablesdefget_env_variables(self)->EnvironmentVariablesdefget_env(self)->EnvironmentVariablesdefforce_resolve_function(self,input:str,use_sub_rule:bool=True)->ActionResult[None,str]defadd_sub_rule(self,pattern:str,replacement:str)->Nonedefremove_sub_rule(self,pattern:str)->Nonedefget_sub_rules(self)->Dict[str,str]defclear_session(self)->NoneExample Usage# Create a new graph sessionsession=GraphSession.new()# Assignment expressionsession.execute("y = 20")# Action: CalculatorAction.VARIABLE_ASSIGNMENT, Ok(20)# Function declaration expressionsession.execute("double(x) = x * 2")# Action: CalculatorAction.FUNCTION_DEFINITION, Ok(double_func(x) = x * 2)session.execute("pow(x) = x^2")# Action: CalculatorAction.FUNCTION_DEFINITION, Ok(pow_func(x) = x^2)# Statement expressionsession.execute("double(pow(2))")# Action: CalculatorAction.STATEMENT_EXECUTION, Ok(8)# Function force-resolve (Does not converge to a value)session.force_resolve_function("double(pow(x+2))")# Ok((x + 2)**2*2)Environment Variables and Value RetrievalNote: All getters returns a copy in order to prevent mutation of internal variables.session=GraphSession.new()session.execute("y = 20")session.execute("double(x) = x * 2")# Get all environment variablessession.get_env()# {'y': '20', 'double_func': (['x'], 'x * 2')}# Get only function varaiblessession.get_env_functions()# {'double_func': (['x'], 'x * 2')}# Get only variablessession.get_env_variables()# {'y': '20'}# Session can be clearedsession.clear_session()Result and Error HandlingMethods which returns theActionResulttype conforms to the following handling.Note:ActionResult.actionholds the action value....result=session.execute(...)ifresult.ok():...# use the result value# Note: The result.message contains the valueelse:...# handle errors...# Note: The result.message contains the error messageSession LoadingSessions can easily be loaded by passing in pre-existing environment variables.session_1=GraphSession.new()session_1.execute("double(x) = x * 2")session_2=GraphSession.new(session.get_env())res=session_2.execute("double(5)")print(res.message)# 10SimplificationExpression simplification is optional. In cases where the input latex is very complex, it can greatly affect
performance. For this reason, thesimplifyflag is defaulted toFalse. Addtionally, the simplify function
is run with a timeout of3seconds, if failed, it will just yield the result without simplifying.session=GraphSession.new()# Action: CalculatorAction.FUNCTION_DEFINITION, Ok(f_func(x) = \frac{x}{3} + 3 + 20 + 20 + 20)session.execute(r"f(x) = \frac{x}{3}+ 3 + y + y + y")# Action: CalculatorAction.FUNCTION_DEFINITION, Ok(f_func(x) = \frac{x}{3} + 63)session.execute(r"f(x) = \frac{x}{3}+ 3 + y + y + y",simplify=True)Substitution RulesTheGraphSession.force_resolve_functionmethod returns a Pythonic representation of the input. However, this representation may need to be modified in order to be usable. For this reason, there are substitution rules that can be applied to the output.This behavior is enabled default, to resolve without using substitution rules, setuse_sub_ruletoFalse.gs.execute(r"make_abs(x) = \left|x\right|")gs.execute(r"pow(a, b) = a^{b}")# Without any substituion ruleprint(gs.force_resolve_function(r"pow(make_abs(x), make_abs(y))"))# Ok(Abs(x)**Abs(y))# We want abs(...) instead of Abs(...)gs.add_sub_rule("Abs","abs")gs.force_resolve_function(r"pow(make_abs(x), make_abs(y))")# Ok(abs(x)**abs(y))# We need pow expressed using '^'gs.add_sub_rule(r"\*\*","^")gs.force_resolve_function(r"pow(make_abs(x), make_abs(y))")# Ok(abs(x)^abs(y))# Resolve without using substitution rulesgs.force_resolve_function(r"pow(make_abs(x), make_abs(y))",use_sub_rule=False)# Ok(Abs(x)**Abs(y))LaTeX overrideYou can override LaTeX functions by declaring a function with the same name. This allows you to customize the functionality of the function according to your needs.# Works perfectly fineprint(gs.force_resolve_function(r"\sin\left(x\right)"))# Ok(sin(x))# Overridegs.execute("double(x) = 2 x")gs.execute("sin(a) = double(a)")# Sin is now overriddenprint(gs.force_resolve_function(r"\sin\left(x\right)"))# Ok(x*2)