跳转至

数学公式 API

数学模块提供 LaTeX 公式渲染后端的注册与管理。

模块概览

导出 类型 职责
MathBackend Protocol 后端接口协议
SVGFragment dataclass 渲染结果(SVG 内容 + 尺寸)
QuickJaxBackend 默认后端(基于 QuickJax / MathJax v4)
register_backend() 函数 注册自定义后端
set_default_backend() 函数 设置默认后端
get_backend() 函数 获取后端实例
get_default_backend_name() 函数 获取默认后端名称

基本用法

from latticesvg.math import get_backend

backend = get_backend()  # 默认 QuickJax
fragment = backend.render(r"E = mc^2", font_size=20, display=True)
print(fragment.width, fragment.height)
print(fragment.svg)  # SVG 字符串片段

自定义后端

from latticesvg.math import register_backend, set_default_backend

class MyBackend:
    def render(self, latex: str, font_size: float, display: bool = True):
        # 返回 SVGFragment
        ...

register_backend("my_backend", MyBackend)
set_default_backend("my_backend")

自动生成的 API 文档

后端管理

math

Math formula rendering — pluggable backend system.

Default backend: quickjax (in-process MathJax v4 via QuickJS).

Usage::

from latticesvg.math import get_backend

backend = get_backend()          # default QuickJax
frag = backend.render(r"E=mc^2", font_size=16)
MathBackend

Bases: Protocol

Abstract interface for math rendering backends.

render
render(latex: str, font_size: float) -> SVGFragment

Render latex at font_size and return an SVG fragment.

Source code in src/latticesvg/math/backend.py
def render(self, latex: str, font_size: float) -> SVGFragment:
    """Render *latex* at *font_size* and return an SVG fragment."""
    ...
available
available() -> bool

Return True if this backend's dependencies are satisfied.

Source code in src/latticesvg/math/backend.py
def available(self) -> bool:
    """Return ``True`` if this backend's dependencies are satisfied."""
    ...
SVGFragment dataclass
SVGFragment(svg_content: str, width: float, height: float, depth: float = 0.0)

Result of rendering a LaTeX expression to SVG.

svg_content instance-attribute
svg_content: str

Inner SVG markup (without outer <svg> wrapper).

width instance-attribute
width: float

Precise width in px.

height instance-attribute
height: float

Precise height in px.

depth class-attribute instance-attribute
depth: float = 0.0

Depth below baseline in px (for inline alignment).

QuickJaxBackend
QuickJaxBackend()

Render LaTeX math via QuickJax (in-process MathJax v4).

QuickJax runs MathJax inside an embedded QuickJS engine — no Node.js, no subprocess, no network. It is the recommended and default backend.

Source code in src/latticesvg/math/backend.py
def __init__(self) -> None:
    self._renderer = None
    self._cache: Dict[Tuple[str, float, bool], SVGFragment] = {}
register_backend
register_backend(name: str, cls: Type[MathBackend]) -> None

Register a math backend class under name.

Source code in src/latticesvg/math/__init__.py
def register_backend(name: str, cls: Type[MathBackend]) -> None:
    """Register a math backend class under *name*."""
    _backend_registry[name] = cls
    # Invalidate cached instance if the class changed
    _backend_instances.pop(name, None)
set_default_backend
set_default_backend(name: str) -> None

Set the global default math backend by name.

Source code in src/latticesvg/math/__init__.py
def set_default_backend(name: str) -> None:
    """Set the global default math backend by name."""
    global _default_backend_name
    _default_backend_name = name
get_default_backend_name
get_default_backend_name() -> str

Return the name of the current default backend.

Source code in src/latticesvg/math/__init__.py
def get_default_backend_name() -> str:
    """Return the name of the current default backend."""
    return _default_backend_name
get_backend
get_backend(name: Optional[str] = None) -> MathBackend

Return a (cached) backend instance.

PARAMETER DESCRIPTION
name

Backend name. None → use the global default.

TYPE: str or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If the requested backend is not registered.

RuntimeError

If the backend reports itself as unavailable.

Source code in src/latticesvg/math/__init__.py
def get_backend(name: Optional[str] = None) -> MathBackend:
    """Return a (cached) backend instance.

    Parameters
    ----------
    name : str or None
        Backend name.  ``None`` → use the global default.

    Raises
    ------
    ValueError
        If the requested backend is not registered.
    RuntimeError
        If the backend reports itself as unavailable.
    """
    if name is None:
        name = _default_backend_name

    if name in _backend_instances:
        return _backend_instances[name]

    cls = _backend_registry.get(name)
    if cls is None:
        raise ValueError(
            f"Unknown math backend {name!r}. "
            f"Registered: {list(_backend_registry)}"
        )

    inst = cls()
    if not inst.available():
        raise RuntimeError(
            f"Math backend {name!r} is not available. "
            f"Check its dependencies (pip install quickjax)."
        )
    _backend_instances[name] = inst
    return inst

QuickJax 后端

backend

Math backend protocol and QuickJax implementation.

SVGFragment dataclass
SVGFragment(svg_content: str, width: float, height: float, depth: float = 0.0)

Result of rendering a LaTeX expression to SVG.

svg_content instance-attribute
svg_content: str

Inner SVG markup (without outer <svg> wrapper).

width instance-attribute
width: float

Precise width in px.

height instance-attribute
height: float

Precise height in px.

depth class-attribute instance-attribute
depth: float = 0.0

Depth below baseline in px (for inline alignment).

MathBackend

Bases: Protocol

Abstract interface for math rendering backends.

render
render(latex: str, font_size: float) -> SVGFragment

Render latex at font_size and return an SVG fragment.

Source code in src/latticesvg/math/backend.py
def render(self, latex: str, font_size: float) -> SVGFragment:
    """Render *latex* at *font_size* and return an SVG fragment."""
    ...
available
available() -> bool

Return True if this backend's dependencies are satisfied.

Source code in src/latticesvg/math/backend.py
def available(self) -> bool:
    """Return ``True`` if this backend's dependencies are satisfied."""
    ...
QuickJaxBackend
QuickJaxBackend()

Render LaTeX math via QuickJax (in-process MathJax v4).

QuickJax runs MathJax inside an embedded QuickJS engine — no Node.js, no subprocess, no network. It is the recommended and default backend.

Source code in src/latticesvg/math/backend.py
def __init__(self) -> None:
    self._renderer = None
    self._cache: Dict[Tuple[str, float, bool], SVGFragment] = {}