Algorithm Search⌘K

Algorithmadvanced

Gulwani's string transformation synthesis

Also called FlashFill algorithm.

The FlashFill method. Build a DAG over output positions with all substring and constant atoms for each example, intersect the DAGs, and pick the best-ranked path.

Time
O(m^(2k) n^k p) worst case all examplesO(m^2 n (m + p)) one example
Space
O(m^(2k) n^k p) worst case all examplesO(m^2 n p) one example
Where
k = the number of examples; m = the length of the longest output; n = the length of the longest input; p = the number of position expressions that denote one index
Properties
deterministiciterative
Origin
Sumit Gulwani, 2011

Gulwani's string transformation synthesis is the algorithm behind Flash Fill in Microsoft Excel. From one or a few examples of an input string and the wanted output, it finds a program that maps each input to its output. Programs concatenate pieces, and each piece is a constant or a substring of the input between two positions. For each example the algorithm builds a DAG over the indices of the output, where an edge holds every atom that produces that piece. It intersects the DAGs of the examples and takes the best path by a ranking. The DAGs are a version space algebra for this language; the general problem is programming by example.

In plain words

Say that "Alan Turing" must become "A. Turing". Look at each piece of the output. The "A" can be copied from the start of the input, or written as a constant. The "." cannot be copied, so it must be a constant. " Turing" can be copied from the input, from the space to the end. A position in the input can be named in more than one way: "index 4", "the last space", or "where a run of letters ends and a space starts".

The algorithm writes all these choices into one graph, without listing whole programs. With a second example, such as "Grace Hopper" to "G. Hopper", it keeps only the choices that also work there. At the end it picks a path through the graph that copies as much as it can and uses simple position names.

The problem

Input. Examples (σ1,o1),…,(σk,ok)(\sigma_1, o_1), \ldots, (\sigma_k, o_k) of input and output strings, with non-empty outputs.

Output. A program of the language below with [ ⁣[P] ⁣](σj)=oj[\![P]\!](\sigma_j) = o_j for each jj, of least cost, or "none".

The language. It is a part of the FlashFill language of Gulwani (2011), without conditionals, loops and several input columns:

  • A program is Concat(f1,…,fn)(f_1, \ldots, f_n) with n≥1n \ge 1 atoms.
  • An atom is ConstStr(c)(c) for a non-empty string cc, or SubStr(p1,p2)(p_1, p_2), the input from position p1p_1 up to position p2p_2. It is defined only when p1<p2p_1 < p_2, so every atom gives a non-empty string.
  • A position is CPos(k)(k), the index kk for k≥0k \ge 0 and the index ∣σ∣+1+k|\sigma| + 1 + k for k<0k < 0, so CPos(−1)(-1) is the end. Or it is Pos(r1,r2,c)(r_1, r_2, c): the cc-th index, from the left for c>0c > 0 and from the right for c<0c < 0, where a run of the token r1r_1 ends and a run of the token r2r_2 starts. The tokens are digits, letters, spaces, and the empty token ε\varepsilon, which matches at every index. A run is a maximal block of characters of one token. Here c∈{±1,±2,±3}c \in \{\pm 1, \pm 2, \pm 3\}, and r1r_1 and r2r_2 are not both ε\varepsilon.

Cost. The cost of a program is the tuple (number of characters in constants, number of atoms, sum of position costs), compared from left to right. CPos(0)(0) and CPos(−1)(-1) cost 1, a Pos costs 2, CPos(k)(k) with k>0k > 0 costs 3, and CPos(k)(k) with k<−1k < -1 costs 4. This prefers copying to constants, short programs, and positions that are named by structure. Gulwani (2011) uses a ranking of the same kind; this exact cost is the one in the code on this page.

The algorithm

  1. SYNTHESIZE((σ1, o1), …, (σk, ok))
  2. 1for j = 1 … k do Wj ← DAG(σj, oj)
  3. 2start ← (0, …, 0); goal ← (|o1|, …, |ok|)
  4. 3for each state u reachable from start, in increasing order of u1 + … + uk do
  5. 4for each w with uj < wj ≤ |oj| for every j do
  6. 5A ← W1(u1, w1) ∩ … ∩ Wk(uk, wk)
  7. 6if A ≠ ∅ then relax w: cost(w) ← min(cost(w), cost(u) + cost of the cheapest atom of A)
  8. 7return the program on a cheapest path from start to goal, or none if goal is not reached
  9. DAG(σ, o) ▷ P(t): all position expressions that denote t on σ
  10. 8for each pair 0 ≤ i < j ≤ |o| do
  11. 9W(i, j) ← {ConstStr(o[i .. j))}
  12. 10for each a with σ[a .. a + j - i) = o[i .. j) do
  13. 11add the rectangle SubStr(P(a), P(a + j - i)) to W(i, j)
  14. 12return W

