Algorithm Search⌘K

Algorithmcore

Best-fit page breaking

Also called TeX page builder.

Add lines to the current page and break at the feasible break of least cost seen before the page overflows, without looking ahead.

Time
O(m k) worstΘ(m) best
Space
Θ(m) extra
Where
k = the largest number of items scanned for one page; m = the number of items of the vertical list
Properties
deterministicnot exactiterative
Origin
Donald E. Knuth, 1984

Best-fit page breaking is the method that TeX uses to divide a long vertical list of lines into pages. It fills one page at a time: it moves lines onto the current page, gives each possible break a cost from how much the page must stretch or shrink and from the penalty at the break, and keeps the break of least cost seen so far. When the page is too full to take more, or a break is forced, it ends the page at the best break and starts the next page there. It never looks at later pages, so it is fast and simple, but it does not always find the breaking of least total cost; optimal pagination does that with dynamic programming.

In plain words

Think of a person who fills pages with lines of text. They put lines on the page one by one. After each line, they ask: if the page ended here, how bad would it look? A page that is too empty must spread its lines apart, and some places are bad for a break, for example after the first line of a paragraph.

They remember the best place so far. When the next line does not fit at all, they cut the page at the best place they remember, and they start the next page with the lines after it.

They never think about the pages that come later. Sometimes a good cut now forces a bad page later.

The problem

The input is a vertical list x0,…,xm−1x_0, \ldots, x_{m-1} in the box, glue and penalty model, as in the page breaking problem:

  • a box is a line (or a display, a figure, a heading) of height h≥0h \ge 0 and depth d≥0d \ge 0;
  • a glue is a space between lines of natural size w≥0w \ge 0, stretch y≥0y \ge 0 and shrink z≥0z \ge 0; the stretch can be of an infinite order (fil, fill), but the shrink is finite;
  • a penalty pp marks a place where a break is good (p<0p < 0), bad (p>0p > 0), forbidden (p≥10000p \ge 10000) or forced (p≤−10000p \le -10000). Widow and club penalties are penalties of this kind.

A break may be at a penalty with p<10000p < 10000, or at a glue that comes right after a box. The last item is a forced penalty. The input also has the page goal gg, the height of the text on a page, and a maximum depth DD.

The page total. A page that starts at the box ss and ends at the break bb holds xs,…,xb−1x_s, \ldots, x_{b-1}. Its total tt is the sum of the heights of its boxes, the sizes of its glue, and the depths of its boxes except the last one: the depth of the last box hangs below the page and counts only for its part above DD. Its stretch YY and shrink ZZ are the sums over its glue.

The badness of a page. If t<gt < g and some glue has infinite stretch, the badness is β=0\beta = 0. If t<gt < g otherwise, β\beta is the badness of TeX for stretching by g−tg - t with stretch YY, which is about 100((g−t)/Y)3100 \bigl((g - t) / Y\bigr)^3 and is capped at 10000. If t−g>Zt - g > Z, the page does not fit and β=∞\beta = \infty. Otherwise β\beta is the badness for shrinking by t−gt - g with shrink ZZ.

The cost of a break. With β\beta and the penalty pp of the break (p=0p = 0 at a glue):

  • c=∞c = \infty if β=∞\beta = \infty;
  • c=pc = p if p≤−10000p \le -10000 (a forced break on a page that fits);
  • c=β+pc = \beta + p if β<10000\beta < 10000;
  • c=100000c = 100000 if β=10000\beta = 10000.

In TeX, cc also adds a penalty qq for footnotes and other insertions that are split, and c=∞c = \infty if q≥10000q \ge 10000. This page leaves insertions out, so q=0q = 0.

The algorithm

  1. BEST-FIT-PAGES(x_0 .. x_{m−1}, g, D)
  2. 1breaks ← empty list; a ← −1
  3. 2loop
  4. 3s ← the first box after the break a
  5. 4if there is no such box then leave the loop
  6. 5least ← ∞; best ← none
  7. 6for b ← s + 1 to m − 1 do
  8. 7if b is not a legal break then continue
  9. 8(t, Y, Z) ← the page total, stretch and shrink of x_s .. x_{b−1}
  10. 9c ← the cost of the break b, from the badness of (t, Y, Z) against g
  11. 10if c ≤ least then
  12. 11least ← c; best ← b
  13. 12if c = ∞ or x_b is a forced penalty then leave the for loop
  14. 13append best to breaks
  15. 14a ← best
  16. 15return breaks

Line L3 drops the glue and penalties at the top of a page, as TeX does, so a page never starts with white space. Line L8 uses prefix sums of the sizes, stretches and shrinks, so it takes O(1)O(1) time; it removes the depth of the last box when no glue follows it on the page. Line L10 uses ≤\le, so a later break wins a tie, as in TeX. Line L12 stops at the first break where the page does not fit: the total can only grow when the page gets longer, so no later break can fit. If the first break already does not fit, its cost ∞\infty is still ≤least\le least, and the page is overfull, which is what TeX does. The items after the best break and up to the stopping break go back to the list and start the next page.

Example

Take six lines of heights 10, 10, 10, 10, 20 and 20 (the last two could be displays), glue of size 2, stretch 8 and shrink 1 between them, the ending of plain TeX (glue with fill stretch and a forced break) and page goal g=44g = 44. All depths are 0 and all penalties are 0.

page lines total badness cost
1 1 10 10000 (no stretch) 100000
1 1 to 2 22 2073 2073
1 1 to 3 34 24 24
1 1 to 4 46 30 30
1 1 to 5 68 ∞\infty ∞\infty, stop
2 4 to 5 32 336 336
2 4 to 6 54 ∞\infty ∞\infty, stop
3 6 20 0 (fill) forced

