Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Adds SymPy expression rendering support (#1412) (#2261)

agostof64762eb92b5c
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 8595589656..26621c169f 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -134,6 +134,7 @@ def _version_check(
class DependencyManager:
"""Utilities for checking the status of dependencies."""
+ sympy = Dependency("sympy")
pandas = Dependency("pandas")
polars = Dependency("polars")
ibis = Dependency("ibis")
diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.py
index d946e9927c..b93018918b 100644
--- a/marimo/_output/formatters/formatters.py
+++ b/marimo/_output/formatters/formatters.py
@@ -24,6 +24,7 @@ from marimo._output.formatters.pandas_formatters import PandasFormatter
from marimo._output.formatters.plotly_formatters import PlotlyFormatter
from marimo._output.formatters.seaborn_formatters import SeabornFormatter
from marimo._output.formatters.structures import StructuresFormatter
+from marimo._output.formatters.sympy_formatters import SympyFormatter
from marimo._output.formatters.tqdm_formatters import TqdmFormatter
# Map from formatter factory's package name to formatter, for third-party
@@ -45,6 +46,7 @@ THIRD_PARTY_FACTORIES: dict[str, FormatterFactory] = {
AnyWidgetFormatter.package_name(): AnyWidgetFormatter(),
TqdmFormatter.package_name(): TqdmFormatter(),
LetsPlotFormatter.package_name(): LetsPlotFormatter(),
+ SympyFormatter.package_name(): SympyFormatter(),
}
# Formatters for builtin types and other things that don't require a
diff --git a/marimo/_output/formatters/sympy_formatters.py b/marimo/_output/formatters/sympy_formatters.py
new file mode 100644
index 0000000000..cad1fbcd63
--- /dev/null
+++ b/marimo/_output/formatters/sympy_formatters.py
@@ -0,0 +1,62 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any
+
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.formatters.formatter_factory import FormatterFactory
+
+
+def patch_sympy(*objs: Any) -> None:
+ import marimo as mo
+
+ """adds the _mime_() method to sympy objects
+ e.g.
+ Symbol._mime_ = sympy_html
+ example:
+ patch_sympy(Symbol, Integral)
+ """
+ from sympy import latex # type: ignore
+
+ for obj in objs:
+ # the lambda below is our sympy_html
+ obj._mime_ = lambda obj: (
+ "text/html",
+ mo.md(f"""\\[{latex(obj)}\\]""").text,
+ )
+
+
+def sympy_as_html(obj: Any) -> tuple[KnownMimeType, str]:
+ from sympy import latex
+
+ import marimo as mo
+
+ """creates HTML output from a Printable Sympy object
+ e.g.
+ example:
+ integral = Integral(x**2, x)
+ sympy_as_html(integral)
+ """
+ return ("text/html", mo.md(f"""\\[{latex(obj)}\\]""").text)
+
+
+class SympyFormatter(FormatterFactory):
+ @staticmethod
+ def package_name() -> str:
+ return "sympy"
+
+ def register(self) -> None:
+ from sympy.core.basic import Printable # type: ignore
+
+ # We will monkey-patch the Printable class so most Sympy constructs
+ # that can be "pretty-printed" with sympy.latex
+ # can also be rendered in marimo.
+ # One way to test if an expression is supported is
+ # with latex(expr)
+ # e.g. latex(x**2) --> x^{2}
+ patch_sympy(Printable)
+
+ # from marimo._output import formatting
+ # @formatting.formatter(Integral)
+ # def _show_integral(integral: Integral) -> tuple[KnownMimeType, str]:
+ # return sympy_as_html(integral)
diff --git a/pyproject.toml b/pyproject.toml
index 58180037d0..3f047ac822 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -149,6 +149,7 @@ testoptional = [
"anthropic==0.34.1",
# exporting as ipynb
"nbformat >=5.10.4",
+ "sympy>=1.13.2",
]
[project.urls]
diff --git a/tests/_output/formatters/test_sympy.py b/tests/_output/formatters/test_sympy.py
new file mode 100644
index 0000000000..ecd430463c
--- /dev/null
+++ b/tests/_output/formatters/test_sympy.py
@@ -0,0 +1,120 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._output.formatters.formatters import register_formatters
+from marimo._output.formatting import (
+ get_formatter,
+)
+
+HAS_DEPS = DependencyManager.sympy.has()
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_sympy_formatters_basic_symbols() -> None:
+ register_formatters()
+
+ from sympy import symbols
+
+ x, y = symbols("x y")
+
+ # x Symbol
+ formatter = get_formatter(x, include_opinionated=False)
+ assert formatter
+ mime, content = formatter(x)
+ assert mime == "text/html"
+ assert content.find(r"||[x||]") > 0
+
+ # y Symbol
+ formatter = get_formatter(y, include_opinionated=False)
+ assert formatter
+ mime, content = formatter(y)
+ assert mime == "text/html"
+ assert content.find(r"||[y||]") > 0
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_sympy_formatters_addition() -> None:
+ register_formatters()
+
+ from sympy import symbols
+
+ x, y, z = symbols("x y z")
+ out_exp = x + y + z
+ # x + y + z
+ formatter = get_formatter(out_exp, include_opinionated=False)
+ assert formatter
+ mime, content = formatter(out_exp)
+ assert mime == "text/html"
+ assert content.find("||[x + y + z||]") > 0
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_sympy_formatters_power() -> None:
+ register_formatters()
+
+ from sympy import symbols
+
+ x, y, z = symbols("x y z")
+ x_squared = x**2
+
+ # x^2
+ formatter = get_formatter(x_squared, include_opinionated=False)
+ assert formatter
+ mime, content = formatter(x_squared)
+ assert mime == "text/html"
+ assert content.find("||[x^{2}||]") > 0
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_sympy_formatters_matrix() -> None:
+ register_formatters()
+
+ from sympy import Matrix, symbols
+
+ x, y, z = symbols("x y z")
+
+ # numeric matrix
+ M = Matrix([[1, 2], [3, 4]])
+ B = Matrix([[1 * x, 2 * y], [z, 4]])
+
+ # numeric matrix
+ formatter = get_formatter(M, include_opinionated=False)
+ assert formatter
+ mime, content = formatter(M)
+ assert mime == "text/html"
+ assert (
+ content.find(
+ r"||[\left[\begin{matrix}1 & 2\\3 & 4\end{matrix}\right]||]" # noqa: E501
+ )
+ > 0
+ )
+ # symbolic matrix
+ formatter = get_formatter(B, include_opinionated=False)
+ assert formatter
+ mime, content = formatter(B)
+ assert mime == "text/html"
+ assert (
+ content.find(
+ r"||[\left[\begin{matrix}x & 2 y\\z & 4\end{matrix}\right]||]" # noqa: E501
+ )
+ > 0
+ )
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_sympy_formatters_Integral() -> None:
+ register_formatters()
+
+ from sympy import Integral, sqrt, symbols
+
+ x, y, z = symbols("x y z")
+ out_exp = Integral(sqrt(1 / x), x)
+
+ # symbolic integral
+ formatter = get_formatter(out_exp, include_opinionated=False)
+ assert formatter
+ mime, content = formatter(out_exp)
+ assert mime == "text/html"
+ assert content.find(r"||[\int \sqrt{\frac{1}{x}}\, dx||]") > 0