The DAG of one example (lines L8 to L12). The nodes are the indices 0,…,∣o∣0, \ldots, |o| of the output, and there is an edge from ii to jj for each i<ji < j. Its label W(i,j)W(i, j) holds every atom that gives o[i..j)o[i .. j) on σ\sigma. The constant is always there. For each place aa where the piece occurs in the input, line L11 adds the set of atoms SubStr(p1,p2)(p_1, p_2) with p1∈P(a)p_1 \in P(a) and p2∈P(a+j−i)p_2 \in P(a + j - i). This set is stored as a pair of sets, a rectangle, so a label with ss choices on each side holds s2s^2 atoms in 2s2s entries. A path from 00 to ∣o∣|o|, with one atom on each edge, is a program that gives oo.

Intersection (lines L3 to L6). The states of the product are tuples of indices, one for each example. An edge of the product moves every component forward, and its label is the intersection of the labels. Two rectangles meet in the rectangle of the pairwise intersections. Only states that can be reached from the start are built.

Ranking (lines L6 and L7). Every edge raises the sum of the components, so this order is topological, and one pass of dynamic programming finds a cheapest path, as in shortest paths in a DAG. The cheapest atom of a rectangle takes the cheapest position from each set.

Gulwani's full algorithm also learns conditionals: it groups the examples so that each group has a non-empty intersection, and it learns a Boolean classifier that picks the group from the input. It also has a loop construct for repeated patterns. Neither is in the pseudocode above.

Example

Take σ1\sigma_1 = "Alan Turing" and o1o_1 = "A. Turing". The DAG has the 10 nodes 0,…,90, \ldots, 9 and the 45 edges i<ji < j. Some labels:

edge piece constant rectangles atoms
(0,1)(0, 1) "A" "A" SubStr({(\{CPos(0)(0), CPos(−12)(-12), Pos(ε,L,1)(\varepsilon, L, 1), Pos(ε,L,−2)},{(\varepsilon, L, -2)\}, \{CPos(1)(1), CPos(−11)})(-11)\}) 9
(1,3)(1, 3) ". " ". " none, since "." is not in the input 1
(1,2)(1, 2) "." "." none 1
(2,9)(2, 9) " Turing" " Turing" one rectangle, from index 4 to index 11, with 8 and 4 positions 33
(3,9)(3, 9) "Turing" "Turing" one rectangle, from index 5 to index 11, with 8 and 4 positions 33

The index 4 is the space. Eight expressions denote it: CPos(4)(4), CPos(−8)(-8), Pos(L,ε,1)(L, \varepsilon, 1) and Pos(L,ε,−2)(L, \varepsilon, -2) (the first of the two places where a run of letters ends), Pos(ε,S,±1)(\varepsilon, S, \pm 1) and Pos(L,S,±1)(L, S, \pm 1). The index 1 is inside the run "Alan", so only CPos names it.

The 45 labels together hold 5,389 programs with at most 3 atoms, and 514,150,720 programs in all. The cheapest has cost (1,3,7)(1, 3, 7):

Concat(SubStr(CPos(0), CPos(1)), ConstStr("."), SubStr(Pos(ε\varepsilon, S, −1-1), CPos(−1-1)))

It uses one constant character, because the space of ". " can be copied as the first character of " Turing". On "Grace Hopper" it gives "G. Hopper".

A second example. Add "Grace Hopper" ↦\mapsto "G. Hopper". The product of the two DAGs has 17 reachable states and 83 edges. On the edge from (2,2)(2, 2) to (9,9)(9, 9) the rectangles meet in SubStr with 7 start positions and 3 end positions. CPos(4)(4) drops out, because the space is at index 4 in the first input and at index 5 in the second. CPos(−8)(-8) stays, because both last names have 6 letters. At the end, CPos(11)(11) drops out and CPos(−1)(-1) stays. Of the programs with at most 3 atoms, 126 remain, and 775,656 programs remain in all. The cheapest program is the same as above.

What the examples do not decide. The program that uses Pos(ε,S,1)(\varepsilon, S, 1), the first space, also fits both examples and has the same cost. On "Mary Ann Evans" the chosen program gives "M. Evans", and the other gives "M. Ann Evans". Only a third example, or a better ranking, can decide which one the user wants.

Correctness