On page 1 the break after line 3 costs 24 and the break after line 4 costs 30, so the builder ends page 1 after line 3. Page 2 then starts with a short line and two tall ones: lines 4 and 5 make 32 units, which must stretch by 12 with only 8 units of stretch, and lines 4 to 6 do not fit. The total cost of the unforced breaks is 24+336=36024 + 336 = 360. The breaking with lines 1 to 4 on page 1 (cost 30) and lines 5 and 6 on page 2 (total 42, at the forced break) costs 30. The builder saved 6 points on page 1 and paid 336 on page 2.

Correctness

The builder is not exact for the total cost, as the example shows, so its correctness is that it does what TeX does. Two facts carry the proof. First, the prefix sums with the depth correction give, for each break, the same total that TeX keeps item by item with its separate page depth. Second, the scan of lines L6 to L12 sees exactly the legal breaks up to the first one where the page does not fit or a break is forced, and the test c≤leastc \le least keeps the last break of least cost among them. Each page ends after it starts, so the loop ends after at most mm pages. The full proof is in the proof file below.

Proof: The page builder returns the pages of the TeX rulefull

We use the model and the pseudocode of the page. The items are x0,…,xm−1x_0, \ldots, x_{m-1}, boxes have height h≥0h \ge 0 and depth d≥0d \ge 0, glue has width w≥0w \ge 0, stretch y≥0y \ge 0 of some order and finite shrink z≥0z \ge 0, and xm−1x_{m-1} is a forced penalty. For a page that starts at the box ss and a legal break b>sb > s, let T(s,b)T(s, b), Y(s,b)Y(s, b) and Z(s,b)Z(s, b) be the page total, the stretch by order and the shrink, as defined on the page: the heights of the boxes in xs,…,xb−1x_s, \ldots, x_{b-1}, the depths of these boxes except the depth of the last box xkx_k when no glue lies between xkx_k and xbx_b, the part of that last depth above the maximum depth DD, and the widths, stretches and shrinks of the glue in xs,…,xb−1x_s, \ldots, x_{b-1}. Let c(s,b)c(s, b) be the cost of the break bb for this page, computed from TT, YY, ZZ, the page goal and the penalty of xbx_b by the rules of the page.

The TeX rule. For a page that starts at the box ss, let b1<b2<⋯b_1 < b_2 < \cdots be the legal breaks after ss, and let ee be the first of them with c(s,e)=∞c(s, e) = \infty or with xex_e a forced penalty. The page ends at the last bi≤eb_i \le e with the least value of c(s,bi)c(s, b_i) among b1,…,eb_1, \ldots, e. The next page starts at the first box after that break. This is the rule of TeX: The Program, part 45, for a vertical list with boxes, glue and penalties only.

Lemma 1 (the page total). For every page start ss and legal break b>sb > s, the value that line L8 computes is (T(s,b),Y(s,b),Z(s,b))(T(s, b), Y(s, b), Z(s, b)), and it is equal to the running totals that TeX holds when it reaches xbx_b.

Proof. The prefix sums give the sum of h+dh + d over the boxes and of ww, yy and zz over the glue in xs,…,xb−1x_s, \ldots, x_{b-1}. Line L8 then removes the depth dd of the last box xkx_k when no glue lies between xkx_k and xbx_b, and adds back d−Dd - D when d>Dd > D. This is T(s,b)T(s, b) by definition. TeX keeps a running total tt and a separate page depth δ\delta. On a box, it sets t←t+δ+ht \leftarrow t + \delta + h and δ←d\delta \leftarrow d, and if δ>D\delta > D it moves δ−D\delta - D into tt and sets δ←D\delta \leftarrow D. On a glue, it sets t←t+δ+wt \leftarrow t + \delta + w and δ←0\delta \leftarrow 0. A penalty changes neither. So a box adds its full depth to tt once a glue or another box follows it: the part above DD at once, the rest later. The last box adds only the part above DD when only penalties follow it. Its height counts at once in both cases. This is T(s,b)T(s, b). The stretch and shrink sums agree, since TeX adds them on each glue. □\square

Lemma 2 (one page). Let the loop of line L2 start a page after the break aa. Line L3 sets ss to the first box after aa. If s<ms < m, then lines L5 to L12 end with bestbest equal to the break that the TeX rule chooses for the page that starts at ss, and with best>abest > a.

Proof. TeX discards glue and penalties at the top of a page, so the page starts at the first box after aa, which is ss. Since xsx_s is a box, s<m−1s < m - 1, and the forced penalty xm−1x_{m-1} is a legal break after ss. So ee exists. Line L6 visits b=s+1,s+2,…b = s + 1, s + 2, \ldots in order, and line L7 skips the items that are not legal breaks, so lines L8 to L12 run for b1,b2,…b_1, b_2, \ldots in order. By Lemma 1 and line L9, cc is c(s,bi)c(s, b_i). Line L12 stops after the first bib_i with c=∞c = \infty or a forced penalty, which is ee. So exactly b1,…,eb_1, \ldots, e are compared. Line L5 starts with least=∞least = \infty, and lines L10 and L11 replace (least,best)(least, best) whenever c≤leastc \le least. By induction on ii, after bib_i the value leastleast is the least cost among b1,…,bib_1, \ldots, b_i and bestbest is the last break that has it, because a later break with an equal cost replaces an earlier one. At the first break, c≤∞=leastc \le \infty = least holds, so bestbest is set, and best≥b1>s>abest \ge b_1 > s > a. □\square

