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.
- Solves
- Page breaking
- Time
- O(n^2 m^2) worst
- Space
- Θ(n m) extra
- Where
- m = the number of figures; n = the number of text lines
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Full proofCode in 1 languages
- 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 text lines with heights and figures with heights , all . Figure is referenced from line , with . The page height is . 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 of a page is at most . There is no glue: the white space of a page is .
- Figure is on the page of line or on a later page.
The cost of a pagination adds, for every page except the last one:
- , the white space, squared;
- if the page holds lines and its last line is not line ; this is the cost of a break after line , for example a widow or club penalty;
- , where is the number of figures referenced on this page or earlier that are not placed yet, and is a weight.
The sum of the terms 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 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 be the number of figures referenced from lines . A state means that the first lines and the first figures are on finished pages. A page from to is allowed when it fits and : every figure on it is referenced on this page or earlier. Its cost depends only on , , and the height , so it is an edge weight in a DAG over the states. Prefix sums of the heights give in time.
OPTIMAL-PAGES(h_1 .. h_n, f_1 .. f_m, r_1 .. r_m, H, α, π)- 1
C[0][0] ← 0; C[i][j] ← ∞ for every other state - 2
for i ← 0 to n do - 3
for j ← 0 to m do - 4
if C[i][j] = ∞ then continue - 5
for i' ← i to n, while the lines i+1 .. i' fit in H do - 6
for j' ← j to m, while j' ≤ R(i') and the page fits in H do - 7
if (i', j') = (i, j) then continue - 8
d ← C[i][j] + the cost of the page from (i, j) to (i', j'), or 0 if (i', j') = (n, m) - 9
if d < C[i'][j'] then C[i'][j'] ← d; P[i'][j'] ← (i, j) - 10
if C[n][m] = ∞ then return failure - 11
follow 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 is fixed for a fixed .
Example
Take eight lines of height 1, one figure of height 3 referenced from line 4, page height , 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 | |
| optimal | lines 1 to 3 | lines 4 and 5, figure | lines 6 to 8 | |
| lines 1 to 4 | figure, line 5 ... | 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 . 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 after each page. Second, the cost splits over the pages: a figure that floats pages from its reference is counted once at each of the page breaks between them, and at each break the number of such figures is . So the valid paginations are the paths from to 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 , the figures have heights , figure is referenced from line with , and is the number of figures with . A state is a pair with and . A pagination with pages is a sequence of states with , , and . Page holds the lines and the figures , and its height is , the sum of their heights. The pagination is valid if for every and every figure is on the page of its reference or later. Its cost is
where the middle sum is over the lines with such that line is on a later page than line , is the page of figure and is the page of line .
Lemma 1 (validity is local). Every figure is on the page of its reference or later if and only if for every .
Proof. Since the references are sorted, holds exactly when . Suppose that for all , and let figure be on page , so . Then , so line is on page or earlier. Conversely, suppose that every figure is on the page of its reference or later, and take with . Figure is on a page , so its reference line is on a page , and . Hence .
Lemma 2 (the cost splits over the pages). For a valid pagination, the cost is , where
and is the height of the page from to .
Proof. The first terms agree by definition. For the penalties: let . Line is on a later page than line exactly when line is the last line of its page , that is, and ; then , since line comes later. So each such is counted once, by the page with , and no other page adds a penalty. For the figures: is the number of with , which is the number of with , and . Summed over , this is . By Lemma 1 and the sorted references, every has , so the set has elements.
The DAG. Put an edge from the state to the state when in both coordinates, the page from to has height at most , and . Its weight is if and 0 if . By Lemmas 1 and 2, the valid paginations are exactly the paths from to 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 , since no edge leaves . 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 , they relax every edge that leaves , and only such edges.
Proof. Heights are , so the height of the lines does not decrease when grows, and the loop of line L5 stops only when no larger can give a page that fits. For a fixed , the height of the page does not decrease when grows and is fixed, so the loop of line L6 stops only when no larger gives an edge. Line L7 skips . Every pair that reaches line L8 satisfies the three conditions of an edge, and line L8 adds its weight.
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 is processed, is the least weight of a path from to : all edges into come from earlier states, which were processed with their final values. So is the least cost of a valid pagination, or when there is none, and then line L10 reports failure. The links store the last edge of a best path to each state, so line L11 rebuilds a path whose weight is .
Complexity. There are states, and each state has at most edges, each relaxed in time with prefix sums. So the time is and the space is . If every page holds at most lines and figures, for example because every height is at least 1 and is fixed, a state has at most edges and the time is .
Complexity
There are states, each with at most pages leaving it, and each page costs time. So the time is and the extra space is for the table and the links. If a page holds at most lines and figures, as when every height is at least 1, the time is , which is linear in for a fixed page size. When , the method is a least weight subsequence problem over the lines, in 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, , 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 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 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 , 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.
# 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VBW9VJ Edit this page History Report an error Markdown