The proof is in proofs/correctness.md. Every atom gives a non-empty string, so a program that gives oo cuts oo into pieces at unique indices, and each atom is in the label of its piece. So the programs that give ojo_j are exactly the paths of the jj-th DAG with an atom from each label. A program fits all examples exactly when its index tuples form a path in the product whose labels hold its atoms, and the intersection of rectangles is exact. The cost is a sum of atom costs under a lexicographic order, which is compatible with addition, so dynamic programming in topological order returns a cheapest consistent program, and "none" exactly when no program fits.

Proof: The product DAG holds exactly the consistent programs, and the search returns a cheapest onefull

Setting. A program is a list of atoms f1,…,fnf_1, \ldots, f_n with n≥1n \ge 1. An atom is ConstStr(c)(c) with a non-empty string cc, or SubStr(p1,p2)(p_1, p_2) with two position expressions. On an input σ\sigma, a position expression denotes an index in 0,…,∣σ∣0, \ldots, |\sigma| or is undefined. SubStr(p1,p2)(p_1, p_2) gives σ[a..b)\sigma[a .. b) when p1p_1 denotes aa, p2p_2 denotes bb and a<ba < b, and is undefined otherwise. A program gives the concatenation of its atoms, and it is undefined if one atom is undefined. Pσ(t)P_\sigma(t) is the set of all position expressions of the language that denote tt on σ\sigma. Line numbers refer to the pseudocode on the page.

A rectangle (A,B)(A, B) with sets of position expressions AA and BB stands for the atoms SubStr(p1,p2)(p_1, p_2) with p1∈Ap_1 \in A and p2∈Bp_2 \in B. A label WW is a set of constants together with a list of rectangles, and it stands for the union of these atoms.

Lemma 1: one example

Claim. For an example (σ,o)(\sigma, o) and 0≤i<j≤∣o∣0 \le i < j \le |o|, the label W(i,j)W(i, j) built by lines L8 to L12 holds exactly the atoms that give o[i..j)o[i .. j) on σ\sigma. Its rectangles have pairwise disjoint first sets.

Proof. ConstStr(c)(c) gives cc, and line L9 puts in the one constant o[i..j)o[i .. j). SubStr(p1,p2)(p_1, p_2) gives o[i..j)o[i .. j) exactly when p1p_1 denotes some aa, p2p_2 denotes b=a+(j−i)b = a + (j - i), and σ[a..b)=o[i..j)\sigma[a .. b) = o[i .. j). Line L10 tries every aa with this property, and line L11 adds the rectangle (Pσ(a),Pσ(a+j−i))(P_\sigma(a), P_\sigma(a + j - i)), which holds exactly the atoms with these two positions. A position expression denotes one index on σ\sigma, so the sets Pσ(a)P_\sigma(a) for different aa are disjoint. □\square

Claim. A program f1,…,fnf_1, \ldots, f_n gives oo on σ\sigma if and only if there are indices 0=t0<t1<⋯<tn=∣o∣0 = t_0 < t_1 < \cdots < t_n = |o| with fr∈W(tr−1,tr)f_r \in W(t_{r-1}, t_r) for each rr. The indices are unique.

Proof. If the program gives oo, each atom gives a non-empty string, so the atoms cut oo into nn non-empty pieces. Let trt_r be the length of the output of f1,…,frf_1, \ldots, f_r. Then frf_r gives o[tr−1..tr)o[t_{r-1} .. t_r), and fr∈W(tr−1,tr)f_r \in W(t_{r-1}, t_r) by the first claim. The trt_r are fixed by the lengths of the outputs, so they are unique. In the other direction, each frf_r gives o[tr−1..tr)o[t_{r-1} .. t_r), and the concatenation is oo. □\square

Lemma 2: the intersection of labels

Claim. For labels WW and W′W', the label W∩W′W \cap W' of line L5 holds exactly the atoms in both. If the rectangles of each label have pairwise disjoint first sets, so do the rectangles of the result.

Proof. A constant is in both when it is in both sets of constants. An atom SubStr(p1,p2)(p_1, p_2) is in both when some rectangle (A,B)(A, B) of WW and some (A′,B′)(A', B') of W′W' hold it, that is, when p1∈A∩A′p_1 \in A \cap A' and p2∈B∩B′p_2 \in B \cap B'. The result has the rectangle (A∩A′,B∩B′)(A \cap A', B \cap B') for each such pair with non-empty parts, so it holds exactly these atoms. Two rectangles of the result come from different pairs; they differ in the rectangle of WW or in that of W′W', so their first sets are subsets of two disjoint sets. □\square

