# ----------------------------------------------------------------------------# SymForce - Copyright 2022, Skydio, Inc.# This source code is under the Apache 2.0 license found in the LICENSE file.# ----------------------------------------------------------------------------"""Helpers for interactive use in a Jupyter notebook with an IPython kernel."""importIPythonimportsympyassympy_pysympy_py.init_printing()importsymforceimportsymforce.symbolicassffromsymforceimportopsfromsymforceimporttypingasTifsymforce.get_symbolic_api()=="symengine":sf.sympy.init_printing()
[docs]defset_notebook_defaults()->None:""" Change SymForce defaults to be more friendly for Jupyter notebooks. - Use LaTeX-friendly symbols (`ops.StorageOps.set_use_latex_friendly_symbols`) """ops.StorageOps.set_use_latex_friendly_symbols(True)
[docs]defdisplay(*args:T.Any)->None:""" Display the given expressions in latex, or print if not an expression. """# TODO(aaron): This should all be unnecessary on new symengine. The problem is that our version# of symengine does not define `DenseMatrixBase._repr_latex_`, so we need to convert symengine# matrices to sympyifsymforce.get_symbolic_api()=="sympy":IPython.display.display(*args)returnconverted_args=[]forarginargs:ifisinstance(arg,sf.Matrix):converted_args.append(arg.mat)else:converted_args.append(arg)try:IPython.display.display(*[sympy_py.S(converted_arg,strict=True)forconverted_arginconverted_args])except(sympy_py.SympifyError,AttributeError,TypeError):IPython.display.display(*args)
[docs]defdisplay_code(code:str,language:T.Optional[str]=None)->None:""" Display code with syntax highlighting. Args: code: Source code language: {python, c++, anything supported by pygments} """IPython.display.display(IPython.display.Code(code,language=language))
[docs]defdisplay_code_file(path:T.Openable,language:str)->None:""" Display code from a file path with syntax highlighting. Args: path: Path to source file language: {python, c++, anything supported by pygments} """withopen(path)asf:code=f.read()display_code(code,language)
[docs]defprint_expression_tree(expr:sf.Expr,assumptions:bool=False)->None:""" Print a SymPy expression tree, ignoring node attributes Args: expr: The expression to print assumptions: Whether to include assumption information for nodes. See ``sympy.printing.tree`` for more information. """fromsympy.printing.treeimporttreeunfiltered_tree=tree(expr,assumptions=assumptions).split("\n")filtered_tree="\n".join(vfori,vinenumerate(unfiltered_tree)if"+-"invori==0)print(filtered_tree)