Skip to the content.

ParSub API Reference

This document describes the public Python API of ParSub, organized by module. For the command line and the REST API see the User Guide.

Main Package

parsub

__version__

The package version string, e.g. "0.2.1" (also shown by parsub --version).

analyze_latex(latex_source, output_dir="./output", source_name=None) -> AnalysisResult

Parse, analyze and generate code for a LaTeX string. Writes generated_computation.py and analysis.json into output_dir. See AnalysisResult.

analyze_latex_file(latex_file, output_dir="./output") -> str

Same for a file; returns the path of the generated Python script.

from parsub import analyze_latex_file

code_file = analyze_latex_file("paper.tex", "./results")

run_generated_code(code_path, output_dir=None, timeout=600, capture_output=True) -> subprocess.CompletedProcess

Run a generated script in a separate Python process. Results are written to output_dir (default: the script’s directory). Raises FileNotFoundError for a missing script and subprocess.TimeoutExpired when timeout seconds are exceeded.

Pipeline Module

parsub.core.pipeline

AnalysisResult

Returned by analyze_latex:

analyze_latex(...), analyze_latex_file(...), run_generated_code(..., task_timeout=None)

The implementations behind the top-level functions. task_timeout sets the per-task time limit of the generated script.

read_run_summary(output_dir) -> dict | None

Load data/summary.json written by a generated script.

Parser Module

parsub.parser.latex_parser

parse_latex_source(latex_source: str) -> Dict[str, Any]

Parse LaTeX source and extract mathematical expressions and metadata.

Returns a dictionary containing:

Expression dictionary:

Example:

from parsub.parser.latex_parser import parse_latex_source

result = parse_latex_source("$E = mc^2$")
print(result["expressions"][0]["sympy_expr"])  # Eq(E, c**2*m)

LaTeXParser

Parser class. LaTeXParser(context_chars=400).parse(latex_source) returns the same dictionary as parse_latex_source.

MathExpression

Dataclass behind the expression dictionaries (to_dict() produces them).

parsub.parser.latex_to_sympy

Helpers used by the parser:

Special-function notation (hypergeometric, Pochhammer, orthogonal polynomials, Bessel functions, indexed functions and primes for derivatives) is described in the User Guide.

Analyzer Module

parsub.analyzer.expression_analyzer

analyze_expressions(expressions, context=None) -> List[Dict[str, Any]]

Analyze expressions and return JSON-serialisable task dictionaries.

Args:

Function definitions found among the expressions are substituted into the other expressions, symbol definitions provide values for fixed parameters, and repeated definitions of the same function produce verify tasks that compare them.

Task dictionary:

Example:

from parsub.analyzer.expression_analyzer import analyze_expressions

tasks = analyze_expressions(parsed["expressions"], {
    "goals": parsed["goals"],
    "methods": parsed["methods"],
    "assignments": parsed["assignments"],
})

ExpressionAnalyzer

ExpressionAnalyzer().analyze_expressions(expressions, context) returns ComputationTask objects instead of dictionaries (task.to_dict() converts them).

Code Generation Module

parsub.generator.code_generator

generate_code_from_tasks(tasks, output_dir="./output", source_name=None) -> str

Generate Python code from task dictionaries, save it as generated_computation.py and return its path.

CodeGenerator

parsub.generator.runtime

The helper library that is embedded in every generated script (and importable directly):

Shared Knowledge

parsub.core.parameters

CLI Module

parsub.cli.main

The Typer application app behind the parsub command (main() is the console-script entry point). See the User Guide.

REST API Module

parsub.api.main

See the User Guide for the endpoints.

Dependencies

Error Handling

  1. Graceful degradation: a formula that cannot be converted is reported, not guessed; a task that fails or times out is recorded in data/summary.json while the others continue.
  2. Informative errors: the CLI prints clear messages and returns exit code 1; the REST API returns 400/403/404/413/504 with a detail message.
  3. Validation: inputs are validated at the CLI and REST API boundaries.

Extending ParSub

Adding a goal type (e.g. fourier_transform)

  1. Add keywords to GOAL_KEYWORDS (and GOAL_PRIORITY) in expression_analyzer.py.
  2. Add a fourier_task(ctx, task_id, expr, ...) function to generator/runtime.py.
  3. Add a branch for the goal in CodeGenerator._generate_task_code.
  4. Add tests.

Adding an output format

Extend save_data in generator/runtime.py (the format is chosen by file extension).

Custom LaTeX constructs

Extend clean_latex / _postprocess in parser/latex_to_sympy.py.

Changelog

See the changelog.