Lemma 3: the product DAG

Let the examples be (σ1,o1),…,(σk,ok)(\sigma_1, o_1), \ldots, (\sigma_k, o_k) with non-empty outputs. A state is a tuple u=(u1,…,uk)u = (u_1, \ldots, u_k) with 0≤uj≤∣oj∣0 \le u_j \le |o_j|. Lines L3 to L6 have an edge from uu to ww, with the label W1(u1,w1)∩⋯∩Wk(uk,wk)W_1(u_1, w_1) \cap \cdots \cap W_k(u_k, w_k), when uj<wju_j < w_j for all jj and the label is not empty.

Claim. A program is consistent with all examples if and only if it is the list of atoms along a path from (0,…,0)(0, \ldots, 0) to (∣o1∣,…,∣ok∣)(|o_1|, \ldots, |o_k|), with one atom taken from the label of each edge. Each consistent program comes from exactly one path.

Proof. Let the program f1,…,fnf_1, \ldots, f_n be consistent. Lemma 1 gives, for each example jj, unique indices t0j<⋯<tnjt^j_0 < \cdots < t^j_n. The states ur=(tr1,…,trk)u^r = (t^1_r, \ldots, t^k_r) form a path: each component grows from ur−1u^{r-1} to uru^r, and frf_r is in each Wj(tr−1j,trj)W_j(t^j_{r-1}, t^j_r), so by Lemma 2 it is in the label, which is therefore not empty. Each state on the path is reachable from the start, so the loop of line L3 visits it. The path is unique because the indices are. In the other direction, a path with atoms from its labels gives, for each jj, indices as in Lemma 1, so the program gives ojo_j on σj\sigma_j. □\square

Theorem

SYNTHESIZE returns a consistent program of least cost, and "none" exactly when no program of the language is consistent with the examples. The count of the programs with at most AA atoms, computed over the product DAG, is exact.

Proof. The cost of a program is the sum of the cost tuples of its atoms, compared in lexicographic order. This order is total, and x≤yx \le y implies x+z≤y+zx + z \le y + z. The cost of an atom SubStr(p1,p2)(p_1, p_2) is a fixed part plus the costs of p1p_1 and p2p_2, so the cheapest atom of a rectangle takes the cheapest member of each set, and the cheapest atom of a label is the cheapest over its constants and rectangles.

Along each edge every component of the state grows, so the sum of the components grows, and the order by this sum is a topological order. Line L6 relaxes the edges in this order. By induction over the order, when a state ww is handled, its value is the least cost of a path from the start to ww with the cheapest atom on each edge: each path into ww ends with an edge from a state with a smaller sum, which was final at that time, and the order on costs is compatible with addition. By Lemma 3 the programs of the paths to the goal are exactly the consistent programs, so line L7 returns a cheapest one, or "none" when the goal is not reachable.

For the count: by Lemma 3 each consistent program is one path together with one atom for each edge, and different choices give different programs. The number of atoms in a label is the number of constants plus ∣A∣⋅∣B∣|A| \cdot |B| for each rectangle (A,B)(A, B), because the rectangles are disjoint by Lemmas 1 and 2. A sum over paths with at most AA edges of the product of these numbers is the count. □\square

Complexity

Let nn be the length of the longest input, mm that of the longest output, kk the number of examples, and pp the number of position expressions that denote one index (at most 2 CPos and 90 Pos here).

  • One example. There are O(m2)O(m^2) edges. For each edge, line L10 compares the piece with O(n)O(n) places in O(m)O(m) time each, and each match adds a rectangle of two sets of size at most pp. So the time is O(m2n(m+p))O(m^2 n (m + p)) and the space O(m2np)O(m^2 n p), after computing P(t)P(t) for all tt once.
  • Several examples. The product has at most (m+1)k(m + 1)^k states and (m+1)2k(m + 1)^{2k} edges, and a label can have nkn^k rectangles. So the worst case is exponential in kk. In practice the labels shrink fast and most states are not reachable: in the example above, the product has 17 states, not 102=10010^2 = 100.
  • The number of programs. A DAG of size polynomial in mm and nn holds a number of programs exponential in mm, as the counts above show.

A unit step is one comparison of characters or one operation on a hash set.

Properties

  • Complete for the language. If any program of the language fits the examples, the algorithm finds one. This holds for this language without conditionals; the full FlashFill algorithm may need to split the examples into groups.
  • Exact optimum. The result is a cheapest program for the stated cost. The cost does not ensure that it is the intended program.
  • All programs at once. The product DAG holds every consistent program. A tool can count them, show several, or find an input on which two of them disagree.
  • Deterministic. Ties in cost are broken by a fixed order on atoms.

