Algorithm Search⌘K

Algorithmadvanced

Optimal pagination by dynamic programming

Also called Plass optimal pagination.

Choose all page breaks of a document at once by dynamic programming over break points, with figures placed in order on or after their first reference.

Time
O(n^2 m^2) worst
Space
Θ(n m) extra
Where
m = the number of figures; n = the number of text lines
Properties
deterministicexactiterative
Origin
Michael F. Plass, 1981

Optimal pagination chooses all the page breaks of a document together, so that the sum of the costs of the pages is as small as possible. A page has a cost for its white space, for a bad break such as a widow line, and for each figure that floats away from the line that refers to it. When the text lines and the figures each keep their order, the state after a page is just the pair (lines placed, figures placed), and a shortest path over these pairs gives the optimum. This is the page version of the total-fit method of Knuth-Plass line breaking, and it can beat the best-fit page builder of TeX, which fills one page at a time.

In plain words

A book has lines of text and some figures. Each figure must come on the page where the text first mentions it, or on a later page. Each page has a fixed height.

We want pages that are well filled, with no bad breaks, and with each figure close to where it is mentioned. A choice that is good for one page can be bad for the next one, so we must look at all pages together.

After some pages are done, all that matters for the rest is how many lines and how many figures are used. So we find the best way to reach each such pair, from small pairs to large ones, as in a shortest path search.

The problem

There are nn text lines with heights h1,…,hnh_1, \ldots, h_n and mm figures with heights f1,…,fmf_1, \ldots, f_m, all ≥0\ge 0. Figure tt is referenced from line rtr_t, with 1≤r1≤⋯≤rm≤n1 \le r_1 \le \cdots \le r_m \le n. The page height is HH. This page uses a simple model of the page breaking problem:

  • A page holds a block of consecutive lines and a block of consecutive figures; one of the blocks can be empty, but not both. So the lines keep their order, and the figures keep their order.
  • The total height uu of a page is at most HH. There is no glue: the white space of a page is H−uH - u.
  • Figure tt is on the page of line rtr_t or on a later page.

The cost of a pagination adds, for every page except the last one:

  • (H−u)2(H - u)^2, the white space, squared;
  • πi\pi_i if the page holds lines and its last line ii is not line nn; this is the cost of a break after line ii, for example a widow or club penalty;
  • αw\alpha w, where ww is the number of figures referenced on this page or earlier that are not placed yet, and α≥0\alpha \ge 0 is a weight.

The sum of the terms ww over all pages is the sum over the figures of the page of the figure minus the page of its reference. So the last term charges α\alpha for each page that a figure floats away from its reference. The last page is free, as in TeX, where it ends with glue that can stretch without limit.

The algorithm

