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
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of input and output strings, with non-empty outputs.
Output. A program of the language below with for each , 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 with atoms.
- An atom is ConstStr for a non-empty string , or SubStr, the input from position up to position . It is defined only when , so every atom gives a non-empty string.
- A position is CPos, the index for and the index for , so CPos is the end. Or it is Pos: the -th index, from the left for and from the right for , where a run of the token ends and a run of the token starts. The tokens are digits, letters, spaces, and the empty token , which matches at every index. A run is a maximal block of characters of one token. Here , and and are not both .
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 and CPos cost 1, a Pos costs 2, CPos with costs 3, and CPos with 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
SYNTHESIZE((σ1, o1), …, (σk, ok))- 1
for j = 1 … k do Wj ← DAG(σj, oj) - 2
start ← (0, …, 0); goal ← (|o1|, …, |ok|) - 3
for each state u reachable from start, in increasing order of u1 + … + uk do - 4
for each w with uj < wj ≤ |oj| for every j do - 5
A ← W1(u1, w1) ∩ … ∩ Wk(uk, wk) - 6
if A ≠ ∅ then relax w: cost(w) ← min(cost(w), cost(u) + cost of the cheapest atom of A) - 7
return the program on a cheapest path from start to goal, or none if goal is not reached DAG(σ, o) ▷ P(t): all position expressions that denote t on σ- 8
for each pair 0 ≤ i < j ≤ |o| do - 9
W(i, j) ← {ConstStr(o[i .. j))} - 10
for each a with σ[a .. a + j - i) = o[i .. j) do - 11
add the rectangle SubStr(P(a), P(a + j - i)) to W(i, j) - 12
return W
The DAG of one example (lines L8 to L12). The nodes are the indices of the output, and there is an edge from to for each . Its label holds every atom that gives on . The constant is always there. For each place where the piece occurs in the input, line L11 adds the set of atoms SubStr with and . This set is stored as a pair of sets, a rectangle, so a label with choices on each side holds atoms in entries. A path from to , with one atom on each edge, is a program that gives .
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 = "Alan Turing" and = "A. Turing". The DAG has the 10 nodes and the 45 edges . Some labels:
| edge | piece | constant | rectangles | atoms |
|---|---|---|---|---|
| "A" | "A" | SubStrCPos, CPos, Pos, PosCPos, CPos | 9 | |
| ". " | ". " | none, since "." is not in the input | 1 | |
| "." | "." | none | 1 | |
| " Turing" | " Turing" | one rectangle, from index 4 to index 11, with 8 and 4 positions | 33 | |
| "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, CPos, Pos and Pos (the first of the two places where a run of letters ends), Pos and Pos. 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 :
Concat(SubStr(CPos(0), CPos(1)), ConstStr("."), SubStr(Pos(, S, ), CPos()))
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" "G. Hopper". The product of the two DAGs has 17 reachable states and 83 edges. On the edge from to the rectangles meet in SubStr with 7 start positions and 3 end positions. CPos drops out, because the space is at index 4 in the first input and at index 5 in the second. CPos stays, because both last names have 6 letters. At the end, CPos drops out and CPos 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, 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 cuts into pieces at unique indices, and each atom is in the label of its piece. So the programs that give are exactly the paths of the -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 with . An atom is ConstStr with a non-empty string , or SubStr with two position expressions. On an input , a position expression denotes an index in or is undefined. SubStr gives when denotes , denotes and , and is undefined otherwise. A program gives the concatenation of its atoms, and it is undefined if one atom is undefined. is the set of all position expressions of the language that denote on . Line numbers refer to the pseudocode on the page.
A rectangle with sets of position expressions and stands for the atoms SubStr with and . A label 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 and , the label built by lines L8 to L12 holds exactly the atoms that give on . Its rectangles have pairwise disjoint first sets.
Proof. ConstStr gives , and line L9 puts in the one constant . SubStr gives exactly when denotes some , denotes , and . Line L10 tries every with this property, and line L11 adds the rectangle , which holds exactly the atoms with these two positions. A position expression denotes one index on , so the sets for different are disjoint.
Claim. A program gives on if and only if there are indices with for each . The indices are unique.
Proof. If the program gives , each atom gives a non-empty string, so the atoms cut into non-empty pieces. Let be the length of the output of . Then gives , and by the first claim. The are fixed by the lengths of the outputs, so they are unique. In the other direction, each gives , and the concatenation is .
Lemma 2: the intersection of labels
Claim. For labels and , the label 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 is in both when some rectangle of and some of hold it, that is, when and . The result has the rectangle 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 or in that of , so their first sets are subsets of two disjoint sets.
Lemma 3: the product DAG
Let the examples be with non-empty outputs. A state is a tuple with . Lines L3 to L6 have an edge from to , with the label , when for all 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 to , with one atom taken from the label of each edge. Each consistent program comes from exactly one path.
Proof. Let the program be consistent. Lemma 1 gives, for each example , unique indices . The states form a path: each component grows from to , and is in each , 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 , indices as in Lemma 1, so the program gives on .
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 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 implies . The cost of an atom SubStr is a fixed part plus the costs of and , 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 is handled, its value is the least cost of a path from the start to with the cheapest atom on each edge: each path into 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 for each rectangle , because the rectangles are disjoint by Lemmas 1 and 2. A sum over paths with at most edges of the product of these numbers is the count.
Complexity
Let be the length of the longest input, that of the longest output, the number of examples, and the number of position expressions that denote one index (at most 2 CPos and 90 Pos here).
- One example. There are edges. For each edge, line L10 compares the piece with places in time each, and each match adds a rectangle of two sets of size at most . So the time is and the space , after computing for all once.
- Several examples. The product has at most states and edges, and a label can have rectangles. So the worst case is exponential in . In practice the labels shrink fast and most states are not reachable: in the example above, the product has 17 states, not .
- The number of programs. A DAG of size polynomial in and holds a number of programs exponential in , 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 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 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.
# 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
- 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
- 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
- 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
- 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.
| 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 NBNPFH Edit this page History Report an error Markdown