Variants and improvements

  • Conditionals. FlashFill partitions the examples into classes with a non-empty DAG intersection, and learns a Boolean condition over the inputs for each class.
  • Loops. A Loop construct concatenates the outputs of an expression for the values 1,2,…1, 2, \ldots of a counter until it fails, for outputs such as all initials of a name.
  • Several inputs. SubStr takes an input column as an argument.
  • Semantic transformations. Later work adds lookup tables and the parsing of numbers and dates.
  • FlashMeta. Polozov and Gulwani (2015) build such structures for any domain-specific language from witness functions, which give, for an operator and a wanted output, the outputs that its arguments must have.
  • Learned ranking. Singh and Gulwani (2015) learn the weights of the ranking from tasks with known programs.

When to use it

Use it for string tasks in a language of concatenations, constants and substrings, when the user gives one to a few examples and the inputs share a layout. It is fast for short strings, and it keeps all consistent programs, so a tool can ask the user about inputs where they disagree. For numeric functions or deeper expressions, use bottom-up enumerative synthesis or a solver; for a general grammar, a version space algebra with witness functions.

Pitfalls

  • One example is rarely enough. One example usually fits thousands of programs, and the best by cost can still be wrong on other rows, as the "Mary Ann Evans" case shows. Show the result on all rows.
  • Constants that look like copies. "A. Turing" with the constant "A. " works on one row and fails on all others. The cost must make constants expensive.
  • Empty pieces. If an atom could give the empty string, the DAG would need edges from a node to itself, and the cut of the output into pieces would not be unique. The language here forbids empty substrings.
  • Products grow with the number of examples. Intersect the DAGs one after the other, and drop states that cannot reach the goal.
  • Positions by index. CPos(4)(4) fits one row and fails when the first name has another length. Prefer token positions in the ranking.
  • Tokens. Two strings with the same characters but different runs, such as "ab1" and "a b1", have different token positions. The choice of tokens is part of the language.

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.

string_transformation_synthesis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/string-transformation-synthesis/. The authors are listed in prov/NBNPFH.jsonl.
"""String transformation synthesis in the style of FlashFill, on a small language.

The language:
    program   Concat(f1, ..., fn), a tuple of atoms, n >= 1
    atom      ("const", s)            the non-empty string s
              ("sub", p1, p2)         the input from position p1 up to position p2
    position  ("cpos", k)             k >= 0: index k; k < 0: index len + 1 + k
              ("pos", r1, r2, c)      the c-th index t where a run of token r1 ends
                                      and a run of token r2 starts; c in +-1..+-3,
                                      negative c counts from the right
Tokens are "D" (digits), "L" (letters), "S" (spaces) and "E" (the empty token,
which matches at every index); r1 and r2 are not both "E". A run is a maximal
block of characters of one token. A substring is defined only when both
positions are defined and p1 < p2, so every atom gives a non-empty string, and
a program is undefined when one of its atoms is undefined.

synthesize(examples) builds one DAG for each example, over the indices of the
output, with all atoms that produce each piece of the output. It intersects
the DAGs and returns the cheapest program, or None. The cost is the tuple
(number of characters in constants, number of atoms, sum of position costs),
compared in this order. A position costs 1 for CPos(0) and CPos(-1), 2 for a
token position, 3 for CPos(k) with k > 0 and 4 for CPos(k) with k < -1.
"""

TOKENS = ("D", "L", "S", "E")
COUNTS = (1, 2, 3, -1, -2, -3)


def token_of(ch):
    if ch.isdigit():
        return "D"
    if ch.isalpha():
        return "L"
    if ch == " ":
        return "S"
    return None


def _ends_run(s, t, tok):
    if tok == "E":
        return True
    return t > 0 and token_of(s[t - 1]) == tok and (t == len(s) or token_of(s[t]) != tok)


def _starts_run(s, t, tok):
    if tok == "E":
        return True
    return t < len(s) and token_of(s[t]) == tok and (t == 0 or token_of(s[t - 1]) != tok)


def eval_pos(p, s):
    """The index that position p denotes in s, or None."""
    if p[0] == "cpos":
        k = p[1]
        t = k if k >= 0 else len(s) + 1 + k
        return t if 0 <= t <= len(s) else None
    _, r1, r2, c = p
    ms = [t for t in range(len(s) + 1) if _ends_run(s, t, r1) and _starts_run(s, t, r2)]
    if c > 0:
        return ms[c - 1] if c <= len(ms) else None
    return ms[c] if -c <= len(ms) else None


