Algorithmadvanced
Hyphenation pattern generation
Also called patgen.
Learn hyphenation patterns from a hyphenated word list in levels, greedily keeping patterns whose good matches outweigh bad ones at each level.
- Solves
- Hyphenation
- Time
- O(P N L^2) worst
- Space
- O(N L + Q) extra
- Where
- L = the length of the longest pattern; N = the total number of letters of the word list; P = the number of passes; Q = the total length of the patterns
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Franklin Mark Liang, 1983
Hyphenation pattern generation learns the patterns of Liang's hyphenation from a list of words with their hyphens marked. It works in levels. Odd levels add patterns that allow hyphens, and even levels add patterns that forbid them, each one able to overrule the levels below it. Inside a level, it tries all strings of a given length with the digit at a given gap, counts on how many gaps of the list each one would help and hurt, and keeps the strings whose weighted score reaches a threshold. Franklin Liang wrote it as the program patgen in 1983, and it made the English patterns of TeX82.
In plain words
Suppose you want short rules such as "put a hyphen before ti" that explain a hyphenated word list. Start with no rules. Look at every gap of every word where the rules are still wrong. For each short piece of letters around such a gap, count how often a new rule on that piece would fix a gap and how often it would break one. Keep the pieces that fix much more than they break.
The first rules are too general and make some wrong hyphens. So the next level looks for rules that forbid hyphens, and only where the current rules are wrong. Then a third level allows hyphens again, and so on. Each level fixes some of the errors of the level below, which is how a short list of patterns can describe a long list of words.
The problem
The input is a list of words with their sets of correct hyphen positions, and for each level the parameters (the good weight), (the bad weight), (the threshold) and a range of pattern lengths. The limits and select the counted gaps: a gap of a word of letters is counted when and . The output is a set of patterns, each a string of letters (with "." for a word edge) and a digit for each gap. The aim is a small set whose values, by Liang's rule, are odd on the correct hyphens and even elsewhere, for as many counted gaps as possible. It is a method for building a solution of the hyphenation problem; it does not promise the smallest set or the best one.
At level , with the patterns chosen so far, call a counted gap now if its value under is odd. Then:
- at an odd level, a gap is good if it is a correct hyphen and not now, and bad if it is not a correct hyphen and not now;
- at an even level, a gap is good if it is not a correct hyphen but now, and bad if it is a correct hyphen and now.
A string with the dot at its gap is kept when , where the counts are over the gaps where occurs with its gap on them.
The algorithm
GENERATE(list, levels)G1 Π ← the empty set of patternsG2 for each level ℓ = 1, 2, ... with parameters (γ, δ, θ, kmin, kmax) doG3 for k ← kmin to kmax doG4 for d ← 0 to k do ▷ one pass for each dot positionG5 good[·] ← 0; bad[·] ← 0G6 for each word w of the list doG7 v ← the gap values of w under Π, by Liang's ruleG8 for each counted gap g of w that is good or bad at level ℓ doG9 q ← the k letters of .w. that have their gap d on gG10 add 1 to good[q] or to bad[q]G11 for each string q with a count doG12 if γ · good[q] - δ · bad[q] ≥ θ thenG13 put the digit ℓ at gap d of q in Π (keep the larger digit)G14 return Π
Line G7 hyphenates each word with the patterns chosen so far, so every pass sees the effect of all earlier passes, also those of the same level. Line G9 finds the one string of length that has its gap on the gap ; near the edges of the word, the string may contain a "." and there may be no such string. Lines G11 to G13 run after all words are counted, so the patterns of a pass do not change its own counts. A pattern of length takes passes, one for each position of its digit.
Example
The word list for this example has 32 English words made up for the page (the tests of this page use it), with 38 correct hyphens, for example hy-phen-ation, com-put-er, mon-ster and ta-ble. The limits are . The three levels are:
| level | lengths | passes | patterns kept | found | errors | missed | |||
|---|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 1 | 2 | 2 to 3 | 7 | 7 | 27 | 3 | 11 |
| 2 | 1 | 2 | 1 | 2 to 4 | 12 | 3 | 27 | 0 | 11 |
| 3 | 1 | 100 | 1 | 2 to 8 | 42 | 11 | 38 | 0 | 0 |
Level 1. In the first pass (, , so the hyphen goes before the two letters), "te" sits after 11 good gaps and 2 bad ones, so its score is and 1te is kept. "ti" scores . "er" is after 1 good gap and 15 bad ones, so it is rejected. The length-2 passes keep 1be, 1bl, 1ce, 1te, 1ti, n1a and n1s, and the length-3 passes add nothing. These seven patterns find 27 of the 38 hyphens but make 3 errors: hyphen-a-tion (the hyphen before "tion" is wrong), compu-ter and mon-s-ter.
Level 2. Now the good gaps are the 3 errors. The level keeps ena2, u2t and n1s2 (the digit 2 is added to the existing pattern n1s), which remove all three errors and keep the 27 correct hyphens.
Level 3. The bad weight is 100, so a pattern is kept only if it makes no wrong hyphen. The level adds 3co, 3de, 3gi, 3go, 3gr, 3ph, 3pu, r3e, 3ri, 3va and a 3 at the end of u2t, which gives u2t3. Now com-put-er gets its hyphen before "p" from 3pu and after "t" from u2t3. The final 19 patterns hyphenate all 38 gaps of the list correctly, and give no wrong hyphen. On words outside the list they can be wrong: the list is far too small for real use.
Correctness
The claim is that each pass keeps exactly the strings that meet the rule of line G12 for the counts of the claim, under the patterns from before the pass. Line G7 computes the values by Liang's rule, so "now" is right. Line G8 sees each counted gap once, and a gap cannot be both good and bad. For a gap and a dot , the only string of length with its gap on starts at position of "..", so line G10 adds each good or bad gap to exactly one count. Lines G11 to G13 then apply the rule, and adding a digit by the maximum is the same as having two patterns, because Liang's rule takes the maximum. Each pass reads the list once, so the method stops after passes. The full proof is in the proof file.
This is correctness of the procedure, not of its result. The rule is a heuristic, and whether the final patterns are right on the whole list depends on the parameters.
Proof: Each pass keeps exactly the candidates that meet the selection rulefull
Claim. Run GENERATE (lines G1 to G14) on a list of hyphenated words and a list of levels. Fix a level with parameters (good weight, bad weight, threshold), a length and a dot position . Let be the patterns before this pass, and for a gap of a word let "now" mean that the value of under by Liang's rule is odd. Call a counted gap of a word good if it is a correct hyphen and not now (odd ), or not a correct hyphen and now (even ); call it bad if it is not a correct hyphen and not now (odd ), or a correct hyphen and now (even ). For a string of letters, let and be the number of good and bad counted gaps of the words such that occurs in the word with "." at both ends with its gap at . Then the pass adds the value at the gap of exactly for the strings with and , and for no other gap or string. (When , as in every level of patgen, the first condition follows from the second.) The run stops after passes.
Setup. A word of letters gives of letters. Gap of (before ) is gap of . A string of letters that starts at position of has its gap at gap of , which is gap of . So the occurrence of with its gap at gap of , if it exists, is the one at , and it exists exactly when , and . For each gap there is at most one such string.
Step 1 (the values are right). Line G7 computes the gap values of under . The function gap_values is Liang's rule written out: for each start of and each length of a pattern, it looks up the substring of that length at and raises the covered gaps to the values of the pattern. This is the definition of the value of a gap, the maximum over all patterns that cover it, as proved on the page on Liang's method. The test test_final_patterns_find_every_hyphen_and_no_bad_hyphen also checks it against a brute force. So "now" in line G8 is the "now" of the claim. The patterns of this pass are not used in this computation: line G13 adds them only after all words are counted (lines G11 to G13 come after the loop of line G6), so every gap is judged under alone.
Step 2 (the counts are right). Line G8 visits each counted gap of each word once. The two tests before the count give exactly the good and the bad of the claim, and a gap cannot be both, because the two conditions differ in "correct hyphen" (odd ) or in "now" (even ). A gap that is neither is skipped. By the setup, line G9 takes the only string of letters that has its gap at , or none when it would run past the marks. Line G10 adds one to the good or to the bad count of that . So after the loop of line G6, for every with a nonzero count, and the strings that are not in the dict have both counts 0.
Step 3 (the selection). By Step 2 the dict holds exactly the strings with , and lines G11 to G13 add the value at gap of exactly for those with . The function add_pattern stores the larger of the old and the new value at the gap , which is the value of the merged pattern by Liang's rule, since the maximum over the patterns is what counts. It changes no other gap.
Termination and the number of passes. Each level runs the lengths (line G3) and the dots of each length (line G4), and each pass reads each counted gap of each word once, so it stops. This gives passes per level, the number Liang gives for patgen and the one the test checks.
What the proof does not say. The rule is a heuristic. A level can add a pattern that makes a wrong hyphen elsewhere, and the next level of the other parity may or may not remove it. The claim is only that the program does what the rule says; whether the final patterns hyphenate every word of the list correctly depends on the parameters, as the tests of the page show.
Complexity
Let be the number of letters of the list and the number of passes. One pass computes the gap values of each word, which takes for a word of letters with a lookup of each substring of length at most , and it counts each gap once. So a pass takes , and the run takes time. Space is for the counts of one pass, plus the patterns. With a trie of the patterns, as in patgen, the values cost per word instead.
Liang's TeX82 run took 109 passes and about one hour of computer time (his measurement on a 1983 machine).
Properties
- Greedy. Each pass keeps every string that meets the rule, and never takes a pattern back. A later level can only overrule it with a larger digit.
- Levels alternate. Odd levels only add hyphens and even levels only remove them, because a digit is odd exactly at odd levels and is larger than all earlier digits.
- Order dependent. The result depends on the order of the levels, the lengths and the dot positions, because each pass sees the patterns of the passes before it.
- Trade-off by weights. A high bad weight gives safe patterns that miss hyphens; a high good weight gives patterns that find more hyphens with more errors.
Variants and improvements
- Liang's parameters for TeX82. Liang used five levels, with good weight, bad weight and threshold 1, 2, 20 (level 1), 2, 1, 8 (level 2), 1, 4, 7 (level 3), 3, 2, 1 (level 4) and 1, infinity, 4 (level 5), and pattern lengths of up to 4, 4, 5, 6 and 8. The levels kept 458, 509, 985, 1647 and 1320 patterns: 4919 in all, of which 4447 are distinct strings. They pack into a packed trie of 5943 locations with 181 different digit lists, and find 89.3 percent of the hyphens of his list. These are his measurements on that list.
- Counting in a trie. patgen keeps the patterns and the candidate counts in a dynamic packed trie, not in a hash map, to save memory on a large list.
- Skipping useless candidates. A string that already has a digit of at least at gap cannot change anything at level , so an implementation can drop it before it counts.
- Exceptions. Words that the patterns still get wrong go into an exception list, as \hyphenation in TeX.
- Weighted lists. A word can count more than once, for example by its frequency in a body of text, so that common words get more weight.
When to use it
Use it to make a pattern set for a language from a hyphenated word list, when the patterns will be used by Liang's method, as in TeX and many word processors. The list must be large and correct, because the patterns learn its errors too. If only a fixed set of words is ever hyphenated, a lookup in the list itself is simpler and exact.
Pitfalls
- Overfitting. With a bad weight of 100 and long patterns, the last levels can learn single words, as in the example. The patterns are then exact on the list and no better than chance on new words. Test them on words that were not in the list.
- Counting with the new patterns. If line G13 adds patterns during the counting loop, the counts of the same pass change while they are being made, and the result depends on the order of the words.
- Forgetting the edges. Without the "." marks, no pattern can depend on the start or the end of a word, and the method misses rules such as "no hyphen after the first letter".
- Different limits. The counted gaps of line G8 must use the same and as the typesetter, or the counts include gaps that are never used.
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/hyphenation-pattern-generation/. The authors are listed in prov/980NJ6.jsonl.
"""Hyphenation pattern generation in the manner of Liang's patgen.
The input is a list of words with their correct hyphen positions. The
output is a set of patterns for Liang's rule (the largest digit at each gap
wins, odd allows a hyphen, even forbids it).
Patterns are chosen one level at a time. Odd levels add hyphenating
patterns, even levels add inhibiting patterns. Inside a level, the patterns
of each length are chosen in separate passes, one pass for each position of
the gap (the "dot") inside the pattern, so a pattern of length k takes k + 1
passes. Each pass hyphenates the whole word list with the patterns chosen so
far, and counts, for each candidate, the gaps where it would help (good) and
where it would hurt (bad):
- at an odd level, good is a correct hyphen that is not found yet, and bad
is a gap with no hyphen that is not hyphenated now;
- at an even level, good is a wrong hyphen that the patterns now give, and
bad is a correct hyphen that they find now.
A candidate is kept when good_wt * good - bad_wt * bad >= thresh, the rule
of patgen. Only the gaps at least left letters from the start and right
letters from the end are counted.
This version keeps the counting simple: it counts every candidate in a
dict. patgen counts in a packed trie and drops hopeless candidates early.
"""
from dataclasses import dataclass
from typing import Dict, List, Sequence, Tuple
Patterns = Dict[str, List[int]] # letters -> gap values, as in parse_pattern
@dataclass(frozen=True)
class Level:
"""The parameters of one level: weights, threshold, pattern lengths."""
good_wt: int
bad_wt: int
thresh: int
min_len: int
max_len: int
@dataclass
class LevelReport:
level: int
patterns: int # patterns chosen at this level
passes: int
found: int # correct hyphens found after the level
errors: int # wrong hyphens after the level
missed: int # correct hyphens not found after the level
def parse_hyphenated(entry: str) -> Tuple[str, frozenset]:
"""'hy-phen-ation' -> ('hyphenation', {2, 6}): k means a hyphen before word[k]."""
word, pos, k = [], set(), 0
for ch in entry:
if ch == "-":
pos.add(k)
else:
word.append(ch)
k += 1
return "".join(word), frozenset(pos)
def gap_values(word: str, patterns: Patterns) -> List[int]:
"""Liang's rule: v[k] is the value of the gap before word[k], k = 0 .. len(word)."""
w = "." + word + "."
v = [0] * (len(w) + 1)
lengths = sorted({len(p) for p in patterns})
for i in range(len(w)):
for k in lengths:
if i + k > len(w):
break
vals = patterns.get(w[i : i + k])
if vals is not None:
for t, d in enumerate(vals):
if d > v[i + t]:
v[i + t] = d
return v[1 : len(word) + 2]
def counted_gaps(n: int, left: int, right: int) -> range:
return range(max(1, left), n - max(1, right) + 1)
def hyphens(word: str, patterns: Patterns, left: int, right: int) -> set:
v = gap_values(word, patterns)
return {k for k in counted_gaps(len(word), left, right) if v[k] % 2 == 1}
def add_pattern(patterns: Patterns, letters: str, dot: int, value: int) -> None:
vals = patterns.setdefault(letters, [0] * (len(letters) + 1))
vals[dot] = max(vals[dot], value)
def generate(
entries: Sequence[str],
levels: Sequence[Level],
left: int = 2,
right: int = 2,
) -> Tuple[Patterns, List[LevelReport]]:
"""Generate patterns from hyphenated words, level by level."""
words = [parse_hyphenated(e.lower()) for e in entries]
patterns: Patterns = {} # @line G1
reports: List[LevelReport] = []
for lev, par in enumerate(levels, start=1): # @line G2
odd = lev % 2 == 1
chosen = 0
passes = 0
for k in range(par.min_len, par.max_len + 1): # @line G3
for dot in range(k + 1): # @line G4
passes += 1
count: Dict[str, List[int]] = {} # @line G5
for word, true in words: # @line G6
v = gap_values(word, patterns) # @line G7
w = "." + word + "."
for g in counted_gaps(len(word), left, right): # @line G8
is_hyphen, now = g in true, v[g] % 2 == 1
if odd:
good, bad = is_hyphen and not now, (not is_hyphen) and not now
else:
good, bad = (not is_hyphen) and now, is_hyphen and now
if not (good or bad):
continue
start = g + 1 - dot # gap g of the word is gap g + 1 of w
if start < 0 or start + k > len(w):
continue
letters = w[start : start + k] # @line G9
c = count.setdefault(letters, [0, 0])
c[0 if good else 1] += 1 # @line G10
for letters, (good, bad) in sorted(count.items()): # @line G11
if par.good_wt * good - par.bad_wt * bad >= par.thresh: # @line G12
add_pattern(patterns, letters, dot, lev) # @line G13
chosen += 1
found = errors = missed = 0
for word, true in words:
h = hyphens(word, patterns, left, right)
t = {g for g in true if g in counted_gaps(len(word), left, right)}
found += len(h & t)
errors += len(h - t)
missed += len(t - h)
reports.append(LevelReport(lev, chosen, passes, found, errors, missed))
return patterns, reports # @line G14
def pattern_strings(patterns: Patterns) -> List[str]:
"""The patterns in the usual notation, for example 'hy3ph'."""
out = []
for letters, vals in sorted(patterns.items()):
s = []
for t, ch in enumerate(letters):
if vals[t]:
s.append(str(vals[t]))
s.append(ch)
if vals[len(letters)]:
s.append(str(vals[len(letters)]))
out.append("".join(s))
return out
test_hyphenation_pattern_generation.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hyphenation-pattern-generation/. The authors are listed in prov/980NJ6.jsonl.
import random
from hyphenation_pattern_generation import (
Level,
counted_gaps,
gap_values,
generate,
hyphens,
parse_hyphenated,
pattern_strings,
)
# A word list made up for this test. The hyphens were marked by hand in the
# American style; they are not copied from any dictionary.
WORDS = """hy-phen-ation com-put-er al-go-rithm pat-tern pat-terns let-ter let-ters mat-ter
but-ter bet-ter lad-der num-ber num-bers ta-ble ca-ble sta-tion na-tion ac-tion mo-tion
frac-tion dic-tion-ary pro-gram pro-cess in-ter-est in-ter-val win-ter sis-ter mon-ster
con-stant con-cept be-gin be-come""".split()
# (good_wt, bad_wt, thresh, shortest, longest): hyphenate, inhibit, then safe hyphenating patterns
LEVELS = [Level(1, 1, 2, 2, 3), Level(1, 2, 1, 2, 4), Level(1, 100, 1, 2, 8)]
def brute_force_values(word, patterns):
w = "." + word + "."
v = [0] * (len(w) + 1)
for letters, vals in patterns.items():
for i in range(len(w) - len(letters) + 1):
if w[i : i + len(letters)] == letters:
for t, d in enumerate(vals):
v[i + t] = max(v[i + t], d)
return v[1 : len(word) + 2]
def test_parse_hyphenated():
assert parse_hyphenated("hy-phen-ation") == ("hyphenation", frozenset({2, 6}))
assert parse_hyphenated("ta-ble") == ("table", frozenset({2}))
def test_levels_counts():
pats, rep = generate(WORDS, LEVELS)
assert len(WORDS) == 32
got = [(r.level, r.patterns, r.passes, r.found, r.errors, r.missed) for r in rep]
assert got == [
(1, 7, 7, 27, 3, 11),
(2, 3, 12, 27, 0, 11),
(3, 11, 42, 38, 0, 0),
]
# a pattern of length k takes k + 1 passes: lengths 2..3 give 3 + 4 = 7 passes
assert [r.passes for r in rep] == [sum(k + 1 for k in range(L.min_len, L.max_len + 1)) for L in LEVELS]
def test_patterns_of_each_level():
p1, _ = generate(WORDS, LEVELS[:1])
assert pattern_strings(p1) == ["1be", "1bl", "1ce", "n1a", "n1s", "1te", "1ti"]
p2, _ = generate(WORDS, LEVELS[:2])
assert pattern_strings(p2) == ["1be", "1bl", "1ce", "ena2", "n1a", "n1s2", "1te", "1ti", "u2t"]
def test_final_patterns_find_every_hyphen_and_no_bad_hyphen():
pats, _ = generate(WORDS, LEVELS)
for e in WORDS:
w, true = parse_hyphenated(e)
assert hyphens(w, pats, 2, 2) == {g for g in true if g in counted_gaps(len(w), 2, 2)}
assert gap_values(w, pats) == brute_force_values(w, pats)
def test_first_pass_follows_the_selection_rule():
# length 2, dot 0, level 1, no earlier patterns: count by brute force
words = [parse_hyphenated(e) for e in WORDS]
good, bad = {}, {}
for w, true in words:
s = "." + w + "."
for g in counted_gaps(len(w), 2, 2):
letters = s[g + 1 : g + 3]
d = good if g in true else bad
d[letters] = d.get(letters, 0) + 1
want = sorted(x for x in set(good) | set(bad) if good.get(x, 0) - bad.get(x, 0) >= 2)
pats, _ = generate(WORDS, [Level(1, 1, 2, 2, 2)])
first_pass = sorted(x for x, v in pats.items() if v[0] == 1)
assert first_pass == want
assert want == ["be", "bl", "ce", "te", "ti"]
assert (good["te"], bad["te"]) == (11, 2) and (good["ti"], bad["ti"]) == (6, 1)
assert (good.get("er", 0), bad["er"]) == (1, 15)
def test_random_lists_with_enough_levels_are_learned_exactly():
rng = random.Random(31)
for _ in range(10):
entries = set()
while len(entries) < 12:
k = rng.randint(4, 8)
w = "".join(rng.choice("abcde") for _ in range(k))
pos = sorted(rng.sample(range(2, k - 1), rng.randint(0, min(2, k - 3)))) if k > 4 else []
e = "".join(("-" if i in pos else "") + c for i, c in enumerate(w))
if w not in {parse_hyphenated(x)[0] for x in entries}:
entries.add(e)
entries = sorted(entries)
levels = [Level(1, 1, 2, 2, 3), Level(1, 1, 1, 2, 4), Level(1, 100, 1, 2, 10), Level(1, 100, 1, 2, 10)]
pats, rep = generate(entries, levels)
assert rep[-1].errors == 0 and rep[-1].missed == 0
for e in entries:
w, true = parse_hyphenated(e)
assert hyphens(w, pats, 2, 2) == set(true)
History
The first TeX used rules on letter classes for hyphenation. Liang, a student of Donald Knuth at Stanford, replaced them with patterns and wrote patgen to learn them; his thesis of 1983 describes the method and the TeX82 run on a word list based on Webster's Pocket Dictionary, with the 676 most common words fully hyphenated and over 1000 exceptions added after a test on a larger dictionary. The same program was later used to make the pattern sets of many other languages in the TeX distributions.
References
- Franklin Mark Liang, Word Hy-phen-a-tion by Com-put-er, PhD thesis, Stanford University, August 1983, report STAN-CS-83-977, Chapter 4, Pattern generation (the word list, the levels, the selection rule, the dynamic packed trie) and Table 5 (the parameters and the results for TeX82)
- Donald E. Knuth, The TeXbook, Computers and Typesetting volume A, Addison-Wesley, Appendix H, Hyphenation
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 980NJ6 Edit this page History Report an error Markdown