Let R(i)R(i) be the number of figures referenced from lines 1,…,i1, \ldots, i. A state (i,j)(i, j) means that the first ii lines and the first jj figures are on finished pages. A page from (i,j)(i, j) to (i′,j′)(i', j') is allowed when it fits and j′≤R(i′)j' \le R(i'): every figure on it is referenced on this page or earlier. Its cost depends only on ii, i′i', j′j' and the height uu, so it is an edge weight in a DAG over the states. Prefix sums of the heights give uu in O(1)O(1) time.

  1. OPTIMAL-PAGES(h_1 .. h_n, f_1 .. f_m, r_1 .. r_m, H, α, π)
  2. 1C[0][0] ← 0; C[i][j] ← ∞ for every other state
  3. 2for i ← 0 to n do
  4. 3for j ← 0 to m do
  5. 4if C[i][j] = ∞ then continue
  6. 5for i' ← i to n, while the lines i+1 .. i' fit in H do
  7. 6for j' ← j to m, while j' ≤ R(i') and the page fits in H do
  8. 7if (i', j') = (i, j) then continue
  9. 8d ← C[i][j] + the cost of the page from (i, j) to (i', j'), or 0 if (i', j') = (n, m)
  10. 9if d < C[i'][j'] then C[i'][j'] ← d; P[i'][j'] ← (i, j)
  11. 10if C[n][m] = ∞ then return failure
  12. 11follow P back from (n, m), and return C[n][m] and the states of the pages

Every page goes from a state to a state that is later in the lexicographic order, so lines L2 and L3 visit the states in a topological order. The loops of lines L5 and L6 stop early, because a longer block can only be taller and R(i′)R(i') is fixed for a fixed i′i'.

Example

Take eight lines of height 1, one figure of height 3 referenced from line 4, page height H=5H = 5, α=5\alpha = 5 and no break penalties.

pagination page 1 page 2 page 3 cost
fill each page lines 1 to 5 figure, lines 6 and 7 line 8 0+5=50 + 5 = 5
optimal lines 1 to 3 lines 4 and 5, figure lines 6 to 8 22=42^2 = 4
lines 1 to 4 figure, line 5 ... 1+5=61 + 5 = 6 or more

Filling each page puts lines 1 to 5 on page 1. The figure is referenced there, does not fit, and floats to page 2, which costs α=5\alpha = 5. The optimum leaves two units of white space on page 1, which costs 4, so that line 4 starts page 2 and the figure sits on the same page as its reference. The DP finds this, and a search over all paginations confirms it.

Correctness

Two facts make the DP exact. First, the condition that each figure comes on or after the page of its reference can be checked page by page: it holds exactly when j′≤R(i′)j' \le R(i') after each page. Second, the cost splits over the pages: a figure that floats dd pages from its reference is counted once at each of the dd page breaks between them, and at each break the number of such figures is R(i′)−j′R(i') - j'. So the valid paginations are the paths from (0,0)(0, 0) to (n,m)(n, m) in a DAG, the cost of a pagination is the weight of its path, and the DP is a shortest path in a DAG. An optimal pagination to a state can be cut and pasted into any optimal pagination through it (the cut-and-paste argument). The full proof is in the proof file below.

Proof: The pagination dynamic program returns a pagination of least costfull

We use the model and the pseudocode of the page. The lines have heights h1,…,hn≥0h_1, \ldots, h_n \ge 0, the figures have heights f1,…,fm≥0f_1, \ldots, f_m \ge 0, figure tt is referenced from line rtr_t with 1≤r1≤⋯≤rm≤n1 \le r_1 \le \cdots \le r_m \le n, and R(i)R(i) is the number of figures with rt≤ir_t \le i. A state is a pair (i,j)(i, j) with 0≤i≤n0 \le i \le n and 0≤j≤m0 \le j \le m. A pagination with PP pages is a sequence of states (0,0)=s0,s1,…,sP=(n,m)(0, 0) = s_0, s_1, \ldots, s_P = (n, m) with sk=(ik,jk)s_k = (i_k, j_k), ik−1≤iki_{k-1} \le i_k, jk−1≤jkj_{k-1} \le j_k and sk−1≠sks_{k-1} \ne s_k. Page kk holds the lines ik−1+1,…,iki_{k-1} + 1, \ldots, i_k and the figures jk−1+1,…,jkj_{k-1} + 1, \ldots, j_k, and its height is uku_k, the sum of their heights. The pagination is valid if uk≤Hu_k \le H for every kk and every figure is on the page of its reference or later. Its cost is

cost=∑k=1P−1(H−uk)2+∑xπx+α∑t=1m(p(t)−q(rt)),\mathrm{cost} = \sum_{k=1}^{P-1} (H - u_k)^2 + \sum_{x} \pi_x + \alpha \sum_{t=1}^{m} \bigl(p(t) - q(r_t)\bigr),

where the middle sum is over the lines xx with 1≤x<n1 \le x < n such that line x+1x + 1 is on a later page than line xx, p(t)p(t) is the page of figure tt and q(x)q(x) is the page of line xx.

Lemma 1 (validity is local). Every figure is on the page of its reference or later if and only if jk≤R(ik)j_k \le R(i_k) for every kk.

Proof. Since the references are sorted, R(i)≥tR(i) \ge t holds exactly when rt≤ir_t \le i. Suppose that jk≤R(ik)j_k \le R(i_k) for all kk, and let figure tt be on page kk, so t≤jk≤R(ik)t \le j_k \le R(i_k). Then rt≤ikr_t \le i_k, so line rtr_t is on page kk or earlier. Conversely, suppose that every figure is on the page of its reference or later, and take kk with jk≥1j_k \ge 1. Figure jkj_k is on a page k′≤kk' \le k, so its reference line is on a page ≤k\le k, and rjk≤ikr_{j_k} \le i_k. Hence R(ik)≥jkR(i_k) \ge j_k. □\square

Lemma 2 (the cost splits over the pages). For a valid pagination, the cost is ∑k=1P−1ℓ(sk−1,sk)\sum_{k=1}^{P-1} \ell(s_{k-1}, s_k), where

ℓ((i,j),(i′,j′))=(H−u)2+[ i<i′<n ] πi′+α(R(i′)−j′)\ell\bigl((i, j), (i', j')\bigr) = (H - u)^2 + [\, i < i' < n \,]\, \pi_{i'} + \alpha \bigl(R(i') - j'\bigr)

and uu is the height of the page from (i,j)(i, j) to (i′,j′)(i', j').

Proof. The first terms agree by definition. For the penalties: let 1≤x<n1 \le x < n. Line x+1x + 1 is on a later page than line xx exactly when line xx is the last line of its page kk, that is, x=ikx = i_k and ik−1<iki_{k-1} < i_k; then k<Pk < P, since line x+1x + 1 comes later. So each such xx is counted once, by the page kk with ik−1<ik=x<ni_{k-1} < i_k = x < n, and no other page adds a penalty. For the figures: p(t)−q(rt)p(t) - q(r_t) is the number of kk with q(rt)≤k<p(t)q(r_t) \le k < p(t), which is the number of kk with 1≤k≤P−11 \le k \le P - 1, rt≤ikr_t \le i_k and t>jkt > j_k. Summed over tt, this is ∑k=1P−1#{t:rt≤ik, t>jk}\sum_{k=1}^{P-1} \#\{t : r_t \le i_k,\ t > j_k\}. By Lemma 1 and the sorted references, every t≤jkt \le j_k has rt≤ikr_t \le i_k, so the set has R(ik)−jkR(i_k) - j_k elements. □\square

The DAG. Put an edge from the state ss to the state s′≠ss' \ne s when s≤s′s \le s' in both coordinates, the page from ss to s′s' has height at most HH, and j′≤R(i′)j' \le R(i'). Its weight is ℓ(s,s′)\ell(s, s') if s′≠(n,m)s' \ne (n, m) and 0 if s′=(n,m)s' = (n, m). By Lemmas 1 and 2, the valid paginations are exactly the paths from (0,0)(0, 0) to (n,m)(n, m) in this DAG, and the cost of a pagination is the weight of its path: every state on a path other than the last one is not (n,m)(n, m), since no edge leaves (n,m)(n, m). Every edge goes to a state that is later in the lexicographic order, so this order is a topological order.

Lemma 3 (all edges are seen). When lines L5 to L9 run for the state (i,j)(i, j), they relax every edge that leaves (i,j)(i, j), and only such edges.

Proof. Heights are ≥0\ge 0, so the height of the lines i+1,…,i′i + 1, \ldots, i' does not decrease when i′i' grows, and the loop of line L5 stops only when no larger i′i' can give a page that fits. For a fixed i′i', the height uu of the page does not decrease when j′j' grows and R(i′)R(i') is fixed, so the loop of line L6 stops only when no larger j′j' gives an edge. Line L7 skips s′=ss' = s. Every pair (i′,j′)(i', j') that reaches line L8 satisfies the three conditions of an edge, and line L8 adds its weight. □\square

Theorem. The algorithm terminates. It returns the least cost of a valid pagination and a pagination with this cost, or failure when no valid pagination exists.

Proof. The loops are finite. The states are processed in lexicographic order, which is topological, and by Lemma 3 each state relaxes all its outgoing edges. By the standard argument for shortest paths in a DAG, when the state ss is processed, C[s]C[s] is the least weight of a path from (0,0)(0, 0) to ss: all edges into ss come from earlier states, which were processed with their final values. So C[n][m]C[n][m] is the least cost of a valid pagination, or ∞\infty when there is none, and then line L10 reports failure. The links PP store the last edge of a best path to each state, so line L11 rebuilds a path whose weight is C[n][m]C[n][m]. □\square

Complexity. There are (n+1)(m+1)(n + 1)(m + 1) states, and each state has at most (n+1)(m+1)(n + 1)(m + 1) edges, each relaxed in O(1)O(1) time with prefix sums. So the time is O(n2m2)O(n^2 m^2) and the space is O(nm)O(n m). If every page holds at most aa lines and bb figures, for example because every height is at least 1 and HH is fixed, a state has at most (a+1)(b+1)(a + 1)(b + 1) edges and the time is O(nmab)O(n m a b).

Complexity

There are (n+1)(m+1)(n + 1)(m + 1) states, each with at most (n+1)(m+1)(n + 1)(m + 1) pages leaving it, and each page costs O(1)O(1) time. So the time is O(n2m2)O(n^2 m^2) and the extra space is Θ(nm)\Theta(n m) for the table and the links. If a page holds at most aa lines and bb figures, as when every height is at least 1, the time is O(nmab)O(n m a b), which is linear in nmn m for a fixed page size. When m=0m = 0, the method is a least weight subsequence problem over the lines, in O(na)O(n a) time.

Properties

  • Exact for its model. It returns a pagination of least total cost among the valid ones.
  • Offline. It needs the whole document before it can fix the first page, unlike the page builder of TeX.
  • The model matters. The DP works because the lines and the figures each keep their order and the cost splits over page breaks. If figures can change order, the problem is NP-complete; see the NP-completeness of pagination.
  • Ties. Line L9 keeps the first best path found, so the result is deterministic.

Variants and improvements

  • Page-dependent costs. If the cost of a page depends on its page number (for example, a figure must be on the same spread, so odd and even pages differ), the state needs the page number too, (i,j,k)(i, j, k), and the time grows by a factor of the number of pages.
  • Other figure costs. A cost that is a convex function of the distance, such as its square, does not split over page breaks with the state (i,j)(i, j) alone, so it needs a larger state or another method.
  • Glue between lines. With stretchable glue between the lines, the white space term becomes the badness of the page, as in the TeX cost, and the DP is the same.
  • Several kinds of floats. With figures and tables in two separate streams, the state is a triple, one count per stream.

When to use it

Use it when the whole document is known and page quality matters: books with many figures, reports with tables, documents for print. For long documents where the first pages must come out before the rest is known, or where the layout changes often, the best-fit page builder is cheaper.

Pitfalls

  • The last page. The last page must be free, or the DP will try to fill it. A cost for its white space is a common error.
  • Figures before their reference. The test j′≤R(i′)j' \le R(i') uses the last line of the new page, not the first line.
  • A figure term that does not split. Summing a convex function of the distance does not fit the state (i,j)(i, j), and a DP that does it anyway is not exact.
  • Equal references. Two figures referenced from the same line must still keep their order; sort them by number, not by height.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

optimal_pagination.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-pagination/. The authors are listed in prov/VBW9VJ.jsonl.

"""Optimal pagination of text lines and figures by dynamic programming.

The model of the page. There are n lines of text with heights h_1 .. h_n
and m figures with heights f_1 .. f_m. Figure t is referenced from the
line r_t, with 1 <= r_1 <= r_2 <= ... <= r_m <= n. A page holds a block of
consecutive lines and a block of consecutive figures (both may be empty,
but not both), so the lines and the figures each keep their order. The
total height of a page is at most H. Figure t must be on the page of
line r_t or later.

The cost of a pagination is the sum over all pages but the last of

    (H - u)^2           the white space u of the page, squared
    + pi[i]             if the page holds lines and its last line is i
    + alpha * w         w = the number of figures referenced on this page
                        or earlier that are not yet placed

The sum of the w terms over the pages is the sum over the figures of
(page of figure t) - (page of line r_t), so alpha weighs how far each
figure floats from its reference. pi[i] is a penalty for a break after
line i (a widow or club penalty, say); pi[0] and pi[n] are not used.

Heights are ints or Fractions. Do not use floats.
"""

import math
from typing import Optional, Sequence


def ref_counts(n: int, refs: Sequence[int]) -> list[int]:
    """R[i] = the number of figures referenced from lines 1 .. i, for i = 0 .. n."""
    R = [0] * (n + 1)
    for r in refs:
        R[r] += 1
    for i in range(1, n + 1):
        R[i] += R[i - 1]
    return R


def check_input(lines: Sequence, figures: Sequence, refs: Sequence[int]) -> None:
    if len(refs) != len(figures):
        raise ValueError("one reference per figure")
    if any(h < 0 for h in lines) or any(f < 0 for f in figures):
        raise ValueError("heights must be >= 0")
    if any(not 1 <= r <= len(lines) for r in refs):
        raise ValueError("a reference must be a line number 1 .. n")
    if any(refs[t] > refs[t + 1] for t in range(len(refs) - 1)):
        raise ValueError("the references must be in order")


def page_cost(H, u, i: int, i2: int, j2: int, R: Sequence[int], alpha, pi: Sequence) -> object:
    """The cost of a page that is not the last one, from state (i, j) to (i2, j2) with height u."""
    c = (H - u) ** 2 + alpha * (R[i2] - j2)
    if i < i2 < len(R) - 1:
        c += pi[i2]
    return c


def optimal_pagination(
    lines: Sequence,
    figures: Sequence,
    refs: Sequence[int],
    H,
    alpha=1,
    pi: Optional[Sequence] = None,
    stats: Optional[dict] = None,
):
    """Return (cost, pages) of a pagination of least cost, or (math.inf, None).

    pages is the list of states (i, j) after each page: page k holds the
    lines i_{k-1}+1 .. i_k and the figures j_{k-1}+1 .. j_k. If stats is a
    dict, stats["relax"] counts the page candidates that were tried.
    """
    check_input(lines, figures, refs)
    n, m = len(lines), len(figures)
    if pi is None:
        pi = [0] * (n + 1)
    LH = [0] * (n + 1)
    for i, h in enumerate(lines):
        LH[i + 1] = LH[i] + h
    FH = [0] * (m + 1)
    for j, f in enumerate(figures):
        FH[j + 1] = FH[j] + f
    R = ref_counts(n, refs)
    relax = 0
    C = [[math.inf] * (m + 1) for _ in range(n + 1)]  # @line L1
    P = [[None] * (m + 1) for _ in range(n + 1)]
    C[0][0] = 0
    for i in range(n + 1):  # @line L2
        for j in range(m + 1):  # @line L3
            if C[i][j] == math.inf:  # @line L4
                continue
            for i2 in range(i, n + 1):  # @line L5
                if LH[i2] - LH[i] > H:
                    break
                for j2 in range(j, m + 1):  # @line L6
                    u = LH[i2] - LH[i] + FH[j2] - FH[j]
                    if j2 > R[i2] or u > H:
                        break
                    if i2 == i and j2 == j:  # @line L7
                        continue
                    relax += 1
                    last = i2 == n and j2 == m
                    d = C[i][j] + (0 if last else page_cost(H, u, i, i2, j2, R, alpha, pi))  # @line L8
                    if d < C[i2][j2]:  # @line L9
                        C[i2][j2] = d
                        P[i2][j2] = (i, j)
    if stats is not None:
        stats["relax"] = relax
    if C[n][m] == math.inf:  # @line L10
        return math.inf, None
    pages = []  # @line L11
    s = (n, m)
    while s != (0, 0):
        pages.append(s)
        s = P[s[0]][s[1]]
    pages.reverse()
    return C[n][m], pages


def pagination_cost(lines, figures, refs, H, pages, alpha=1, pi=None):
    """The cost of a pagination from the page numbers of its lines and figures.

    This does not use the split of the figure term over page breaks: it
    finds the page of every line and every figure and adds the distances.
    It returns math.inf if the pagination is not valid.
    """
    check_input(lines, figures, refs)
    n, m = len(lines), len(figures)
    if pi is None:
        pi = [0] * (n + 1)
    if not pages or pages[-1] != (n, m):
        return math.inf
    line_page = [0] * (n + 1)
    fig_page = [0] * (m + 1)
    cost = 0
    i, j = 0, 0
    for k, (i2, j2) in enumerate(pages, start=1):
        if i2 < i or j2 < j or (i2, j2) == (i, j):
            return math.inf
        u = sum(lines[i:i2]) + sum(figures[j:j2])
        if u > H:
            return math.inf
        for x in range(i + 1, i2 + 1):
            line_page[x] = k
        for t in range(j + 1, j2 + 1):
            fig_page[t] = k
        if k < len(pages):
            cost += (H - u) ** 2
        i, j = i2, j2
    for x in range(1, n):
        if line_page[x] < line_page[x + 1]:
            cost += pi[x]
    for t in range(1, m + 1):
        d = fig_page[t] - line_page[refs[t - 1]]
        if d < 0:
            return math.inf
        cost += alpha * d
    return cost


def all_paginations(n: int, m: int):
    """Every sequence of states from (0, 0) to (n, m), for tiny inputs only."""

    def rec(i, j):
        if (i, j) == (n, m):
            yield []
            return
        for i2 in range(i, n + 1):
            for j2 in range(j, m + 1):
                if (i2, j2) != (i, j):
                    for rest in rec(i2, j2):
                        yield [(i2, j2)] + rest

    return rec(0, 0)


def first_fit_pagination(lines, figures, refs, H):
    """A simple baseline, not optimal: each page first takes the waiting figures
    (referenced on an earlier page) that fit, in order, and then as many lines
    as fit. Returns the pages, or None if some item is taller than H."""
    check_input(lines, figures, refs)
    n, m = len(lines), len(figures)
    R = ref_counts(n, refs)
    pages = []
    i = j = 0
    while (i, j) != (n, m):
        u = 0
        i2, j2 = i, j
        while j2 < R[i] and u + figures[j2] <= H:
            u += figures[j2]
            j2 += 1
        while i2 < n and u + lines[i2] <= H:
            u += lines[i2]
            i2 += 1
        if (i2, j2) == (i, j):
            return None
        pages.append((i2, j2))
        i, j = i2, j2
    return pages
test_optimal_pagination.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-pagination/. The authors are listed in prov/VBW9VJ.jsonl.

import math
import random
from fractions import Fraction

from optimal_pagination import (
    all_paginations,
    first_fit_pagination,
    optimal_pagination,
    pagination_cost,
    ref_counts,
)


def brute_force(lines, figures, refs, H, alpha, pi):
    best = math.inf
    for pages in all_paginations(len(lines), len(figures)):
        best = min(best, pagination_cost(lines, figures, refs, H, pages, alpha, pi))
    return best


def random_instance(rng, n_max, m_max):
    n = rng.randint(1, n_max)
    m = rng.randint(0, m_max)
    lines = [rng.randint(1, 3) for _ in range(n)]
    figures = [rng.randint(1, 5) for _ in range(m)]
    refs = sorted(rng.randint(1, n) for _ in range(m))
    H = rng.randint(3, 8)
    alpha = rng.choice([0, 1, 3, 10])
    pi = [rng.choice([0, 7])] + [rng.choice([0, 0, 5, 50]) for _ in range(n - 1)] + [rng.choice([0, 7])]
    return lines, figures, refs, H, alpha, pi


def test_ref_counts():
    assert ref_counts(5, [2, 2, 5]) == [0, 0, 2, 2, 2, 3]
    assert ref_counts(3, []) == [0, 0, 0, 0]


def test_example_of_the_page():
    lines, figures, refs, H, alpha = [1] * 8, [3], [4], 5, 5
    cost, pages = optimal_pagination(lines, figures, refs, H, alpha)
    assert (cost, pages) == (4, [(3, 0), (5, 1), (8, 1)])
    ff = first_fit_pagination(lines, figures, refs, H)
    assert ff == [(5, 0), (7, 1), (8, 1)]
    assert pagination_cost(lines, figures, refs, H, ff, alpha) == 5


def test_widow_penalty_moves_a_break():
    lines = [1, 1, 1, 1]
    assert optimal_pagination(lines, [], [], 3) == (0, [(3, 0), (4, 0)])
    pi = [0, 0, 0, 100, 0]
    assert optimal_pagination(lines, [], [], 3, pi=pi) == (1, [(2, 0), (4, 0)])


def test_infeasible_and_trivial_inputs():
    assert optimal_pagination([1, 1], [9], [1], 5) == (math.inf, None)
    assert optimal_pagination([7], [], [], 5) == (math.inf, None)
    assert optimal_pagination([2, 2], [], [], 5) == (0, [(2, 0)])
    assert optimal_pagination([], [], [], 5) == (0, [])


def test_bad_input_is_rejected():
    for args in (([1], [1], []), ([1], [1], [2]), ([1, 1], [1, 1], [2, 1]), ([-1], [], [])):
        try:
            optimal_pagination(*args, 5)
        except ValueError:
            continue
        raise AssertionError("bad input accepted")


def test_figure_never_before_its_reference():
    rng = random.Random(3)
    for _ in range(200):
        lines, figures, refs, H, alpha, pi = random_instance(rng, 9, 3)
        cost, pages = optimal_pagination(lines, figures, refs, H, alpha, pi)
        if pages is None:
            continue
        line_page, fig_page = {}, {}
        i = j = 0
        for k, (i2, j2) in enumerate(pages):
            for x in range(i + 1, i2 + 1):
                line_page[x] = k
            for t in range(j + 1, j2 + 1):
                fig_page[t] = k
            i, j = i2, j2
        for t, r in enumerate(refs, start=1):
            assert fig_page[t] >= line_page[r]


def test_against_brute_force():
    rng = random.Random(1)
    feasible = 0
    for _ in range(150):
        lines, figures, refs, H, alpha, pi = random_instance(rng, 7, 2)
        cost, pages = optimal_pagination(lines, figures, refs, H, alpha, pi)
        assert cost == brute_force(lines, figures, refs, H, alpha, pi)
        if pages is not None:
            feasible += 1
            assert pagination_cost(lines, figures, refs, H, pages, alpha, pi) == cost
    assert feasible >= 100


def test_fraction_heights():
    lines = [Fraction(1, 2)] * 6
    cost, pages = optimal_pagination(lines, [Fraction(3, 2)], [2], Fraction(2))
    assert cost == brute_force(lines, [Fraction(3, 2)], [2], Fraction(2), 1, [0] * 7)
    assert pagination_cost(lines, [Fraction(3, 2)], [2], Fraction(2), pages) == cost


def test_dp_is_never_worse_than_first_fit():
    rng = random.Random(2)
    better = 0
    for _ in range(300):
        lines, figures, refs, H, alpha, _ = random_instance(rng, 12, 3)
        cost, _ = optimal_pagination(lines, figures, refs, H, alpha)
        ff = first_fit_pagination(lines, figures, refs, H)
        if ff is None:
            continue
        fc = pagination_cost(lines, figures, refs, H, ff, alpha)
        assert cost <= fc
        better += cost < fc
    assert better > 0


def test_number_of_page_candidates():
    rng = random.Random(4)
    n, m, H = 400, 6, 10
    lines = [1] * n
    figures = [rng.randint(1, 4) for _ in range(m)]
    refs = sorted(rng.randint(1, n) for _ in range(m))
    stats = {}
    cost, pages = optimal_pagination(lines, figures, refs, H, 3, stats=stats)
    assert pages is not None
    assert stats["relax"] <= (n + 1) * (m + 1) * (H + 1) ** 2
    assert pagination_cost(lines, figures, refs, H, pages, 3) == cost

History

Michael Plass, a student of Donald Knuth, studied the pagination of text with figures in his Stanford PhD thesis of 1981. He showed that the problem is NP-complete for two simple badness functions, so a fast exact method needs a restricted model such as the one on this page. In the same year, Knuth and Plass published the total-fit method for lines, which this method carries over to pages. TeX itself kept the simpler best-fit page builder.

References

  1. Michael F. Plass, Optimal Pagination Techniques for Automatic Typesetting Systems, PhD thesis, Stanford University, 1981, the optimal pagination of text with figures, and the badness functions for which the problem is NP-complete
  2. Donald E. Knuth and Michael F. Plass, Breaking paragraphs into lines, Software, Practice and Experience 11(11), 1119-1184, 1981, the total-fit method for lines, which optimal pagination carries over to pages

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/VBW9VJ/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example