def eval_atom(f, s):
    if f[0] == "const":
        return f[1]
    a, b = eval_pos(f[1], s), eval_pos(f[2], s)
    if a is None or b is None or a >= b:
        return None
    return s[a:b]


def run(program, s):
    """The output of the program on s, or None if it is undefined."""
    out = []
    for f in program:
        r = eval_atom(f, s)
        if r is None:
            return None
        out.append(r)
    return "".join(out)


def positions(max_len):
    """All position expressions that can be defined on a string of length <= max_len."""
    ps = [("cpos", k) for k in range(-(max_len + 1), max_len + 1)]
    for r1 in TOKENS:
        for r2 in TOKENS:
            if r1 == "E" and r2 == "E":
                continue
            for c in COUNTS:
                ps.append(("pos", r1, r2, c))
    return ps


def pos_cost(p):
    if p[0] == "cpos":
        if p[1] in (0, -1):
            return 1
        return 3 if p[1] > 0 else 4
    return 2


def atom_cost(f):
    """(characters in constants, atoms, position cost); tuples compare in this order."""
    if f[0] == "const":
        return (len(f[1]), 1, 0)
    return (0, 1, pos_cost(f[1]) + pos_cost(f[2]))


def add_cost(a, b):
    return tuple(x + y for x, y in zip(a, b))


def program_cost(program):
    c = (0, 0, 0)
    for f in program:
        c = add_cost(c, atom_cost(f))
    return c


def position_sets(s):
    """For each index t of s, the set of position expressions that denote t."""
    sets = {t: set() for t in range(len(s) + 1)}
    for p in positions(len(s)):
        t = eval_pos(p, s)
        if t is not None:
            sets[t].add(p)
    return {t: frozenset(v) for t, v in sets.items()}


def example_dag(s, out):
    """The labels W[(i, j)] of the DAG of one example: (constants, substring choices)."""
    pset = position_sets(s)
    w = {}
    for i in range(len(out)):  # @line L8
        for j in range(i + 1, len(out) + 1):
            piece = out[i:j]
            subs = []
            for a in range(len(s) - (j - i) + 1):
                if s[a:a + j - i] == piece:  # @line L10
                    subs.append((pset[a], pset[a + j - i]))  # @line L11
            w[(i, j)] = (frozenset([piece]), tuple(subs))  # @line L9
    return w  # @line L12


def intersect_labels(x, y):
    consts = x[0] & y[0]
    subs = []
    for a1, a2 in x[1]:
        for b1, b2 in y[1]:
            c1 = a1 & b1
            if c1:
                c2 = a2 & b2
                if c2:
                    subs.append((c1, c2))
    return (consts, tuple(subs))


def label_empty(lab):
    return not lab[0] and not lab[1]


def label_count(lab):
    return len(lab[0]) + sum(len(p1) * len(p2) for p1, p2 in lab[1])


def best_atom(lab):
    """The cheapest atom of a label, with its cost."""
    best = None
    for c in sorted(lab[0]):
        cand = (atom_cost(("const", c)), ("const", c))
        if best is None or cand < best:
            best = cand
    for p1s, p2s in lab[1]:
        p1 = min(p1s, key=lambda p: (pos_cost(p), p))
        p2 = min(p2s, key=lambda p: (pos_cost(p), p))
        f = ("sub", p1, p2)
        cand = (atom_cost(f), f)
        if best is None or cand < best:
            best = cand
    return best


def product_edges(dags, outs, u):
    """The edges of the product DAG that leave the state u, with their labels."""
    k = len(dags)
    res = []

    def go(j, label, w):
        if j == k:
            res.append((tuple(w), label))
            return
        for nxt in range(u[j] + 1, len(outs[j]) + 1):
            lab = dags[j][(u[j], nxt)]
            lab = lab if label is None else intersect_labels(label, lab)  # @line L5
            if not label_empty(lab):
                go(j + 1, lab, w + [nxt])

    go(0, None, [])
    return res


def product_dag(examples):
    """The reachable part of the intersection of the example DAGs."""
    dags = [example_dag(s, o) for s, o in examples]  # @line L1
    outs = [o for _, o in examples]
    start = tuple(0 for _ in examples)  # @line L2
    goal = tuple(len(o) for o in outs)
    edges = {}
    seen = {start}
    frontier = [start]
    while frontier:  # @line L3
        u = frontier.pop()
        edges[u] = product_edges(dags, outs, u)  # @line L4
        for w, _ in edges[u]:
            if w not in seen:
                seen.add(w)
                frontier.append(w)
    return start, goal, edges