Theorem. The page builder terminates. It returns the breaks of the TeX rule: the first page starts at the first box, each page ends at the break that the rule chooses, and the next page starts at the first box after it. The list ends when no box is left.

Proof. By Lemma 2, each pass of the loop of line L2 with s<ms < m appends the break of the rule (line L13) and moves aa to it (line L14), and the new aa is larger than the old one. There are at most mm legal breaks, so after at most mm passes line L3 finds no box after aa, and line L4 ends the loop. When the loop ends, every box lies on a page, since a pass starts at the first box after the last break. Glue and penalties after the last break, including the final forced penalty when the last page ends before it, are discarded, as TeX discards them at the top of a page. □\square

Complexity. The prefix sums, the arrays of the last box and the last glue, and the array of the next box take O(m)O(m) time and space. Each pass of line L6 takes O(1)O(1) time, and line L3 takes O(1)O(1) time. Let kk be the largest value of e−se - s over the pages, the number of items that line L6 scans for one page. The number of pages PP is at most the number of boxes, which is at most mm. So the time is O(m+Pk)O(m + P k), which is O(mk)O(m k) in the worst case. Items after the chosen break and up to ee are scanned again by the next page, as in TeX, where they go back to the list of contributions; this is why the bound is not O(m)O(m). When each page holds about kk legal breaks, PkP k is O(m)O(m) and the time is linear. The extra space is O(m)O(m).

Complexity

Each break is tested in O(1)O(1) time. A page scans the items from its first box to its stopping break, and the items after its best break are scanned again for the next page, so the time is O(m+Pk)O(m + P k) for PP pages, where kk is the largest number of items scanned for one page. This is O(mk)O(m k) in the worst case. In practice a page holds about kk items, so PkP k is about mm and the time is Θ(m)\Theta(m). The prefix sums take Θ(m)\Theta(m) extra space; TeX itself keeps only running totals for the current page.

Properties

  • A heuristic. It does not minimize the total cost of the breaks, and the example above loses by a factor of 12. The choices of the plain TeX values (for example \clubpenalty=150 and \widowpenalty=150) are design choices, not results.
  • Online. It needs only the current page and the next item, so TeX can ship out a page before it reads the rest of the document. This matters for page numbers and running heads that depend on the material.
  • Deterministic and iterative. A later break wins a tie.
  • Overfull pages are possible. When a single box is taller than the page goal plus the shrink, the page is overfull, and TeX reports it.

Variants and improvements

  • Insertions. TeX adds footnotes, floating figures and tables as insertions. Each one takes space from the page goal, and a split insertion adds the penalty qq to the cost.
  • Top skip and marks. TeX puts the glue \topskip before the first box of a page so that the first baselines line up, and it keeps marks for running heads. Both leave the method the same.
  • Splitting a box. The \vsplit operation of TeX uses the same cost to cut a box of a given height from a vertical list, for columns and for balancing.
  • Optimal breaking. Optimal pagination chooses all page breaks together, as Knuth-Plass line breaking does for lines. With floating figures, the general problem is hard; see the NP-completeness of pagination.

When to use it

Use it when pages must be produced one at a time, as in TeX, when the document is long, or when later material is not known yet. When the whole document is known and the cost of a bad page is high, as in books with many displays, use optimal pagination, or run the builder and then fix the worst pages by hand.

Pitfalls

  • The depth of the last box. The depth of the last line hangs below the bottom of the page and does not count in the total, unless it is more than DD. Counting it makes every page look fuller than it is.
  • Glue at the top. The glue and penalties after a break are dropped. A forced penalty that comes at the top of a page is dropped too, so the list of breaks can end before the last item.
  • The cost 100000. A page with badness 10000 costs 100000, not 10000+p10000 + p. So when no break fits well, the builder takes the latest such break, which can end a page right before a heading.
  • It is not optimal. Do not use it as a reference for tests of an optimal method. Test it against an item by item copy of the TeX rule instead.

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.

best_fit_page_breaking.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/best-fit-page-breaking/. The authors are listed in prov/81895S.jsonl.

"""Best-fit page breaking: the page builder of TeX, without insertions.

The input is a vertical list of boxes (lines, with height and depth), glue
(the space between lines) and penalties. The builder fills one page at a
time. At each legal breakpoint it computes the cost c of a break there, as
in The TeXbook, chapter 15, and TeX: The Program, part 45. It keeps the
break of least cost seen so far (a later break wins a tie), and it ends the
page at that break as soon as c is infinite or a penalty forces a break.
It never looks at later pages.

Simplifications, each one stated on the page: no insertions (so q = 0),
no \\topskip glue, no marks and no kerns. Glue with infinite shrink is
rejected, as TeX reports it as an error on a page.
"""

import math
from typing import Optional, Sequence

from boxglue import INF_BAD, INF_PENALTY, NORMAL, Box, Glue, Item, Measures, Penalty, all_breakings, is_forced, is_legal_break, tex_badness

AWFUL_BAD = math.inf  # awful_bad of TeX: the cost of a page that does not fit
DEPLORABLE = 100000  # the cost of a page with badness INF_BAD


