0

This question is not a duplicate of this one, even if it is closely related.

When I use sympy on a jupyter notebook, it nicely format the output of my equations with MathJax, like this:

sympy latex output demonstration

If we have a look at the source of the notebook, we can see that the output saved is made of two parts text/plain and text/latex :

"outputs": [
 {
  "data": {
   "text/latex": [
    "$\\displaystyle \\frac{- b - \\sqrt{- 4 a c + b^{2}}}{2 a}$"
   ],
   "text/plain": [
    "(-b - sqrt(-4*a*c + b**2))/(2*a)"
   ]
  },
  "execution_count": 22,
  "metadata": {},
  "output_type": "execute_result"
 }
],
"source": [
 "import sympy\n",
 "\n",
 "a, b, c = sympy.symbols('a b c')\n",
 "(-b - sympy.sqrt(b**2 - 4*a*c)) / (2*a)"
]

Even if I know how to print in a latex form (cf. link above), I would like to make a custom object behave as a sympy one, and be able to be displayed naturally as latex math in a jupyter notebook (and if I could fill both the text/latex and text/plain fields it would be nice !). If anyone had a clue on how to do it :)

yota
  • 2,020
  • 22
  • 37
  • I'm not quite sure what your specifically want to do. You may want to get more Jupyter people's eyes on it by posting at [the Jupyter Community Discourse Forum](https://discourse.jupyter.org/). Please note here if you end up doing that. It sounded like digging in how sympy works and how MathJax gets made may provide you a route? Maybe looking into how [latexify_py](https://twitter.com/KhuyenTran16/status/1575136709544747008) or [latex2sympy2](https://github.com/OrangeX4/latex2sympy) would help you where you want to go? – Wayne Oct 20 '22 at 18:41
  • Thanks for the advice ! I will ask the jupyter community and update this page if I find something. – yota Oct 21 '22 at 16:54

1 Answers1

0

I asked the forum and got a fast answer (link), as promised, I copy/paste it here (all credits goes to bollwyvl):

The key resource for the plumbing is in the Integrating your objects with IPython section of the docs.

Here’s an example:

class Foo:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def _repr_mimebundle_(self, **kwargs):
        return {
            "text/plain": f"x={self.x}",
            "text/latex": f"$x = {self.x}\\\\y = {self.y}$"
        }

foo = Foo(1, 2)
foo

yields:

enter image description here

yota
  • 2,020
  • 22
  • 37