def synthesize(examples):
    """The cheapest program consistent with all examples, or None."""
    if any(o == "" for _, o in examples):
        return None
    start, goal, edges = product_dag(examples)
    order = sorted(edges, key=sum)  # every edge raises the sum of the indices
    best = {start: ((0, 0, 0), ())}
    for u in order:
        if u not in best:
            continue
        cu, pu = best[u]
        for w, lab in edges[u]:
            ca, f = best_atom(lab)
            cand = (add_cost(cu, ca), pu + (f,))
            if w not in best or cand < best[w]:  # @line L6
                best[w] = cand
    if goal not in best:
        return None
    return best[goal][1]  # @line L7


def count_programs(examples, max_atoms):
    """The number of programs with at most max_atoms atoms consistent with all examples."""
    if any(o == "" for _, o in examples):
        return 0
    start, goal, edges = product_dag(examples)
    order = sorted(edges, key=sum)
    ways = {start: {0: 1}}
    for u in order:
        for w, lab in edges[u]:
            c = label_count(lab)
            for n, v in ways.get(u, {}).items():
                if n < max_atoms:
                    d = ways.setdefault(w, {})
                    d[n + 1] = d.get(n + 1, 0) + v * c
    return sum(ways.get(goal, {}).values())


def show(program):
    parts = []
    for f in program:
        if f[0] == "const":
            parts.append(f"ConstStr({f[1]!r})")
        else:
            parts.append(f"SubStr({_show_pos(f[1])}, {_show_pos(f[2])})")
    return "Concat(" + ", ".join(parts) + ")"


def _show_pos(p):
    if p[0] == "cpos":
        return f"CPos({p[1]})"
    return f"Pos({p[1]}, {p[2]}, {p[3]})"
test_string_transformation_synthesis.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/string-transformation-synthesis/. The authors are listed in prov/NBNPFH.jsonl.

import random

from string_transformation_synthesis import (
    atom_cost, count_programs, eval_atom, eval_pos, positions, program_cost, run, synthesize,
)

ALPHABET = "abAB12 "
MAX_ATOMS = 4


def brute_force(examples, max_atoms=MAX_ATOMS):
    """Search all programs with at most max_atoms atoms.

    Constants are the non-empty substrings of the first output; a constant of a
    consistent program is always one of them. Atoms with the same outputs on all
    example inputs are grouped, with their number. The search extends a list of
    atoms while the outputs so far are prefixes of the wanted outputs; a list
    that is not a prefix cannot be completed. Returns (number of consistent
    programs, least cost or None, one program with that cost).
    """
    ins = [s for s, _ in examples]
    outs = [o for _, o in examples]
    max_len = max(len(s) for s in ins)
    groups = {}
    ps = positions(max_len)
    for p1 in ps:
        for p2 in ps:
            f = ("sub", p1, p2)
            vec = tuple(eval_atom(f, s) for s in ins)
            if None not in vec:
                groups.setdefault(vec, []).append(f)
    o1 = outs[0]
    pieces = {o1[i:j] for i in range(len(o1)) for j in range(i + 1, len(o1) + 1)}
    for piece in sorted(pieces):
        groups.setdefault(tuple(piece for _ in ins), []).append(("const", piece))
    items = [(vec, sorted(fs, key=atom_cost)) for vec, fs in groups.items()]
    total = 0
    best = [None, None]

    def go(prefix_lens, depth, chosen):
        nonlocal total
        if all(n == len(o) for n, o in zip(prefix_lens, outs)) and depth > 0:
            total_here = 1
            for _, fs in chosen:
                total_here *= len(fs)
            total += total_here
            prog = tuple(fs[0] for _, fs in chosen)
            if best[0] is None or program_cost(prog) < best[0]:
                best[0] = program_cost(prog)
                best[1] = prog
            return
        if depth == max_atoms:
            return
        for vec, fs in items:
            ok = True
            new = []
            for piece, n, o in zip(vec, prefix_lens, outs):
                if o[n:n + len(piece)] != piece:
                    ok = False
                    break
                new.append(n + len(piece))
            if ok:
                go(tuple(new), depth + 1, chosen + [(vec, fs)])

    go(tuple(0 for _ in outs), 0, [])
    return total, best[0], best[1]


def random_string(rng):
    return "".join(rng.choice(ALPHABET) for _ in range(rng.randint(1, 6)))


