You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Sphinx Autodoc自定义LaTeX导言区以支持algpseudocode包及自定义数学宏?

Customizing Sphinx LaTeX Preamble for Napoleon Autodoc

To add LaTeX's algpseudocode support and custom math macros to your Sphinx-generated documentation (using Napoleon Autodoc), follow these straightforward steps:


Step 1: Update Sphinx Configuration (conf.py)

The core change happens in your project's conf.py file, where you’ll extend the LaTeX preamble via the latex_elements dictionary. This lets you load required packages and define your custom math shortcuts.

Example Configuration:

# Enable necessary extensions
extensions = [
    'sphinx.ext.autodoc',       # Auto-generate docs from docstrings
    'sphinx.ext.napoleon',      # Support Google/Numpy-style docstrings
    'sphinx.ext.mathjax',       # For HTML math rendering (optional but recommended)
]

# Customize LaTeX output settings
latex_elements = {
    'preamble': r'''
        % Load packages for algorithms and advanced math
        \usepackage{algorithm}    % Base package for algorithm environments
        \usepackage{algpseudocode} % For pseudocode syntax highlighting
        \usepackage{amsmath}      % Required for complex math symbols and macros
        
        % Define your custom math macros here
        \newcommand{\R}{\mathbb{R}}          % Set of real numbers
        \newcommand{\norm}[1]{\left\|#1\right\|} % Euclidean norm
        \newcommand{\inner}[2]{\langle#1,#2\rangle} % Inner product
        \newcommand{\argmin}{\operatornamewithlimits{argmin}} % Argmin operator
        % Add any other macros you need!
    ''',
}

Step 2: Embed algpseudocode in Docstrings

Since Napoleon converts docstrings to reStructuredText, you’ll use the .. raw:: latex directive to wrap your algorithm code (as algpseudocode is LaTeX-specific). This ensures the code renders correctly in the PDF output.

Example Docstring with Algorithm:

def compute_euclidean_norm(vector):
    """
    Calculate the Euclidean norm of an input vector.
    
    .. raw:: latex
    
        \begin{algorithm}
            \caption{Euclidean Norm Calculation}
            \begin{algorithmic}[1]
                \Procedure{ComputeNorm}{$\mathbf{v} \in \R^n$}
                    \State $sum \gets 0$
                    \For{$i = 1$ \To $n$}
                        \State $sum \gets sum + v_i^2$
                    \EndFor
                    \State $\norm{\mathbf{v}} \gets \sqrt{sum}$
                    \State \Return $\norm{\mathbf{v}}$
                \EndProcedure
            \end{algorithmic}
        \end{algorithm}
    
    Args:
        vector (list): Input vector in $\R^n$.
    
    Returns:
        float: Euclidean norm $\norm{\vector}$.
    """
    return sum(x**2 for x in vector)**0.5

Note: Raw LaTeX blocks only render in PDF output (generated via sphinx-build -b latex). For HTML rendering, consider extensions like sphinxcontrib-algorithms, but this solution focuses on your LaTeX requirement.


Step 3: Use Custom Math Macros in Docstrings

Your pre-defined macros work seamlessly in Sphinx’s math environments (either inline with $...$ or block-style with .. math::).

Example Docstring with Custom Macros:

def vector_inner_product(u, v):
    """
    Compute the inner product of two vectors.
    
    The inner product is defined as:
    .. math::
        \inner{\mathbf{u}}{\mathbf{v}} = \sum_{i=1}^d u_i v_i
    where $\mathbf{u}, \mathbf{v} \in \R^d$.
    
    Args:
        u (list): First vector in $\R^d$.
        v (list): Second vector in $\R^d$.
    
    Returns:
        float: Inner product $\inner{\mathbf{u}}{\mathbf{v}}$.
    """
    return sum(a*b for a, b in zip(u, v))

Key Tips

  • Double-check your raw LaTeX blocks for valid syntax (no missing \begin/\end pairs or typos).
  • To make your math macros work in HTML output too, mirror them in the MathJax configuration in conf.py:
    mathjax_config = {
        'TeX': {'Macros': {
            'R': r'\mathbb{R}',
            'norm': r'\left\|#1\right\|',
            # Match your LaTeX macros here
        }}
    }
    
  • Test your PDF output regularly with sphinx-build -b latex docs/ build/latex && cd build/latex && pdflatex yourdocs.tex to catch any LaTeX errors early.

内容的提问来源于stack exchange,提问作者dan_sk8r

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 22:17:30