Module contents
Lesson 19 of 23Core 100 min

LaTeX for researchers: from reproducible manuscript to submission

LaTeX as paper engineering: document model, mathematical typesetting and notation macros, bibliography, booktabs and siunitx tables, code-generated vector figures, reproducible latexmk or Tectonic builds, and venue submission preparation.

After this lesson you can

  • Structure a LaTeX document with a minimal preamble, notation macros, and separate section files.
  • Typeset mathematics with appropriate amsmath environments, operators, and delimiters.
  • Manage a clean BibTeX or biblatex bibliography and detect defective entries.
  • Generate included tables and figures from code with a one-command build.
  • Prepare an anonymous page-limited submission and a valid arXiv source package.

Before you start

One result, one source

If a figure changes in an experiment but not in a hand-copied table, the PDF no longer describes the results. A reproducible build connects data, transformations, tables, figures, and manuscript. The results table already defines what to communicate; here you build the path carrying it to a PDF.

The LaTeX document model separates class, preamble, and body. The class sets global conventions; the preamble loads packages and declares macros; the body contains sections, references, and figures. For submission use the venue’s official template and current instructions. A generic class helps learning but does not guarantee conference-format compliance.

Locally you can install TeX Live with latexmk, or Tectonic to compile a document. Tectonic’s first use may download bundle resources, so compilation is not necessarily offline. A free editor or service such as Overleaf can help editing, but source code, input data, and tool versions remain part of the artifact. The project directory and version workflow keep them together.

A useful structure separates paper.tex, notation.tex, sections/, references.bib, results/, and figures/. The main file includes sections; analysis code generates tables in a known directory; data files retain unrounded results. Separation makes changes easier to locate, though a venue template may require different packaging. Define a project-relative build path rather than an absolute machine path another reader lacks.

Keep the preamble small and note why each package is loaded. Two packages can redefine commands or conflict with the conference class. If a template already supplies bibliography, margins, or headers, do not replace them for convenience without checking submission rules. After adding a package, recompile and inspect the log: an existing PDF may be from an earlier build that failed on the current version.

Mathematics as structure

Mathematical typesetting expresses relationships, not just glyphs. equation suits one numbered equation; align aligns several equations at points marked with &; multline breaks one long expression without requiring alignment across steps; gather centers equations without operator alignment; cases represents cases within an expression. amsmath supplies these environments.