class Page:
    """Prefix data for the pages of one vertical list.

    total(s, b) is the page total of TeX for the items s .. b-1: the heights
    of the boxes, the depths of all boxes but the last one, and the natural
    sizes of the glue. The depth of the last box counts only when a glue
    follows it on the page, as in TeX, and only the part above max_depth.
    """

    def __init__(self, items: Sequence[Item], max_depth=None) -> None:
        for x in items:
            if isinstance(x, Glue) and x.shrink != 0 and x.shrink_order != NORMAL:
                raise ValueError("infinite shrink on a page")
        self.items = list(items)
        self.meas = Measures(items, vertical=True)
        self.max_depth = max_depth
        m = len(items)
        # last_box[i], last_glue[i]: the largest index < i that holds a box or a glue, or -1
        self.last_box = [-1] * (m + 1)
        self.last_glue = [-1] * (m + 1)
        for i, x in enumerate(items):
            self.last_box[i + 1] = i if isinstance(x, Box) else self.last_box[i]
            self.last_glue[i + 1] = i if isinstance(x, Glue) else self.last_glue[i]

    def first_box(self, a: int) -> int:
        """The first item of the page after break a: discardable items are dropped."""
        return self.meas.next_box[a + 1]

    def total(self, s: int, b: int):
        """(page total, stretch by order, normal shrink) of the items s .. b-1."""
        W, Y, Z = self.meas.W, self.meas.Y, self.meas.Z
        t = W[b] - W[s]
        k = self.last_box[b]
        if k >= s and self.last_glue[b] < k:
            d = self.items[k].depth  # the page depth: not yet in the total
            t -= d
            if self.max_depth is not None and d > self.max_depth:
                t += d - self.max_depth
        stretch = tuple(Y[o][b] - Y[o][s] for o in range(len(Y)))
        return t, stretch, Z[NORMAL][b] - Z[NORMAL][s]


def page_badness(total, stretch, shrink, goal):
    """The badness b of a page with this total, set to the page goal.

    It is 0 when the page must stretch and has stretch of an infinite order,
    AWFUL_BAD when it must shrink more than its shrink, and otherwise the
    integer badness of TeX. Sizes are integers (scaled points or abstract
    units).
    """
    if total < goal:
        if any(stretch[1:]):
            return 0
        return tex_badness(goal - total, stretch[NORMAL])
    if total - goal > shrink:
        return AWFUL_BAD
    return tex_badness(total - goal, shrink)


def break_cost(b, p: int, q: int = 0):
    """The cost c of a page break with page badness b, penalty p and insert penalties q.

    The TeXbook, chapter 15: c = p for a forced break on a page that fits,
    b + p + q when b < 10000, 100000 when b = 10000, and infinite when the
    page does not fit or q >= 10000.
    """
    if b < AWFUL_BAD:
        if p <= -INF_PENALTY:
            c = p
        elif b < INF_BAD:
            c = b + p + q
        else:
            c = DEPLORABLE
    else:
        c = AWFUL_BAD
    if q >= INF_PENALTY:
        c = AWFUL_BAD
    return c


def _penalty(x: Item) -> int:
    return x.penalty if isinstance(x, Penalty) else 0


def page_builder(items: Sequence[Item], goal, max_depth=None, stats: Optional[dict] = None):
    """Break a vertical list into pages as TeX does. Returns (breaks, costs).

    breaks[j] is the index of the item where page j ends (the item itself
    is dropped), and costs[j] is the cost c of that break. The last item
    must be a forced penalty. When no break on a page fits, the builder
    takes the first break where the page does not fit (an overfull page),
    as TeX does. A forced penalty that comes at the top of a page is
    discarded with the glue there, so the breaks can end before the last
    item. If stats is a dict, stats["tests"] counts the breakpoints at
    which a cost was computed.
    """
    m = len(items)
    if m == 0 or not is_forced(items[-1]):
        raise ValueError("the last item must be a forced penalty")
    pg = Page(items, max_depth)
    tests = 0
    breaks: list[int] = []  # @line L1
    costs: list = []
    a = -1
    while True:  # @line L2
        s = pg.first_box(a)  # @line L3
        if s >= m:  # @line L4
            break
        least, best = AWFUL_BAD, None  # @line L5
        for b in range(s + 1, m):  # @line L6
            if not is_legal_break(items, b):  # @line L7
                continue
            tests += 1
            p = _penalty(items[b])
            total, stretch, shrink = pg.total(s, b)  # @line L8
            c = break_cost(page_badness(total, stretch, shrink, goal), p)  # @line L9
            if c <= least:  # @line L10
                least, best = c, b  # @line L11
            if c == AWFUL_BAD or p <= -INF_PENALTY:  # @line L12
                break
        breaks.append(best)  # @line L13
        costs.append(least)
        a = best  # @line L14
    if stats is not None:
        stats["tests"] = tests
    return breaks, costs  # @line L15


def breaking_cost(items: Sequence[Item], breaks: Sequence[int], goal, max_depth=None):
    """The total cost of a breaking: the sum of c over its unforced breaks.

    A forced break adds 0, since every breaking has the same forced breaks.
    The value is AWFUL_BAD when a page does not fit, when a page has no box,
    or when a page runs past a forced break.
    """
    pg = Page(items, max_depth)
    total_cost = 0
    a = -1
    for b in breaks:
        s = pg.first_box(a)
        if s >= b:
            return AWFUL_BAD
        for i in range(s, b):
            if is_forced(items[i]):
                return AWFUL_BAD
        p = _penalty(items[b])
        t, stretch, shrink = pg.total(s, b)
        c = break_cost(page_badness(t, stretch, shrink, goal), p)
        if c == AWFUL_BAD:
            return AWFUL_BAD
        if p > -INF_PENALTY:
            total_cost += c
        a = b
    if pg.first_box(a) < len(items):
        return AWFUL_BAD  # a box is left after the last break
    return total_cost