def random_program(rng, max_len):
    ps = positions(max_len)
    prog = []
    for _ in range(rng.randint(1, 3)):
        if rng.random() < 0.3:
            prog.append(("const", rng.choice(["-", ".", "x", "ab", ", "])))
        else:
            prog.append(("sub", rng.choice(ps), rng.choice(ps)))
    return tuple(prog)


def random_task(rng, k):
    while True:
        ins = [random_string(rng) for _ in range(k)]
        prog = random_program(rng, max(len(s) for s in ins))
        outs = [run(prog, s) for s in ins]
        if None not in outs:
            return list(zip(ins, outs))


def check(examples):
    total, least, witness = brute_force(examples)
    found = synthesize(examples)
    if witness is not None:
        assert all(run(witness, s) == o for s, o in examples)
        assert program_cost(witness) == least
    if found is not None:
        assert all(run(found, s) == o for s, o in examples)
    if least is not None:
        # If the search finds a program, so does the synthesizer, and no cheaper one exists.
        assert found is not None
        assert program_cost(found) <= least
        if len(found) <= MAX_ATOMS:
            assert program_cost(found) == least
    elif found is not None:
        assert len(found) > MAX_ATOMS
    assert count_programs(examples, MAX_ATOMS) == total


def test_random_tasks_match_brute_force():
    rng = random.Random(7)
    for t in range(30):
        check(random_task(rng, 1 + t % 3))


def test_random_outputs_match_brute_force():
    rng = random.Random(8)
    for t in range(30):
        k = 1 + t % 2
        examples = [(random_string(rng), random_string(rng).strip() or "a") for _ in range(k)]
        check(examples)


def test_names():
    examples = [("Ada Lo", "A. Lo"), ("Bo Ng", "B. Ng")]
    check(examples)
    prog = synthesize(examples)
    assert run(prog, "Cy Wu") == "C. Wu"
    assert sum(1 for f in prog if f[0] == "const") == 1


def test_one_example_is_ambiguous():
    prog = synthesize([("Ada Lo", "A. Lo")])
    assert run(prog, "Ada Lo") == "A. Lo"
    assert count_programs([("Ada Lo", "A. Lo")], 3) > count_programs([("Ada Lo", "A. Lo"), ("Bo Ng", "B. Ng")], 3)


def test_positions():
    s = "ab 12 c"
    assert eval_pos(("pos", "L", "S", 1), s) == 2
    assert eval_pos(("pos", "S", "D", 1), s) == 3
    assert eval_pos(("pos", "E", "L", -1), s) == 6
    assert eval_pos(("pos", "E", "L", 3), s) is None
    assert eval_pos(("cpos", -1), s) == 7
    assert eval_pos(("cpos", -8), s) == 0
    assert eval_pos(("cpos", -9), s) is None
    assert atom_cost(("const", "x")) > atom_cost(("sub", ("cpos", 4), ("cpos", 5)))


def test_unrealizable():
    assert synthesize([("ab", "zz"), ("12", "yy")]) is None
    assert brute_force([("ab", "zz"), ("12", "yy")])[0] == 0

History

Gulwani (2011) presented the language, the DAG of one example, the intersection of DAGs, the learning of conditionals and the ranking at POPL 2011. The method shipped as Flash Fill in Microsoft Excel 2013. Singh and Gulwani (2015) replaced the hand-made ranking by a learned one. Polozov and Gulwani (2015) made the method general in FlashMeta, which builds version space algebras for any domain-specific language with witness functions, and which they used for FlashFill and for other tasks such as text extraction.

References

  1. Sumit Gulwani, Automating string processing in spreadsheets using input-output examples, Principles of Programming Languages (POPL 2011), pp. 317-330, the language of trace expressions with ConstStr, SubStr, CPos and Pos, the DAG of one example, the intersection of DAGs, conditionals and loops, and the ranking
  2. Oleksandr Polozov and Sumit Gulwani, FlashMeta, a framework for inductive program synthesis, Object-Oriented Programming, Systems, Languages and Applications (OOPSLA 2015), pp. 107-126, the general form with witness functions and version space algebras, with FlashFill as one instance
  3. Rishabh Singh and Sumit Gulwani, Predicting a correct program in programming by example, Computer Aided Verification (CAV 2015), pp. 398-414, a learned ranking function for FlashFill programs
  4. Sumit Gulwani, Oleksandr Polozov and Rishabh Singh, Program Synthesis, Foundations and Trends in Programming Languages 4(1-2), 2017, chapter 7, programming by examples, with FlashFill as the main example

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 proofH1 sketch
  • a full proof of time.all examples
  • a full proof of time.one example
  • a full proof of space.all examples
  • a full proof of space.one example
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
  • a scene preset for the example