Known operators are written as operators, for example \log or \sin, not products of italic letters. \langle x,y\rangle distinguishes an inner product from two comparisons. A differential can be typeset as \,\mathrm{d}x. Automatic delimiters \left and \right can help with tall fractions but should not be applied everywhere without checking size and spacing. A semantic macro such as \newcommand{\vect}[1]{\mathbf{#1}} centralizes a decision; also define its meaning in the paper’s notation.

InteractiveMath linter
logx+<x,y>log x + <x,y>
  • Use \log for the logarithm operator.
  • Use \langle x,y\rangle for an inner product.
Edit the expression and compare warnings with the view. The linter uses limited patterns and does not interpret a proof or validate macro meaning.

A macro does not prevent inconsistencies if used for different objects. Before writing the body, list symbol, object type, dimension, and meaning. Avoid redefining existing commands without knowing how class or package uses them. Check each compiled formula, references, and the context of notation reconstruction.

For a derivation with several equalities, put each equals sign at an alignment point and explain assumptions in prose. align supplies numbers per line unless suppressed; for one number covering several steps, an appropriate equation and aligned combination can communicate that they form one relation. cases lives inside math mode and its conditions should explain which part of the domain they cover. Do not choose an environment for appearance if it changes what is numbered or referenced in text.

The notation table also checks consistency: if \vect{x} denotes a column vector, state its dimension when first introduced; if R means risk in one section and reward in another, disambiguate or use distinct symbols. The linter recognizes character strings only. An expression without warnings can have incompatible dimensions or a missing assumption, while a flagged expression may be correct in context. Mathematical review remains human.

Bibliography as data

Bibliography management separates source description from output style. BibTeX and biblatex use different workflows and styles: follow the venue template before choosing. Check key, authors, title, year, venue, and DOI where appropriate; preserve significant capitalization with braces if style changes capitalization. A title match can indicate a duplicate but does not prove two entries are the same version.

InteractiveClean an entry
@misc{ejemplo,
  title = {Study of ML},
  author = {Autor, Ana},
  eprint = {0000.00000},
}
@inproceedings{copia, title = {Study of ML}}

Simulated view of a style that lowercases titles: Autor, Ana. Study of ml.

The example assumes a fictional published version; the preview is not a compilation. In a real case check the relationship between versions before replacing a citation.

Example warnings5
Correct defects in a fictitious entry and check warnings. The tool does not query an external database or decide whether two paper versions are identical.

If a revised version and preprint are related, check title, authors, venue, identifiers, and version before replacing a citation. Sometimes a specific version is worth citing because it contains a result or appendix absent elsewhere. Automatic title or DOI comparison is a clue to consult sources, not proof of content equivalence.

A practical workflow starts with one entry per source and a stable key. Check author import did not swap given and family names, title preserves acronyms and proper names, year matches the cited version, and DOI resolves to the expected work. If two entries share a title, compare contents and dates before merging: a technical report and conference paper may differ in theorems or appendices. In the final bibliography also inspect style output because capitalization protection and name handling depend on it.

A correct identifier does not prove the text cites it faithfully. For a quantitative claim return to the primary table, figure, or section and retain scope: dataset, metric, and configuration. If a result appears only in one version’s appendix, identify that version. A linter detects missing fields and duplicate clues; it cannot conclude that a reference is correct or supports the neighboring sentence.

Tables, figures, and floats

Integrating tables and figures starts from generated files, not transcribed figures. booktabs supplies horizontal table rules; siunitx helps align numbers. Retain units and interval meaning in the caption. The figure as argument decides content before formatting beautifies it.

InteractiveTwo tables, the same data
MethodScore
A8.2
B12.35
C9.04

Actual decimal alignment is implemented with siunitx; this table shows the visual idea without compiling LaTeX.

Transform the grid in three steps: remove vertical lines, retain essential rules, and align decimals. Values are fictitious.

PDF and PGF can preserve vector elements, though an included raster image stays raster. Matplotlib PGF export needs a compatible LaTeX engine to measure text and manuscript-consistent configuration. PDF output must also be generated from code. Identify fonts and check final size in the template, in color and grayscale if the venue requires it. The Matplotlib object model helps control axes, legend, and output.

A figure has two sizes: original canvas and included document width. If reduced too far, labels legible in the notebook can become tiny in the PDF. Generate near publication size, open at page scale, and check axes, legend, lines, and uncertainty. Including an image in PDF does not undo earlier rasterization: zoom in and check marks if sharpness matters.

A caption should identify data, unit, and represented quantity. If a band is a mean interval, state procedure and resampling unit; if it is seed deviation, say so. A table must retain ± meaning and replicate count from the results lesson. In siunitx output, column format must accommodate actual signs, decimals, and magnitudes; a text cell needs different handling from a numeric entry.

A float is not guaranteed to appear exactly where written. Its options indicate allowed or preferred positions, but LaTeX considers space and order constraints. h alone does not force placement; t, b, and p broaden alternatives. Reducing the figure, moving its source reference, or adjusting template rules can help. Do not conceal a figure that does not fit using manual breaks and spaces without reviewing the overall result.

InteractiveA simple placement rule
  • Text
  • Float
Page 1
Page 2
40
Simulated page2
Positiontop of next page
This simulation uses a 35% gap on the first page and places the float by size and first preference. It does not reproduce real LaTeX queues or parameters; use it to reason about space, then check the compiled PDF.

Build and submit

A reproducible build is a graph: data feed tables and figures; those files feed the document; bibliography, class, and packages complete compilation. One command should regenerate what is needed when an input changes. Record versions, dependencies, and configuration; clean intermediates without deleting original results. A PDF hash may vary with metadata even when visible content agrees, so define whether binary equality or content reproduction is expected.

In a project with many results, Make can express dependencies: a changed CSV invalidates table and figure; either change invalidates the PDF. Compilation must exit with an error if data are missing or TeX fails, rather than leaving an old PDF as if new. latexmk automates compilation and bibliography passes, while a build script can regenerate analysis artifacts before invoking it. Check that deleting only generated files allows reconstruction from retained inputs.

An end-to-end test changes a controlled input, runs the full command, and compares visible output. Also check the reverse path: if a table appears in the PDF, can you identify which file and analysis version produced it? Reproducibility does not mean every run has identical time or bytes; it means procedure and dependencies are sufficiently specified to assess what may vary. For random results retain seeds, configuration, and units, and separate synthetic samples from published results.

Submission preparation depends on each venue’s rules. Check template, deadline, format, page limit, references and appendices, and anonymous-review policy. For double anonymity, inspect first-person self-citations, personal repository links, acknowledgments, figure paths, metadata, and supplementary material; a simple search cannot be promised to catch every leak. For arXiv consult official submission instructions: include required sources and dependencies and check package compilation under current rules.

Review the exact file to be submitted. Count pages according to the venue’s policy, which may treat references and appendices differently. Check that no figure or table is cut off, every citation and reference resolves, and supplementary material contains what the text promises. For anonymous review, a URL, printed path, or supplementary filename may reveal identity. Specific rules may allow or require particular self-citations: respect them without deleting background needed to assess the work.

For later public distribution prepare code and data you may publish, with execution guidance and required resources. A preprint repository’s source package can differ from anonymous-review requirements. Do not assume local compilation with installed packages means a remote service has the same files: check its compiler messages and resulting PDF.

Lab: from result to document

The lab creates a temporary paper-demo-* directory and synthetic data, never a paper’s result. It downloads the official ACL template from a fixed revision and verifies SHA-256. The build creates a table and vector PDF and PGF figures from CSV and includes PGF in a document compiled with Tectonic. Matplotlib also needs xelatex on PATH to measure text when generating PGF. The fixed template is an engineering example, not a future-call compliance guarantee; consult the version required by your venue. Then integrate the validated researchkit generator from the previous lesson.

[ ]Generate data, table, and figureLocal GPU
from pathlib import Path
import csv
import tempfile
import hashlib
import inspect
import math
from urllib.request import urlopen
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt

plt.rcParams['pgf.texsystem'] = 'xelatex'
root = Path(tempfile.mkdtemp(prefix='paper-demo-', dir='.'))
print('Directorio:', root.resolve())
style_url = ('https://raw.githubusercontent.com/acl-org/acl-style-files/'
             'd5adc823ff0f80f98c80405ca0ab66c68e684409/acl.sty')
with urlopen(style_url, timeout=30) as response:
    style = response.read()
assert hashlib.sha256(style).hexdigest() == '19dfeddc2c0e448f3926a0bef048a9db3f3611b46265b760caabd7ada4f361de'
(root / 'acl.sty').write_bytes(style)
data = root / 'resultados.csv'
with data.open('w', encoding='utf-8', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['tarea', 'metodo', 'semilla', 'score'])
    writer.writerows([['T1', m, i, v] for m, values in
                      [('A', [0.68, 0.70, 0.72, 0.70]),
                       ('B', [0.71, 0.75, 0.77, 0.73])]
                      for i, v in enumerate(values)])

# Misma implementación descargable de researchkit_tables.py, incluida aquí
# para que el laboratorio sea autocontenido en una sesión nueva.
def paired_p(a, b):
    d = np.asarray(a, dtype=float) - np.asarray(b, dtype=float)
    if np.allclose(d, d[0], rtol=0, atol=1e-12):
        return 1.0 if abs(d[0]) < 1e-12 else 0.0
    return float(stats.ttest_1samp(d, 0).pvalue)

def tied_best_group(scores, alpha=0.05):
    if (not 0 < alpha < 1 or scores.shape[0] < 2 or scores.shape[1] < 1
            or not scores.columns.is_unique or not scores.index.is_unique
            or not np.isfinite(scores.to_numpy(dtype=float)).all()):
        raise ValueError('Se requieren al menos dos pares completos y 0 < alpha < 1')
    best = scores.mean().idxmax()
    comparisons = [(name, paired_p(scores[best], scores[name]))
                   for name in scores.columns if name != best]
    ordered = sorted(comparisons, key=lambda pair: pair[1])
    rejected = set()
    for rank, (name, p) in enumerate(ordered):
        if p <= alpha / (len(ordered) - rank):
            rejected.add(name)
        else:
            break
    return set(scores.columns) - rejected

def table_latex(frame, alpha=0.05):
    if frame.duplicated(['tarea', 'semilla', 'metodo']).any():
        raise ValueError('Hay filas duplicadas')
    lines = [r'\begin{tabular}{ll}', r'\toprule',
             r'Método y tarea & Media e IC 95\% \\', r'\midrule']
    counts = []
    for task, group in frame.groupby('tarea', sort=True):
        wide = group.pivot(index='semilla', columns='metodo', values='score')
        counts.append(f'{task}: n={len(wide)}')
        keep = tied_best_group(wide, alpha)
        for name in wide.columns:
            values = wide[name].to_numpy()
            se = stats.sem(values)
            half = stats.t.ppf(0.975, len(values)-1) * se
            digits = max(0, -math.floor(math.log10(se))) if se > 0 else 2
            mean_text = f'{values.mean():.{digits}f}'
            interval_text = f'[{values.mean()-half:.{digits}f}, {values.mean()+half:.{digits}f}]'
            label = f'{name} ({task})' + ('*' if name in keep else '')
            lines.append(f'{label} & {mean_text} {interval_text} ' + r'\\')
    lines.extend([r'\bottomrule', r'\end{tabular}',
                  r'{\par\smallskip\footnotesize Medias e intervalos t del 95\%; ' + ', '.join(counts)
                  + r'. *: no rechazo exploratorio pareado con Holm frente al máximo observado, no equivalencia.\par}'])
    return '\n'.join(lines)

def generar(root):
    frame = pd.read_csv(root / 'resultados.csv')
    (root / 'tabla.tex').write_text(table_latex(frame), encoding='utf-8')
    groups = frame.groupby('metodo').score
    means = groups.mean()
    half = stats.t.ppf(0.975, groups.count() - 1) * groups.sem()
    fig, ax = plt.subplots(figsize=(3.2, 2.2))
    ax.bar(means.index, means.values, yerr=half.values, capsize=3)
    ax.set_ylabel('Valor sintético')
    fig.tight_layout()
    fig.savefig(root / 'figura.pdf')
    fig.savefig(root / 'figura.pgf')
    plt.close(fig)

generar(root)
print((root / 'tabla.tex').read_text(encoding='utf-8'))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second cell writes the source and a build.py script. From the printed directory, python build.py regenerates table, figures, and PDF in one command; it needs tectonic and xelatex on PATH and Matplotlib installed. Double slashes in Python code represent a LaTeX row break. Document and data are deliberately small. Before running, install Tectonic and a TeX distribution with XeLaTeX; initial compilation may download packages. The cell does not load external data or train a model.

[ ]Compile and repeat after changing dataLocal GPU
import os
import shutil
import subprocess
import hashlib
import inspect
import sys

source = r'''\documentclass[11pt]{article}
\usepackage[review]{acl}
\usepackage{booktabs,graphicx,pgf}
\input{notation.tex}
\renewcommand{\figurename}{Figura}
\renewcommand{\tablename}{Tabla}
\title{Demostración reproducible}
\author{Autor anónimo}
\begin{document}
\maketitle
\input{sections/results.tex}
\end{document}'''
(root / 'paper.tex').write_text(source, encoding='utf-8')
(root / 'notation.tex').write_text(r'\newcommand{\vect}[1]{\mathbf{#1}}', encoding='utf-8')
(root / 'sections').mkdir(exist_ok=True)
(root / 'sections' / 'results.tex').write_text(r'''Resultados sintéticos de cuatro semillas por método.
\begin{table}[htbp]
\centering\input{tabla.tex}
\caption{Puntuaciones sintéticas por método y tarea.}
\end{table}
\begin{figure}[htbp]
\centering\input{figura.pgf}
\caption{Medias sintéticas e intervalos t del 95\% de la media entre semillas.}
\end{figure}''', encoding='utf-8')
if shutil.which('tectonic') is None:
    raise RuntimeError('Instala Tectonic y añádelo al PATH')
build = '''from pathlib import Path
import csv
import math
import subprocess
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
plt.rcParams['pgf.texsystem'] = 'xelatex'
''' + inspect.getsource(paired_p) + '\n' + inspect.getsource(tied_best_group) + '\n' + inspect.getsource(table_latex) + '\n' + inspect.getsource(generar) + '''
generar(Path('.'))
subprocess.run(['tectonic', 'paper.tex'], check=True)
'''
(root / 'build.py').write_text(build, encoding='utf-8')
def construir():
    env = dict(os.environ, PYTHONUTF8='1')
    subprocess.run([sys.executable, 'build.py'], cwd=root, env=env, check=True,
                   capture_output=True, text=True, encoding='utf-8')

construir()
first = (root / 'tabla.tex').read_text(encoding='utf-8')
first_pdf_hash = hashlib.sha256((root / 'paper.pdf').read_bytes()).hexdigest()
with data.open('w', encoding='utf-8', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['tarea', 'metodo', 'semilla', 'score'])
    writer.writerows([['T1', m, i, v] for m, values in
                      [('A', [0.68, 0.70, 0.72, 0.70]),
                       ('B', [0.75, 0.79, 0.81, 0.77])]
                      for i, v in enumerate(values)])
construir()
second = (root / 'tabla.tex').read_text(encoding='utf-8')
second_pdf_hash = hashlib.sha256((root / 'paper.pdf').read_bytes()).hexdigest()
assert first != second and '0.78' in second and first_pdf_hash != second_pdf_hash
print('Tabla actualizada y PDF recompilado:', (root / 'paper.pdf').stat().st_size, 'bytes')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Changing CSV regenerated the table and compiled the PDF without changing source. To verify that the PDF visually reflects the new value, open the result and inspect table and figure; PDF existence alone does not establish its contents. Values are a fixed teaching list, not a population sample: intervals illustrate calculation and cannot verify coverage here. The included generator reproduces the previous lesson’s add-on: the group is exploratory and the star does not establish equivalence. Add replicate count, unit, interval, and test limitations to a real table caption. This example uses controlled labels; escape external labels before writing LaTeX.

Lab: limited bibliography audit

The following validator analyzes a subset of .bib: entries with balanced-brace values. It considers required fields by type, duplicates by normalized title, and unprotected acronyms. It performs no external searches: a possible preprint related to a publication needs manual consultation. An uncited key is identified by comparing with keys extracted from the manuscript.

[ ]Audit entries and citationsBrowser
import re

def cerrar_llave(text, opening):
    depth = 0
    for i in range(opening, len(text)):
        if text[i] == '{': depth += 1
        elif text[i] == '}':
            depth -= 1
            if depth == 0: return i
    raise ValueError('Llaves sin cerrar')

def parse_bib(text):
    entries, pos = {}, 0
    while True:
        match = re.search(r'@(\w+)\s*\{\s*([^,]+),', text[pos:])
        if not match: break
        opening = pos + match.start() + match.group().index('{')
        end = cerrar_llave(text, opening)
        key, kind = match.group(2).strip(), match.group(1).lower()
        if key in entries: raise ValueError('Clave duplicada: ' + key)
        body = text[pos + match.end():end]
        entry, cursor = {'type':kind}, 0
        while True:
            field = re.search(r'(\w+)\s*=\s*\{', body[cursor:])
            if not field: break
            start = cursor + field.end() - 1
            stop = cerrar_llave(body, start)
            entry[field.group(1).lower()] = body[start+1:stop]
            cursor = stop + 1
        entries[key] = entry
        pos = end + 1
    return entries

required = {'article': {'author','title','year','journal'},
            'inproceedings': {'author','title','year','booktitle'}}
def audit_bib(entries, cited):
    seen = {}
    warnings = []
    for key, entry in entries.items():
        kind = entry.get('type', '').lower()
        missing = sorted(field for field in required.get(kind, set()) if not entry.get(field, '').strip())
        title = entry.get('title', '')
        outside = re.sub(r'\{[^{}]*\}', '', title)
        acronyms = re.findall(r'\b[A-Z]{2,}\b', outside)
        normalized = re.sub(r'[^a-z0-9]+', '', title.lower())
        if normalized and normalized in seen:
            warnings.append((key, 'posible duplicado', seen[normalized]))
            prior = entries[seen[normalized]]
            if (('eprint' in prior and ('journal' in entry or 'booktitle' in entry)) or
                ('eprint' in entry and ('journal' in prior or 'booktitle' in prior))):
                warnings.append((key, 'posible preprint y versión publicada', seen[normalized]))
        elif normalized:
            seen[normalized] = key
        if missing: warnings.append((key, 'faltan campos', missing))
        if acronyms: warnings.append((key, 'siglas sin proteger', acronyms))
        if key not in cited: warnings.append((key, 'no citada', ''))
    return warnings

bib = r'''@article{a, title={Estudio de ML}, author={A}, year={2025}, eprint={0000.00000}}
@inproceedings{b, title={Estudio de {ML}}, author={A}, year={2025}, booktitle={Actas}}'''
manuscript = r'Véase \cite{a}.'
cited = set(k.strip() for group in re.findall(r'\\cite\{([^}]+)\}', manuscript)
            for k in group.split(','))
for warning in audit_bib(parse_bib(bib), cited):
    print(warning)

The example and preprint identifier are fictitious. Protection and normalization are checked only for the stated subset; quoted values, comments, escapes, macro-defined strings, concatenation, and cite variants need a more complete BibTeX parser and LaTeX analysis. A preprint-publication match is an alert, not confirmation. Manually verify duplicates, published version, and citations before editing the file.

Exercises

Quiz
You want to align three steps at equals signs and number each line. Which amsmath environment is the natural choice?
Quiz
Choose the correspondence for: (1) one numbered equation; (2) several aligned equations; (3) one long equation split without alignment; (4) several centered equations without alignment; (5) a piecewise function.
Quiz
For double-anonymous review, what deserves inspection before submission?
Code
Implement check_bib(entries). It receives a dictionary of keys to entries with type and title. For article require author, title, year, and journal; for inproceedings require author, title, year, and booktitle. Return for each key a dictionary with sorted lists missing and acronyms: the latter are words of two or more uppercase letters outside unnested brace pairs. Require no fields for other types.
def check_bib(entries):
  pass
Shift+Enter to run
Code
Implement make_macros(rows): each row is (nombre, expresion, descripcion), where nombre contains only ASCII letters without a backslash. Return source with one zero-argument macro declaration per row, one per line. Reject duplicate names and standard names log, sin, or alpha with ValueError. Description is table information and is not part of the result.
def make_macros(rows):
  pass
Shift+Enter to run

Summary

Key idea
The PDF is the last node of a reproducible process: retain data and code, generate tables and figures, compile with recorded dependencies, and inspect the submission package.