def optimal_breaking(items: Sequence[Item], goal, max_depth=None):
    """The brute force optimum (cost, breaks) over all breakings, for tiny lists only.

    A breaking may also stop before the last item when only glue and
    penalties follow its last break (TeX discards them at the top of the
    next page), so each breaking is tried with and without its last break.
    """
    best_cost, best_breaks = AWFUL_BAD, None
    for full in all_breakings(items):
        for br in (full, full[:-1]):
            if not br:
                continue
            c = breaking_cost(items, br, goal, max_depth)
            if c < best_cost:
                best_cost, best_breaks = c, br
    return best_cost, best_breaks


def lines(heights, glue: Glue, penalties: Optional[Sequence[int]] = None, finish: bool = True) -> list[Item]:
    """A vertical list of lines of the given heights (depth 0), with glue between them.

    penalties[i], when given and nonzero, is a penalty put before the glue
    that follows line i (a club or widow penalty, say). With finish, the
    list ends as \\end does in plain TeX: a glue 0 plus 1fill and a forced
    break.
    """
    items: list[Item] = []
    for i, h in enumerate(heights):
        if i > 0:
            pen = penalties[i - 1] if penalties else 0
            if pen:
                items.append(Penalty(0, pen))
            items.append(glue)
        items.append(Box(0, h))
    if finish:
        items.append(Glue(0, 1, 0, stretch_order=2))
        items.append(Penalty(0, -INF_PENALTY))
    return items
boxglue.py 329 lines
# SPDX-License-Identifier: MIT
# Shared helper of the text processing and typesetting pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Boxes, glue and penalties, in the notation of the typesetting pages.

This module holds no line breaking or page breaking method. It gives:

- the item types Box, Glue and Penalty, and the constant INF_PENALTY;
- a paragraph builder from word widths, with an interword glue and the
  ending of TeX (penalty 10000, glue 0 plus 1fil, penalty -10000);
- the legal breakpoints of an item list;
- the measures (L, Y, Z) of a line between two breaks, by prefix sums;
- the adjustment ratio r as a Fraction;
- the real badness min(100 |r|^3, 10000) as an exact Fraction, and the
  integer badness of TeX: The Program, section 108;
- a brute force that lists every breaking of a tiny paragraph;
- a text renderer for examples.

Widths are ints or fractions.Fraction. Do not use floats for widths.

A break is an index b of the item list. The start of the paragraph is the
break -1. A line from break a to break b holds the items a+1 .. b-1, less
the glue and penalties that follow a before the first box (TeX discards
them), plus the width of x_b when x_b is a penalty (a hyphen). Nothing is
discarded at the start of the paragraph (a = -1).

