Metadata-Version: 2.4
Name: pylatex-report
Version: 0.1.1
Summary: Compose technical PDF reports from Python with PyLaTeX.
Author: Harold Guéneau
License-Expression: MIT
Project-URL: Repository, https://github.com/HaroldGueneau/pylatex-report
Project-URL: Issues, https://github.com/HaroldGueneau/pylatex-report/issues
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: matplotlib<4,>=3.8
Requires-Dist: numpy<3,>=1.26
Requires-Dist: pandas<4,>=2.2
Requires-Dist: polars<2,>=1
Requires-Dist: pydantic<3,>=2.8
Requires-Dist: pylatex<2,>=1.4.2
Dynamic: license-file

![Logo pylatex-report](https://raw.githubusercontent.com/HaroldGueneau/pylatex-report/main/assets/pylatex-report-logo.png)

# PyLaTeX Report

Build technical PDF reports from Python using pandas or Polars DataFrames, Matplotlib figures, and native TikZ / PGFPlots graphs. The project wraps PyLaTeX with helpers for repeated experiments, figure mosaics, and reusable report styles.

## Getting started

You need Python 3.10 or newer and a TeX installation to generate PDFs.

### Install the Python library

Install into your Python environment with pip:

```bash
python -m pip install pylatex-report
```

Or add it to an existing uv project:

```bash
uv add pylatex-report
```

The installed distribution is named `pylatex-report`; its Python import is `from pylatex_report import LatexReport`. Python imports use underscores instead of hyphens.

### Install TeX separately

pip and uv install the Python dependencies, but do not install TeX. You need `pdflatex` on your PATH and the LaTeX packages used by the report; TikZ graphs also need `tikz` and `pgfplots`. If `latexmk` is available, the library uses it to manage compilation passes.

On macOS, install [MacTeX](https://tug.org/mactex/). On Ubuntu, the following packages match the [test workflow](https://github.com/HaroldGueneau/pylatex-report/blob/main/.github/workflows/tests.yml):

```bash
sudo apt-get update
sudo apt-get install -y latexmk lmodern texlive-latex-extra texlive-pictures
```

### Generate a first report

Save this as `quickstart.py` in any writable directory. It uses the installed library and needs no files from this repository.

```python
import pandas as pd
from matplotlib.figure import Figure

from pylatex_report import LatexReport

scores = pd.DataFrame({"Model": ["Baseline", "Candidate"], "Score": [0.81, 0.86]})
chart = Figure(figsize=(5, 2.5), layout="constrained")
ax = chart.subplots()
ax.bar(scores["Model"], scores["Score"])
ax.set_ylabel("Score")

report = LatexReport(
    "quickstart",
    "Model comparison",
    "Research team",
    table_of_contents=False,
    separate_cover=False,
)
report.add_section("Results")
report.add_text("Evaluation scores on the held-out dataset.")
report.add_table(scores, "Model scores", precision=2)
report.add_plot(chart, "Scores by model")
pdf = report.generate_report("reports")
print(pdf)
```

Run it with `python quickstart.py`, or `uv run python quickstart.py` from your uv project. It writes `reports/quickstart.pdf` beneath the current directory.

## Examples

The [examples directory](https://github.com/HaroldGueneau/pylatex-report/tree/main/examples) contains two runnable reports. Their scripts and data live in the repository and are not installed with the library.

| Example | What it demonstrates | Sample output |
| --- | --- | --- |
| [ML experiment](https://github.com/HaroldGueneau/pylatex-report/blob/main/examples/ml_experiment.py) | Compare three classifiers across five seeds. Reuse pandas summaries for a mean ± standard deviation table, TikZ curves with error bars, and grouped bars. Keep per-seed Matplotlib diagnostics in a paginated mosaic. | [PDF](https://github.com/HaroldGueneau/pylatex-report/blob/main/output/pdf/ml_experiment.pdf) |
| [Fund risk report](https://github.com/HaroldGueneau/pylatex-report/blob/main/examples/fund_risk.py) | Read daily returns from CSV. Use Polars for performance and risk tables, a TikZ histogram of losses, and an empirical distribution in steps. Include branded pages and Matplotlib diagnostics. | [PDF](https://github.com/HaroldGueneau/pylatex-report/blob/main/output/pdf/fund_risk.pdf) |

To run them, clone the repository and install its locked development and example dependencies with uv:

```bash
git clone https://github.com/HaroldGueneau/pylatex-report.git
cd pylatex-report
uv sync --locked

uv run --locked python -B -m examples.ml_experiment --output-dir reports
uv run --locked python -B -m examples.fund_risk \
  --input examples/data/fund_returns.csv \
  --as-of 2025-12-30 \
  --output-dir reports
```

The linked sample PDFs were generated with these commands, using `--output-dir output/pdf`. The fund example writes `reports/fund_risk.pdf` with the commands above. Its [bundled CSV](https://github.com/HaroldGueneau/pylatex-report/blob/main/examples/data/fund_returns.csv) contains simulated returns through December 31, 2025. The command above includes observations through December 30. Omit `--input` to use the bundled CSV or omit `--as-of` to report through the latest observation.

To use your own CSV, provide `date,return` columns with one row per date. The script sorts the rows by date. Dates use `YYYY-MM-DD`. Returns are daily simple returns in decimal form, so `0.0125` means 1.25%. Each return must be finite and greater than `-1`, and at least two observations must fall on or before the cutoff. When the cutoff falls between observations, the report shows the requested date and the period through the last included observation.

### Run the fund report with Docker

The image installs `pylatex-report==0.1.0` from PyPI and includes TeX. From the project root, build it once and create the output directory on the host.

```bash
docker build -f examples/Dockerfile.fund-risk -t fund-risk .
mkdir -p reports

docker run --rm --network none \
  --user "$(id -u):$(id -g)" \
  --mount "type=bind,source=$PWD/examples/data/fund_returns.csv,target=/returns.csv,readonly" \
  --mount "type=bind,source=$PWD/reports,target=/output" \
  fund-risk --input /returns.csv --as-of 2025-12-30 --output-dir /output
```

To use another version available on PyPI, add `--build-arg PYLATEX_REPORT_VERSION=<version>` to the `docker build` command. Python dependencies are resolved at build time; this image does not use the repository's `uv.lock`.

Docker mounts the CSV read-only. The report writes `reports/fund_risk.pdf` as the sole output file. For a scheduled job, reuse the image and pass the current CSV path and cutoff date. Runs using the same output directory replace the previous PDF.

## Usage guide

### Tables and repeated runs

- `add_table(df, title, precision=2)` accepts pandas and Polars DataFrames. Use `include_index` to control whether row labels are shown and `longtable=True` for a multipage table with repeated headers.
- `add_aggregate_table(runs, "Scores by model", keys="Model", metrics=["Score"])` renders mean ± standard deviation. Each run is a pandas or Polars DataFrame with the same unique model keys. Use `highlight="max"` or `highlight="min"` to bold the highest or lowest mean in each row.
- `LatexReport.aggregate_tables(runs, keys="Model", metrics=["Score"])` returns the means and standard deviations as two pandas DataFrames. The default `ddof=1` computes sample standard deviations. Missing observations are skipped per cell. Without explicit keys, rows are aligned by pandas index or Polars row position.

Both table methods accept `formats` and `column_headers`, keyed by the original data column labels.

```python
report.add_table(
    metrics,
    "Fund performance",
    formats={"Annual return": ".2%", "Sharpe": ".2f"},
    column_headers={"Annual return": "Annual\nreturn"},
)
```

Formats use Python's format specifiers. For example, `.2%` displays `0.0744` as `7.44%`. Columns without a format still use `precision`. In an aggregate table, the same format is applied to the mean and standard deviation, and highlighting uses the unrounded means. Use `\n` in a column label or its display header to start a new line. The [fund report](https://github.com/HaroldGueneau/pylatex-report/blob/main/examples/fund_risk.py) and [ML experiment](https://github.com/HaroldGueneau/pylatex-report/blob/main/examples/ml_experiment.py) show both options in use.

### Figure mosaics

`add_plot` accepts one Matplotlib `Figure` or an iterable of figures. For example, the following call lays out up to six panels per page.

```python
report.add_plot(figures, "Diagnostics", columns=3, rows_per_page=2, panel_labels=True)
```

When the mosaic spans multiple pages, each group gets its own page and the caption shows its position, such as `(1/2)`. Panel labels continue across pages and start again at `(a)` for each new call. Figures are captured when you call `add_plot`.

### TikZ / PGFPlots graphs

`add_tikz_plot` accepts one PyLaTeX `Plot` or an iterable of plots and draws them on a single axis. It uses the existing PyLaTeX dependency and requires the `tikz` and `pgfplots` packages in your TeX installation.

The graph type is selected with standard PGFPlots options:

| Graph | `Plot(options=...)` | `axis_options` / data |
| --- | --- | --- |
| Lines / smooth curves | `mark=none` / `smooth,mark=none` | Ordered `(x, y)` pairs, or a `func` expression |
| Scatter | `only marks` | `(x, y)` pairs |
| Vertical / horizontal bars | Optional colors | `ybar` / `xbar`; horizontal bars use `(value, position)` |
| Grouped bars | One plot per series | `ybar` or `xbar`, shared category positions |
| Stacked bars | One plot per series | `ybar stacked` or `xbar stacked` |
| Steps | `const plot,mark=none` | Sort by x; each value extends to the next x |
| Stems | `ycomb` or `xcomb` | Numeric pairs |
| Symmetric error bars | `error bars/.cd,y dir=both,y explicit` | `error_bar=[(x_error, y_error), ...]`, one pair per point |
| Logarithmic axes | Any compatible plot style | `xmode=log` and/or `ymode=log`; positive values on each log axis |
| Histogram | `ybar interval,fill=blue!30` | Compute counts in Python; pairs of left bin edge and count, followed by `(last_edge, 0)` |

Coordinates must be numeric. Represent categories with positions such as `1, 2, 3` and set `xtick` / `xticklabels` (or their y equivalents). This helper covers 2D plots; it has no dedicated API for 3D, heatmaps, pie charts, or box plots. See the [PGFPlots plot types](https://tikz.dev/pgfplots/reference-2dplots) and [error bars](https://tikz.dev/pgfplots/reference-errorbars) documentation for option details.

#### DataFrame table, model curve, and scatter

This example uses illustrative load-test data from the same DataFrame for a table and a graph, alongside a simple latency model:

```python
import pandas as pd
from pylatex import Plot

from pylatex_report import LatexReport

measurements = pd.DataFrame(
    {
        "Concurrent users": [10, 25, 50, 75, 100],
        "Latency (ms)": [31.0, 39.5, 53.0, 67.5, 86.0],
        "Stddev (ms)": [1.5, 2.0, 3.2, 4.1, 5.0],
    }
)
report = LatexReport(
    "load_test",
    "API latency",
    "Engineering team",
    table_of_contents=False,
    separate_cover=False,
)
report.add_section("Load test")
report.add_text("Illustrative load-test measurements.")
report.add_table(measurements, "Latency by concurrent user count", precision=1)
report.add_tikz_plot(
    [
        Plot(name="Model", func="25 + 0.5*x"),
        Plot(
            name="Observations",
            coordinates=measurements[["Concurrent users", "Latency (ms)"]].itertuples(
                index=False, name=None
            ),
            options="only marks",
        ),
    ],
    "Observed latency and model",
    axis_options=(
        r"width=0.85\linewidth,height=5.5cm,grid=major,"
        "xlabel={Concurrent users},ylabel={Latency (ms)},"
        "domain=0:100,legend pos=north west"
    ),
)
print(report.generate_report("reports"))
```

#### Polars table and grouped or stacked bars

The following snippets reuse `report` and `Plot` above. Insert them before `generate_report` to include them in the same PDF. Here, each row describes a processing stage; both series use the same numeric positions.

```python
import polars as pl

jobs = pl.DataFrame(
    {
        "Position": [1, 2, 3],
        "Stage": ["Validate", "Predict", "Export"],
        "First attempt": [940, 910, 970],
        "Retried": [60, 90, 30],
    }
)
report.add_table(jobs.drop("Position"), "Completed jobs by stage", precision=0)
report.add_tikz_plot(
    [
        Plot(name=column, coordinates=jobs.select("Position", column).iter_rows())
        for column in ("First attempt", "Retried")
    ],
    "Completed jobs: first attempt and retries",
    axis_options=(
        r"width=0.85\linewidth,height=5cm,ybar,ymin=0,"
        "bar width=12pt,enlarge x limits=0.25,"
        "xtick={1,2,3},xticklabels={Validate,Predict,Export},"
        "ylabel={Jobs},legend style={at={(0.5,1.05)},anchor=south,legend columns=2}"
    ),
)
```

Replace `ybar` with `ybar stacked` to show each stage's total of 1,000 completed jobs, split by first attempt and retry.

#### Mean latency with error bars

Reuse the load-test DataFrame to draw the mean latency with its sample standard deviation. The first error coordinate is zero because the user count has no uncertainty here.

```python
report.add_tikz_plot(
    Plot(
        name="Mean latency",
        coordinates=measurements[["Concurrent users", "Latency (ms)"]].itertuples(
            index=False, name=None
        ),
        error_bar=((0, std) for std in measurements["Stddev (ms)"]),
        options="mark=*,error bars/.cd,y dir=both,y explicit",
    ),
    "Mean latency with sample standard deviation",
    axis_options=(
        r"width=0.85\linewidth,height=5cm,grid=major,"
        "xlabel={Concurrent users},ylabel={Latency (ms)},legend pos=north west"
    ),
)
```

The [ML example](https://github.com/HaroldGueneau/pylatex-report/blob/main/examples/ml_experiment.py) computes these summaries from repeated runs rather than entering them by hand. The [fund example](https://github.com/HaroldGueneau/pylatex-report/blob/main/examples/fund_risk.py) builds a Polars histogram table with `numpy.histogram` and an empirical cumulative distribution, then plots the counts as intervals and the probabilities as steps. Their rendered PDFs are linked in [Examples](#examples).

Each plot supplies either a nonempty `func` expression or nonempty `coordinates` of finite numeric `(x, y)` pairs. Functions use PGFPlots syntax, such as `x^2`, rather than Python callables. Plot data and options are captured when `add_tikz_plot` is called, including coordinates supplied as an iterator.

`axis_options` and `Plot.options` preserve PGFPlots/LaTeX syntax, including commands such as `\linewidth`; plain text captions and legend names are escaped. Escape LaTeX special characters yourself in raw options, such as `\%` in tick labels. Omitting `axis_options` uses an axis width of `0.9\linewidth` and a height of `6cm`; supplying it replaces those defaults, so include the dimensions you want. This method creates one figure with one axis; use `add_plot` for Matplotlib mosaics.

### Report style

Reuse a `ReportStyle` across reports to apply the same branding. Put your own logo at `logo.png` in your working directory, or download the [example logo](https://raw.githubusercontent.com/HaroldGueneau/pylatex-report/main/examples/assets/horizon-logo.png) and save it under that name.

```python
from pylatex_report import CoverPage, LatexReport, ReportStyle

style = ReportStyle(
    logo="logo.png",
    accent_color="#126D77",
    header="Horizon Research",
    footer="Simulated data",
    cover=CoverPage(label="Research report", subtitle="Model comparison"),
)
report = LatexReport("comparison", "Model comparison", "Research team", style=style)
```

Logos can be PNG, JPEG or PDF. A custom cover uses the report title, author and date, with page numbering starting on the next page. Set `page_numbers=False` on the style to hide page numbers. The constructor options `table_of_contents`, `separate_cover` and `section_page_break` control pagination. For custom LaTeX, use the underlying PyLaTeX document at `report.doc`.

### Output and diagnostics

`generate_report("reports")` returns the PDF path. By default, it publishes only the finished PDF and cleans up temporary compilation files on success or failure. Use `keep_intermediates=True` to retain a build directory with the `.tex` file, figures, logo and LaTeX log. To recompile an example from its retained build directory, run `latexmk -pdf report.tex`.

When `latexmk` is unavailable, `pdflatex` runs until the auxiliary files for references and contents stop changing, with a maximum of five passes. If they do not stabilize, generation raises an error and preserves any existing destination PDF. Use `keep_intermediates=True` to inspect the build files.

The API validates inputs with Pydantic. Pass `columns=3` as an integer. A string such as `columns="3"` raises a `ValidationError`.

## Development

Clone the [repository](https://github.com/HaroldGueneau/pylatex-report) as shown in [Examples](#examples), then run these commands from its root. `uv sync --locked` installs the library in editable mode along with the development and example dependencies.

```bash
uv sync --locked
uv run --locked pre-commit install
uv run --locked pre-commit run --all-files
```

Run `pre-commit install` once per clone. The hooks use [Ruff](https://docs.astral.sh/ruff/) for linting and formatting checks and [ty](https://docs.astral.sh/ty/) for static type checking. To apply formatting locally, run `uv run --locked ruff format`.

```bash
uv run --locked python -B -m pytest
```

The suite includes integration tests that compile PDFs and skips them when `pdflatex` is unavailable. Use `-m "not integration"` to run unit tests only or `--keep-test-artifacts` to keep generated test files for debugging.

GitHub Actions runs unit tests on Python 3.10 and 3.15 with freshly resolved dependencies. A third environment on Python 3.10 uses `--resolution lowest-direct` to test the minimum compatible versions of the declared direct dependencies. These jobs install only the runtime dependencies and the `test` dependency group; they do not use or modify `uv.lock`.

A single Python 3.12 job installs LaTeX and runs pre-commit, the full test suite with locked dependencies, and the installed-distribution check. The distribution check builds a wheel and a source distribution, rebuilds a second wheel from that source distribution, and installs each wheel with its runtime dependencies in a separate fresh environment. Each installation must import the public API and compile a PDF from outside the checkout, with Python's isolated mode enabled. Run the same check locally with `uv` and LaTeX available:

```bash
bash scripts/check_distribution.sh
```

Pass a new output directory to retain the tested wheel and source archive, for example `bash scripts/check_distribution.sh dist`. The script refuses an existing destination and exports files only after both installation checks succeed.

After updating a dependency with `uv lock --upgrade-package <name>`, rerun the checks.

To enforce these checks on the default branch, configure an active branch ruleset under **Settings → Rulesets**. Require a pull request and require all four status checks: **Quality and tests**, **Python 3.10 / highest**, **Python 3.15 / highest**, and **Python 3.10 / lowest-direct**. [GitHub ruleset documentation](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/creating-rulesets-for-a-repository)

### Publishing a release (maintainers)

The [publication workflow](https://github.com/HaroldGueneau/pylatex-report/blob/main/.github/workflows/publish.yml) uses Trusted Publishing to upload the tested distributions to PyPI after all checks pass.

1. Update the version in `pyproject.toml`, then run `uv lock`.
2. Commit and push the release changes, then wait for CI to pass.
3. Publish a GitHub release with a matching tag, such as `vx.x.x` for version `x.x.x`, pointing to that commit.
4. Check that **Publish to PyPI** succeeds in GitHub Actions, then install the published version in a fresh environment outside this repository and generate a PDF with the quickstart.

Each release needs a new version and tag; published distribution files cannot be replaced.

## License

Distributed under the [MIT license](https://github.com/HaroldGueneau/pylatex-report/blob/main/LICENSE).