Glue can have an infinite order: 0 is normal, 1 is fil, 2 is fill and 3 is
filll, as in TeX. Stretch and shrink totals are tuples with one entry per
order.
"""

from dataclasses import dataclass
from fractions import Fraction
from itertools import product
import math
from typing import Iterator, Sequence, Union

Number = Union[int, Fraction]

INF_PENALTY = 10000  # a penalty >= INF_PENALTY forbids a break, <= -INF_PENALTY forces one
INF_BAD = 10000  # the largest finite badness (inf_bad in TeX)
NORMAL, FIL, FILL, FILLL = 0, 1, 2, 3
ORDERS = 4


@dataclass(frozen=True)
class Box:
    """A rigid item: a letter, a word or a line. text is for the renderer."""

    width: Number
    height: Number = 0
    depth: Number = 0
    text: str = ""


@dataclass(frozen=True)
class Glue:
    """A space with natural width, stretchability y and shrinkability z."""

    width: Number
    stretch: Number = 0
    shrink: Number = 0
    stretch_order: int = NORMAL
    shrink_order: int = NORMAL


@dataclass(frozen=True)
class Penalty:
    """A possible break with cost penalty. flagged marks a hyphen."""

    width: Number
    penalty: int
    flagged: bool = False


Item = Union[Box, Glue, Penalty]


def is_forced(item: Item) -> bool:
    """True for a penalty of -INF_PENALTY or less (a forced break)."""
    return isinstance(item, Penalty) and item.penalty <= -INF_PENALTY


def is_legal_break(items: Sequence[Item], b: int) -> bool:
    """A penalty below INF_PENALTY, or a glue right after a box."""
    x = items[b]
    if isinstance(x, Penalty):
        return x.penalty < INF_PENALTY
    if isinstance(x, Glue):
        return b > 0 and isinstance(items[b - 1], Box)
    return False


def legal_breakpoints(items: Sequence[Item]) -> list[int]:
    """The indices of all legal breakpoints, in increasing order."""
    return [b for b in range(len(items)) if is_legal_break(items, b)]


def _box(piece) -> Box:
    if isinstance(piece, Box):
        return piece
    if isinstance(piece, str):
        return Box(len(piece), text=piece)
    return Box(piece)


def paragraph(
    words: Sequence,
    space: Glue = Glue(1, 0, 0),
    hyphen_width: Number = 1,
    hyphen_penalty: int = 50,
    finish: bool = True,
) -> list[Item]:
    """Build the item list of a paragraph.

    Each word is a width (int or Fraction), a str (width len(str), and the
    text is kept), a Box, or a list or tuple of such pieces. Between two
    pieces of one word the builder puts a flagged penalty (a hyphenation
    point) of width hyphen_width and cost hyphen_penalty. Between two words
    it puts the glue space. With finish, it adds the ending of TeX:
    Penalty(0, INF_PENALTY), Glue(0, 1, 0, FIL) (the parfillskip) and
    Penalty(0, -INF_PENALTY).
    """
    items: list[Item] = []
    for k, word in enumerate(words):
        if k > 0:
            items.append(space)
        pieces = word if isinstance(word, (list, tuple)) else [word]
        for t, piece in enumerate(pieces):
            if t > 0:
                items.append(Penalty(hyphen_width, hyphen_penalty, True))
            items.append(_box(piece))
    if finish:
        items.append(Penalty(0, INF_PENALTY))
        items.append(Glue(0, 1, 0, stretch_order=FIL))
        items.append(Penalty(0, -INF_PENALTY))
    return items


class Measures:
    """Prefix sums over an item list, and the measures of a line in O(1).

    With vertical=True the size of a box is its height plus its depth and a
    penalty has no size, a simple model of a vertical list. The page builder
    of TeX treats the depth of the last box apart; a page that needs this
    must correct for it.
    """

    def __init__(self, items: Sequence[Item], vertical: bool = False) -> None:
        m = len(items)
        self.items = list(items)
        self.vertical = vertical
        self.W: list[Number] = [0] * (m + 1)
        self.Y: list[list[Number]] = [[0] * (m + 1) for _ in range(ORDERS)]
        self.Z: list[list[Number]] = [[0] * (m + 1) for _ in range(ORDERS)]
        for i, x in enumerate(self.items):
            dw: Number = 0
            for o in range(ORDERS):
                self.Y[o][i + 1] = self.Y[o][i]
                self.Z[o][i + 1] = self.Z[o][i]
            if isinstance(x, Box):
                dw = x.height + x.depth if vertical else x.width
            elif isinstance(x, Glue):
                dw = x.width
                self.Y[x.stretch_order][i + 1] += x.stretch
                self.Z[x.shrink_order][i + 1] += x.shrink
            self.W[i + 1] = self.W[i] + dw
        # next_box[i]: the least index >= i that holds a box, or m
        self.next_box = [m] * (m + 1)
        for i in range(m - 1, -1, -1):
            self.next_box[i] = i if isinstance(self.items[i], Box) else self.next_box[i + 1]

    def start(self, a: int, b: int) -> int:
        """The index of the first item of the line from break a to break b."""
        if a < 0:
            return 0
        return min(self.next_box[a + 1], b)

    def line(self, a: int, b: int) -> tuple[Number, tuple, tuple]:
        """(L, Y, Z) of the line from break a to break b, with a < b.

        L is the natural width, Y and Z are the total stretch and shrink,
        one entry per glue order.
        """
        s = self.start(a, b)
        L = self.W[b] - self.W[s]
        x = self.items[b]
        if isinstance(x, Penalty) and not self.vertical:
            L += x.width
        Y = tuple(self.Y[o][b] - self.Y[o][s] for o in range(ORDERS))
        Z = tuple(self.Z[o][b] - self.Z[o][s] for o in range(ORDERS))
        return L, Y, Z


def _orders(v) -> tuple:
    if isinstance(v, tuple):
        return v + (0,) * (ORDERS - len(v))
    return (v,) + (0,) * (ORDERS - 1)


def adjustment_ratio(l: Number, L: Number, Y, Z) -> tuple:
    """(r, order) for a line of natural width L set to the length l.

    Y and Z are numbers (normal order only) or tuples by order. The ratio
    uses the highest order with a nonzero total. r is a Fraction, or
    math.inf when the line must stretch and cannot, or -math.inf when it
    must shrink and cannot.
    """
    Yo, Zo = _orders(Y), _orders(Z)
    if L == l:
        return Fraction(0), NORMAL
    tot = Yo if L < l else Zo
    for o in range(ORDERS - 1, -1, -1):
        if tot[o] != 0:
            return Fraction(l - L) / Fraction(tot[o]), o
    return (math.inf if L < l else -math.inf), NORMAL


def is_overfull(r, order: int = NORMAL) -> bool:
    """True when the glue must shrink more than its shrinkability."""
    return order == NORMAL and r < -1


def badness(r, order: int = NORMAL):
    """The real badness min(100 |r|^3, 10000) of Knuth and Plass, exact.

    Glue of infinite order gives 0. An overfull line (r < -1) gives
    math.inf, so that it loses to every legal line. A line that cannot
    stretch (r = math.inf) gives 10000.
    """
    if order != NORMAL:
        return Fraction(0)
    if r < -1:
        return math.inf
    if r == math.inf:
        return Fraction(INF_BAD)
    return min(100 * abs(Fraction(r)) ** 3, Fraction(INF_BAD))


def tex_badness(t: int, s: int) -> int:
    """The integer badness(t, s) of TeX: The Program, section 108.

    t >= 0 is the amount to stretch or shrink and s the total stretch or
    shrink, both in scaled points (integers). The value is about
    100 (t/s)^3, and 10000 stands for infinitely bad.
    """
    if t < 0:
        raise ValueError("t must be >= 0")
    if t == 0:
        return 0
    if s <= 0:
        return INF_BAD
    if t <= 7230584:
        r = (t * 297) // s  # 297^3 = 99.94 * 2^18
    elif s >= 1663497:
        r = t // (s // 297)
    else:
        r = t
    if r > 1290:  # 1290^3 < 2^31 < 1291^3
        return INF_BAD
    return (r * r * r + 0o400000) // 0o1000000  # r^3 / 2^18, rounded


def tex_line_badness(l: int, L: int, Y, Z) -> int:
    """The badness that the line breaker of TeX gives a line (sections 852 and 853).

    Integer widths only. A line that needs stretch and has stretch of an
    infinite order gets 0. An overfull line gets INF_BAD + 1. Infinite
    shrink, which TeX reports as an error in a paragraph, gives 0 here.
    """
    Yo, Zo = _orders(Y), _orders(Z)
    shortfall = l - L
    if shortfall > 0:
        if any(Yo[1:]):
            return 0
        return tex_badness(shortfall, Yo[0])
    if shortfall < 0:
        if any(Zo[1:]):
            return 0
        if -shortfall > Zo[0]:
            return INF_BAD + 1
        return tex_badness(-shortfall, Zo[0])
    return 0


def all_breakings(items: Sequence[Item]) -> Iterator[tuple[int, ...]]:
    """Yield every breaking of the paragraph, for tiny paragraphs only.

    A breaking is a tuple b_1 < ... < b_k of legal breaks with b_k = m - 1
    that holds every forced break. The last item must be a forced penalty.
    There are 2^q breakings for q optional breakpoints.
    """
    m = len(items)
    if m == 0 or not is_forced(items[-1]):
        raise ValueError("the last item must be a forced penalty")
    legal = legal_breakpoints(items)
    optional = [b for b in legal if b != m - 1 and not is_forced(items[b])]
    forced = [b for b in legal if b == m - 1 or is_forced(items[b])]
    for choice in product((False, True), repeat=len(optional)):
        chosen = [b for b, c in zip(optional, choice) if c]
        yield tuple(sorted(chosen + forced))


def render(items: Sequence[Item], breaks: Sequence[int]) -> list[str]:
    """The text of each line of a breaking, for examples.

    A box shows its text (or 'x' repeated by its integer width), a glue of
    positive width shows one space, and a flagged penalty at a break shows
    '-'. Trailing spaces are removed.
    """
    meas = Measures(items)
    out: list[str] = []
    a = -1
    for b in breaks:
        parts: list[str] = []
        for x in items[meas.start(a, b) : b]:
            if isinstance(x, Box):
                if x.text:
                    parts.append(x.text)
                else:
                    parts.append("x" * x.width if isinstance(x.width, int) else "x")
            elif isinstance(x, Glue) and x.width > 0:
                parts.append(" ")
        x = items[b]
        if isinstance(x, Penalty) and x.flagged and not is_forced(x):
            parts.append("-")
        out.append("".join(parts).rstrip())
        a = b
    return out
test_best_fit_page_breaking.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/best-fit-page-breaking/. The authors are listed in prov/81895S.jsonl.

import math
import random

from boxglue import FILL, INF_PENALTY, Box, Glue, Penalty, all_breakings, is_forced, is_legal_break, tex_badness
from best_fit_page_breaking import (
    AWFUL_BAD,
    DEPLORABLE,
    Page,
    break_cost,
    breaking_cost,
    lines,
    optimal_breaking,
    page_badness,
    page_builder,
)


def simulate(items, goal, max_depth=None):
    """The page builder item by item, with running totals as in TeX, no prefix sums."""
    m = len(items)
    breaks, costs = [], []
    a = -1
    while True:
        i = a + 1
        while i < m and not isinstance(items[i], Box):
            i += 1  # glue, kerns and penalties at the top of a page are discarded
        if i >= m:
            return breaks, costs
        total, depth = 0, 0
        stretch, shrink = [0, 0, 0, 0], 0
        least, best = AWFUL_BAD, None
        for k in range(i, m):
            x = items[k]
            if k > i and is_legal_break(items, k):
                p = x.penalty if isinstance(x, Penalty) else 0
                c = break_cost(page_badness(total, tuple(stretch), shrink, goal), p)
                if c <= least:
                    least, best = c, k
                if c == AWFUL_BAD or p <= -INF_PENALTY:
                    break
            if isinstance(x, Box):
                total += depth + x.height
                depth = x.depth
                if max_depth is not None and depth > max_depth:
                    total += depth - max_depth
                    depth = max_depth
            elif isinstance(x, Glue):
                total += depth + x.width
                depth = 0
                stretch[x.stretch_order] += x.stretch
                shrink += x.shrink
        breaks.append(best)
        costs.append(least)
        a = best


def random_list(rng, n):
    items = []
    for i in range(n):
        if i > 0:
            if rng.random() < 0.3:
                items.append(Penalty(0, rng.choice([-200, 50, 150, 300, INF_PENALTY])))
            items.append(Glue(rng.randint(0, 3), rng.randint(0, 4), rng.randint(0, 2)))
        items.append(Box(0, rng.randint(5, 15), rng.randint(0, 3)))
    items.append(Glue(0, 1, 0, stretch_order=FILL))
    items.append(Penalty(0, -INF_PENALTY))
    return items


def test_break_cost_rules():
    assert break_cost(50, 100) == 150
    assert break_cost(20, -500) == -480
    assert break_cost(0, 0) == 0
    assert break_cost(10000, 0) == DEPLORABLE
    assert break_cost(10000, -INF_PENALTY) == -INF_PENALTY
    assert break_cost(37, -INF_PENALTY) == -INF_PENALTY
    assert break_cost(AWFUL_BAD, 0) == AWFUL_BAD
    assert break_cost(AWFUL_BAD, -INF_PENALTY) == AWFUL_BAD
    assert break_cost(50, 100, 25) == 175
    assert break_cost(50, 100, INF_PENALTY) == AWFUL_BAD


def test_page_badness_rules():
    assert page_badness(22, (8, 0, 0, 0), 0, 44) == tex_badness(22, 8)
    assert page_badness(22, (8, 1, 0, 0), 0, 44) == 0
    assert page_badness(44, (0, 0, 0, 0), 0, 44) == 0
    assert page_badness(20, (0, 0, 0, 0), 5, 44) == 10000
    assert page_badness(46, (0, 0, 0, 0), 3, 44) == tex_badness(2, 3)
    assert page_badness(48, (9, 9, 0, 0), 3, 44) == AWFUL_BAD


def test_example_of_the_page():
    # four lines of height 10 and two of height 20, glue 2 plus 8 minus 1, page goal 44
    items = lines([10, 10, 10, 10, 20, 20], Glue(2, 8, 1))
    assert page_badness(34, (16, 0, 0, 0), 2, 44) == 24
    assert page_badness(46, (24, 0, 0, 0), 3, 44) == 30
    assert page_badness(32, (8, 0, 0, 0), 1, 44) == 336
    breaks, costs = page_builder(items, 44)
    assert breaks == [5, 9, 12]
    assert costs == [24, 336, -INF_PENALTY]
    assert breaking_cost(items, breaks, 44) == 360
    assert optimal_breaking(items, 44) == (30, (7, 12))


def test_a_later_break_wins_a_tie():
    items = [Box(0, 10), Glue(2), Box(0, 10), Glue(0), Penalty(0, 0), Box(0, 10), Glue(0, 1, 0, stretch_order=FILL), Penalty(0, -INF_PENALTY)]
    breaks, costs = page_builder(items, 22)
    assert breaks == [4, 7]
    assert costs == [0, -INF_PENALTY]


def test_discards_at_the_top_of_a_page():
    items = [Box(0, 10), Glue(2), Box(0, 10), Penalty(0, -INF_PENALTY), Glue(5), Penalty(0, 50), Glue(7), Box(0, 10), Glue(0, 1, 0, stretch_order=FILL), Penalty(0, -INF_PENALTY)]
    pg = Page(items)
    assert pg.first_box(3) == 7
    assert pg.total(7, 8)[0] == 10
    breaks, costs = page_builder(items, 22)
    assert breaks == [3, 9]
    assert costs == [-INF_PENALTY, -INF_PENALTY]


def test_depth_of_the_last_box():
    items = [Box(0, 8, 3), Glue(2), Box(0, 8, 3), Glue(0, 1, 0, stretch_order=FILL), Penalty(0, -INF_PENALTY)]
    assert Page(items).total(0, 3)[0] == 21
    assert Page(items).total(0, 4)[0] == 24
    assert Page(items, max_depth=1).total(0, 3)[0] == 23
    assert Page(items, max_depth=5).total(0, 3)[0] == 21


def test_overfull_page_is_taken_when_nothing_fits():
    items = lines([30, 10], Glue(2))
    breaks, costs = page_builder(items, 20)
    assert breaks == [1, 4]
    assert costs[0] == AWFUL_BAD
    assert breaking_cost(items, breaks, 20) == AWFUL_BAD


def test_infinite_shrink_is_rejected():
    items = [Box(0, 10), Glue(2, 0, 1, shrink_order=FILL), Box(0, 10), Penalty(0, -INF_PENALTY)]
    try:
        page_builder(items, 20)
    except ValueError:
        return
    raise AssertionError("infinite shrink was accepted")


def test_builder_against_item_by_item_simulation():
    rng = random.Random(1)
    for _ in range(400):
        items = random_list(rng, rng.randint(1, 12))
        goal = rng.randint(15, 60)
        md = rng.choice([None, 0, 1, 2])
        assert page_builder(items, goal, md) == simulate(items, goal, md)


def test_builder_never_beats_the_optimum_and_is_a_breaking():
    rng = random.Random(2)
    worse = 0
    for _ in range(300):
        items = random_list(rng, rng.randint(1, 7))
        goal = rng.randint(15, 50)
        breaks, _ = page_builder(items, goal)
        gc = breaking_cost(items, breaks, goal)
        oc, ob = optimal_breaking(items, goal)
        if gc == AWFUL_BAD:
            continue
        full = set(all_breakings(items))
        assert tuple(breaks) in full or tuple(breaks) + (len(items) - 1,) in full
        assert all(is_legal_break(items, b) for b in breaks)
        assert oc <= gc
        worse += oc < gc
    assert worse > 0


def test_forced_breaks_are_always_taken():
    rng = random.Random(4)
    for _ in range(200):
        items = random_list(rng, rng.randint(1, 10))
        k = rng.randrange(len(items) - 1)
        if isinstance(items[k], Glue) and k > 0 and isinstance(items[k - 1], Box):
            items[k] = Penalty(0, -INF_PENALTY)
        breaks, _ = page_builder(items, rng.randint(15, 60))
        tops = [-1] + breaks
        for b, x in enumerate(items):
            if is_forced(x):
                # either the page ends there, or the penalty is at the top of a page and is discarded
                a = max(t for t in tops if t < b)
                assert b in breaks or not any(isinstance(y, Box) for y in items[a + 1 : b])


def test_number_of_tests_per_page_is_bounded():
    rng = random.Random(5)
    h, goal = 10, 120
    items = lines([h] * 3000, Glue(2, 3, 0), [rng.choice([0, 0, 150]) for _ in range(2999)])
    stats = {}
    breaks, costs = page_builder(items, goal, stats=stats)
    assert all(c < AWFUL_BAD for c in costs)
    assert stats["tests"] <= len(breaks) * (goal // h + 2)
    assert not math.isinf(breaking_cost(items, breaks, goal))

History

Knuth wrote the page builder for TeX and described its cost of a page break in The TeXbook in 1984, and its full code is in TeX, The Program of 1986. The method keeps only the current page in memory, so TeX can ship out each page before it reads the rest of the document. At about the same time, his student Michael Plass studied the optimal version of the problem with figures in his Stanford thesis of 1981, which led to optimal pagination and to the hardness results.

References

  1. Donald E. Knuth, The TeXbook, Addison-Wesley, 1984, chapter 15, How TeX makes lines into pages: the page goal, the cost of a page break and the choice of the best break so far
  2. Donald E. Knuth, TeX, The Program, Addison-Wesley, 1986, part 45, The page builder

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/81895S/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