Dynamic programming by polymorphic semiring algebraic shortcut fusion
Abstract
Dynamic programming (DP) is a broadly applicable algorithmic design paradigm for the efficient, exact solution of otherwise intractable, combinatorial problems. However, the design of such algorithms is often presented informally in an ad-hoc manner. It is sometimes difficult to justify the correctness of these DP algorithms. To address this issue, this paper presents a rigorous algebraic formalism for systematically deriving DP algorithms, based on semiring polymorphism. We start with a specification, construct a (brute-force) algorithm to compute the required solution which is self-evidently correct because it exhaustively generates and evaluates all possible solutions meeting the specification. We then derive, primarily through the use of shortcut fusion, an implementation of this algorithm which is both efficient and correct. We also demonstrate how, with the use of semiring lifting, the specification can be augmented with combinatorial constraints and through semiring lifting, show how these constraints can also be fused with the derived algorithm. This paper furthermore demonstrates how existing DP algorithms for a given combinatorial problem can be abstracted from their original context and re-purposed to solve other combinatorial problems.
This approach can be applied to the full scope of combinatorial problems expressible in terms of semirings. This includes, for example: optimization, optimal probability and Viterbi decoding, probabilistic marginalization, logical inference, fuzzy sets, differentiable softmax, and relational and provenance queries. The approach, building on many ideas from the existing literature on constructive algorithmics, exploits generic properties of (semiring) polymorphic functions, tupling and formal sums (lifting), and algebraic simplifications arising from constraint algebras. We demonstrate the effectiveness of this formalism for some example applications arising in signal processing, bioinformatics and reliability engineering. Python software implementing these algorithms can be downloaded from: http://www.maxlittle.net/software/dppolyalg.zip.
⋆School of Computer Science, University of Birmingham, UK
†MIT, Cambridge, MA, USA
#Abdullah Gul University, Turkey
First author contact: [email protected]111This work partially funded by NIH grant UR-Udall Center, award number P50 NS108676.
1 Introduction
Dynamic programming (DP) (Bellman, 1957; Sniedovich, 2011) is one of the most effective and widely used computational tools for finding exact solutions to a large range of otherwise intractable combinatorial problems (Kleinberg and Tardos, 2005). Typically, the exhaustive (brute-force) solution to problems for which DP is amenable are of exponential or even factorial, time complexity. Where DP is applicable, it is often possible to reduce the worst case computational effort required to solve the problem, to something tractable such as low-order (quasi)-polynomial.
Nonetheless, devising correct and efficient DP algorithms typically relies on special intuition and insight (de Moor, 1999). It is also often difficult to prove that an algorithm is correct with respect to a formal problem specification and gain understanding of the function of these algorithms from their, sometimes inscrutable, implementations. To address these shortcomings, a more systematic approach is to start with a specification of the combinatorial problem and then compute an efficient implementation of the same, through provably correct derivation steps. In this way, the resulting algorithm is both efficient and guaranteed correct. This approach is exemplified in constructive algorithmics frameworks described in e.g. Bird and de Moor (1996), de Moor (1991) and Jeuring (1993).
This paper reports on a novel and relatively simple approach to the systematic design of such DP algorithms which exploits semiring polymorphism and shortcut fusion. Our approach starts from a specification given in terms of a semiring objective over the set of all combinatorial configurations in the DP problem. With a semiring polymorphic generator of this set of combinatorial configurations (often given by a Bellman recursion) we show how to derive an efficient and correct algorithm for solving the semiring objective by applying semiring shortcut fusion. We furthermore show how this approach can be extended to complex DP problems which solve semiring objectives over multiple combinatorial constraints.
Our approach brings together several concepts that have traditionally existed independently across various fields, including machine learning, computational linguistics, and automata theory. Semirings (Golan, 1999) are widely used in special DP applications (Huang, 2008; Goodman, 1999; Mensch and Blondel, 2018; Li and Eisner, 2009), but their general usage in DP lacks rigorous justifications in terms of correctness with respect to a specification, which we provide here. We furthermore show how semiring lifting (Emoto et al., 2012) can be used to solve more complex constrained DP problems where the constraint is expressed in terms of an algebra homomorphism. When this constraint algebra is a group we show that it further simplifies the algorithm implementation. We also show how semirings can often be combined in parallel (tupled) to significant advantage such as providing a general implementation of backtracing applicable to any such semiring DP algorithm.
Our approach is applicable to a very wide range of unconstrained or constrained combinatorial problems which can be expressed in terms of semirings. We demonstrate its effectiveness on some practical, novel extensions of classical problems in signal processing, machine learning, computational statistics and engineering.
The layout of the paper is as follows. In Section 2, we detail the main theoretical developments of this paper, and in Section 3 we develop DP algorithms for applications from several disciplines. Section 4 puts the work into the context of existing research on DP algorithms in general. We end in Section 5 with a summary and discussion of the importance, general scope and possible extensions of the work. The appendices contain detailed proofs of the main results in the paper, list some widely-used semirings and simplified constraint algebras.
2 Theory
In this paper, sets are indicated by the upper case double-strike letters with their corresponding cardinalities, and , or the standard sets etc. The Boolean set is given by (for true, false respectively). To indicate the type of sets with elements of type , we write . The type of lists (that is, ordered sequences) with elements in the arbitrary type are denoted with . Binary algebraic operators are written as circled symbols, and their corresponding identities are . Algebras and objects such as monoids, groups and semirings using binary operators are given as tuples with upper-case calligraphic letters for names, e.g. is a semiring over values of type with binary operators with identities and a monoid with values of type and binary operator . Integer and natural number indices are given by lower case letters etc. We use the superscript notation as shorthand for (higher-order) function application which does not have any input (it is not a function). Thus, for having type it follows the function has type . If has an additional recurrence index, , then it has type so that is shorthand for partial application , full application uses subscript notation . Where an algebra appears in the superscript , this is shorthand for which in this case means full application to the operators and identities of the algebra . Where there is no ambiguity we suppress superscript parameters purely for presentational clarity. Binary operators are subscripted to indicate lifting, e.g. is the operator lifted over the monoid algebra and the lifted semiring value denotes a function of type which has an input of type of values in the monoid algebra . Regarding types, lifting means that, whereas the plain semiring operator is a function taking two semiring values to a single semiring value e.g. of type , its lifted version takes two lifted values , returning another lifted value so it has type .
2.1 Correct and efficient dynamic programming by semiring fusion
A very wide class of DP problems can be specified as a combinatorial problem over a semiring ,
(1) |
where is the set of all combinatorial configurations and embeds values in the DP problem into values in the semiring . As an example, consider the rod-cutting problem which maximizes the sum of values of segments of a list partition. A partition of a list is a decomposition of a list of values, into a list of non-empty contiguous segments. For instance, for the list , the set of configurations is
(2) |
In this example, the combinatorial configurations are list partitions of segments, so variable represents a partition such as and variable a segment of that partition such as , with being the value of that segment. We can specify the rod-cutting problem as
(3) |
which is an instance of (1) with the max-plus semiring .
We will next demonstrate how to solve (1) through brute-force (exhaustive) generate-evaluate computation. There is a special semiring which can be used to exhaustively generate the set of all possible combinatorial configurations . We call this special semiring the generator semiring . This well-known semiring (and variants) arise in several contexts; for example, to computational linguists it is called the formal language semiring over sets of lists with elements of type , which we denote by . The operator is set union, and is the cross-join of two sets of lists obtained by concatenating each element in configuration with each element in . To illustrate, for elements set ,
(4) |
Define a semiring generator which is a function fully applied to the arbitrary semiring ’s binary operators and operator identities and value mapping function , which maps some data into semiring values. Apply this function to the generator semiring and value mapping function which embeds an element into a singleton configuration, . In this way, we will generate (enumerate) all combinatorial configurations by computing . Also, assume we have an evaluation function which is a semiring homomorphism preserving the semiring structure for all ,
(5) | ||||
along with the requirement that for all . Here, we suppress the subscripted parameters from for clarity. Now, using this generator and evaluator , problems defined by the semiring specification (1) can be solved exactly using the following exhaustive generate-evaluate algorithm,
(6) |
Self-evidently, this solves (1) because generates the set and then evaluates each one of the configurations over and aggregates them over the semiring .
While problem (1) is indeed correctly solved by this generate-evaluate algorithm, this computation is usually intractable because the configurations set is typically exponential (or larger). However, it turns out there is no need to generate the set in the first place. We have assumed that the generator is polymorphic in an arbitrary semiring i.e. it is a function of type
(7) |
In words, this function takes as parameters two semiring operators of type , two semiring operator identities of type and a mapping function , returning a value of type . Then, we can show the following equivalence holds,
(8) |
provided only in addition that is a semiring homomorphism mapping . We call this theorem semiring fusion. If the semiring has operators with computational complexity, then computing will be much more computationally efficient than using (6). The proof of this theorem, given rigorously in Appendix A: Proof of DP semiring fusion is a straightforward application of Wadler’s free theorem (Wadler, 1989). This theorem is very widely applicable in the context of DP because semiring polymorphic generators are extremely common, for instance, all Bellman recursions are of this form (Bellman, 1957; Sniedovich, 2011).
2.2 Constraint lifting
Combinatorial problems in applications of DP, are often more complex than those which can be specified by the simple semiring formulation (1). For instance, let us suppose we want to constrain the semiring problem to restrict it to apply only to configurations which satisfy some constraint, . Such constrained combinatorial problems are specified as,
(9) |
As with exhaustive generate-evaluate above, a self-evidently correct (but not at all “smart”) way to solve (9) is to apply the following algorithm. Firstly, compute all configurations using a semiring generator . Then, remove (filter away) those configurations for which using a filtering function partially applied to the constraint function, . Finally, evaluate the remaining configurations using a evaluation function . This generate-filter-evaluate algorithm computes,
(10) |
The difficulty with this approach is the same as faced above: the intractable size of the intermediate configurations . Above, this was solved by invoking semiring fusion (93), but unfortunately here the filtering prevents this theorem from being applicable. We will present a practical solution to this which makes use of semiring lifting (Jeuring, 1993; Emoto et al., 2012). This is based on the following idea: if we can find a new semiring which implicitly evaluates the constraints , then we can fuse the constraint with the semiring homomorphism (5) so that semiring fusion (93) becomes applicable once more. This will effectively eliminate the need to compute , which is responsible for the intractability of the algorithm (10). The resulting theorem will be a generalization of theorem (8).
To apply this idea, we will need constraints expressed in a separable form, which we explain in detail next. Although not entirely general, many kinds of constraints typically encountered in combinatorial problems are in this form (Sniedovich, 2011). Such separable constraints are formalized using a constraint algebra which we denote by . The only restrictions on the constraint set is that it is countable and (for practical implementation purposes) of finite cardinality. The binary operator is usually accompanied by an identity, (but this is not essential, we will illustrate this below). Then, a typical separable constraint can be defined in terms of a recurrence function partially applied to monoid ’s operator and identity over a set of configurations of length ,
(11) | ||||
where the constraint map maps an element in a configuration into a constraint value . Widely encountered algebras include arbitrary finite monoids ( is associative) and finite groups. To complete this separable specification of the constraint, we define a Boolean acceptance condition, , whereby a configuration is retained if evaluates to true. Thus, for a configuration the constraint in (9) is computed using .
In this separable formulation, problem (10) is restated by
(12) |
with the modified filtering function which is partially applied to the algebra , constraint mapping and acceptance criteria , implementing . To illustrate, a specific, recursive implementation of can be given as (Bird and de Moor, 1996),
(13) | ||||
where , are configurations in the configuration set and we suppress the superscripted parameters of and only for clarity.
To give a concrete, practical example of this separable constraint formalism, with the additive constraint group , the constraint with the mapping computes lengths of configurations . Indeed, this algebra is just the list length homomorphism defined by the recursion , (Bird and de Moor, 1996). Thus, the recurrence (26) coupled with this constraint group and the acceptance criteria,
(14) |
restricts configurations to only those of length .
With this separable formulation, we can construct a new semiring by lifting over the algebra (Jeuring, 1993; Emoto et al., 2012). This is the desired semiring with which we can fuse the constraint with the semiring homomorphism (5). Lifting creates vectors (which we can also consider as functions) of semiring values of type . The new, composite semiring has binary operators over values given explicitly by,
(15) | ||||
where refers to indexing with values in . The associated operator identities are,
(16) | ||||
The operator is an interesting and far-reaching generalization of discrete convolution operators found in contexts such as digital signal processing, machine learning and applied mathematics. We also need the lifted value mapping, given by,
(17) |
where the original semiring map is and the constraint map is .
Finally, to obtain the solution to to (8), we need to project the vector lifted over , onto using the projection function partially applied to semiring operators and identities and acceptance criteria ,
(18) |
This yields all the ingredients to define a theorem which we call semiring constrained fusion,
(19) |
To summarize (19), on the left hand side, exhaustively computes configurations in ; filters away any configurations which do not satisfy the constraint implemented by and over the constraint algebra and evaluates the remaining configurations in with the semiring using the mapping . On the right hand side, (fully) applied to lifted semiring’s ’s operators and identities and lifted mapping function , first maps the element into lifted semiring values using and lifts them over the constraint set using . It then evaluates all configurations in , for every value of the constraint set , using the lifted semiring . Finally, projects this lifted computation back down onto the plain semiring .
The proof of (19) result is given in Appendix B: Constraint lifting proofs. To give some informal intuition into the steps in this proof, we show that (15) is a semiring and then using a change of variables argument, show how the projection is obtained. We then demonstrate that the composition of the filtering with the semiring homomorphism, can be fused into a new homomorphism over the constraint-lifted semiring. This allows us to use our already established result (19) to show that the composition of the exhaustive configuration generator followed by the filtering, is equivalent to evaluation of these configurations in the lifted semiring, followed by a projection.
We raise a couple of important comments about this theorem here:
-
1.
The effect on the computational and memory complexity of the corresponding unconstrained algorithm (8), is quite predictable. For most practical computational semirings (e.g. max-plus or sum-product) the operators will be . In this setting, for each value of , the binary operator is , and the operator is . Thus, in general, applying a constraint increases the worst-case computational complexity of an existing polymorphic semiring generator function by a multiplicative factor . In terms of memory, lifting requires storing values per configuration, therefore the memory complexity increases multiplicatively by a factor .
-
2.
Lifting is intimately related to the design of DP algorithms found in textbooks, in the following way. A widely stated, but intuitive observation, is that designing practical DP algorithms boils down to identifying a structural decomposition which makes frequent re-use of sub-problems (Kleinberg and Tardos, 2005). This design principle is easy to state, but often quite tricky to apply in practice, as it can depend upon a serendipitous discovery of the right way to parameterize the problem. However, implicit to the definition of the constraint operator for constraints which can be implemented in separable algebraic form, is the relationship that solutions for different values of the constraint algebra have with each other. The lifted product in (15) combines all solutions at every value of the constraint. However, for each , the condition in the product partitions the solutions in a way which determines how the DP sub-problems should be combined. In other words, this partitioning, coupled with the pairwise summation, determines the dependency structure of configurations . For example, in the case of the simple natural number addition, , to find the sub-problem for the case requires us to combine all sub-problems , , and , together. Interestingly, this also demonstrates that DP decompositions can be performed in ways that are much more general than the fairly limited descriptions of combining “smaller”, self-similar problems. Indeed, it is useful to think of DP decomposition as arising from a partitioning of the space of the constraint value under the constraint operator , into subsets of pairs of sub-problems for a given value of .
2.3 Simplifying the constraint algebra
The main problem with the construction (19) is that the direct computation of is quadratic in the size of . This is not a problem for small lifting sets, but for many practical problems we want to apply constraints which can take on a potentially large set of values, which makes the naive application of constraint lifting computationally inefficient. We also know that it is often possible to come up with hand-crafted DP algorithms which are more efficient than this. We can, however, substantially improve on this quadratic dependence by noting that for many semiring polymorphic configuration generators given as DP (Bellman) recursions, we need to compute terms of the form for some general . Since the lifted mapping function only for one value, , we can simplify the double summation to a single one,
(20) | ||||
Because the operator does not necessarily have inverses, solutions to the equation are not necessarily unique. However, we can flip this around and instead explicitly compute for each . This leads to an obvious iterative algorithm,
(21) | ||||
to obtain at the end of the iteration; here the arrow denotes setting the variable on the left, to the value on the right, possibly overwriting the previous value of the variable. Thus the product (20) is an inherently operation. As a result, semiring polymorphic generators modified to produce constrained configurations will have worst-case multiplicative increase in time complexity of , if the semiring product appears in the generator only in terms of the form . This is true, for instance of all algebraic path problems (Huang, 2008) and we will encounter several other examples below.
If, additionally, the algebra has inverses (for example, if the algebra is a group), on fixing and , there is a unique (and often analytical) solution to which we can write as . This also allows us to simplify the lifted semiring product to the computation,
(22) |
Note that we often have finite groups where we are not interested in defining inverses for all elements, for example where we need but . In that case, setting suffices to appropriately truncate the above product.
For such group lifting algebras, terms of the form simplify even further. We can solve uniquely to find , so that the product (20) can, in this situation, now be computed as,
(23) |
which is an time operation. Thus, semiring polymorphic configuration generators can be modified to produce constrained configurations with multiplicative time complexity increase of only , if constraints are expressible in terms of a group algebra. Some examples of useful, simplified constraint algebras are listed in Appendix D: Some useful constraint algebras.
2.4 Taking stock: worked example
Let us pause to examine how to apply the preceding theory. Consider the problem of finding the value of the minimum sum subsequence of a list (a subsequence being a sublist of generally non-consecutive elements of a list). We can specify this simple, unconstrained combinatorial optimization problem as,
(24) |
where the configuration set contains all possible subsequences of a list, of which there are for lists of length . For instance, the subsequences of the list are
(25) |
This is a specification (1) over the min-plus semiring . For a given a length list indexed as , a simple, semiring polymorphic generator is given by the following DP Bellman recursion,
(26) | ||||
where embeds elements of some given list to -semiring values. Semiring fusion (8) tells us that given by
(27) | ||||
is a correct algorithm for solving problem (24) exactly in time complexity, even though the exhaustive solution would require generating and evaluating subsequences requiring exponential time.
Now, assume that, rather than subsequences, we are interested in combinations of elements of a list (that is, fixed-size subsequences). We can define a constrained subsequence problem as
(28) |
where the constraint condition receives a subsequence, and evaluates to true if that subsequence has the given length . For instance, if , the configurations constrained by sublist length for list is the set
(29) |
This sequence length constraint can be formulated using the lifting algebra , constraint mapping function and acceptance criteria if and otherwise. Inserting the semiring ’s operators and lifted mapping into the semiring polymorphic generator recursion (26), we obtain,
(30) | ||||
where we suppress ’s superscripts for clarity. The first line above simplifies to,
(31) |
and the second line can be simplified as follows,
(32) | ||||
for all and . Explicitly, by invoking constrained semiring fusion (19), in the min-plus semiring with this is,
(33) | ||||
which is a simple , provably correct algorithm for solving 28 through computing using the recursion (33) above.
It is instructive to compare this systematically derived algorithm to the textbook presentation of similar DP algorithms such as the quasi-polynomial knapsack problem (Kleinberg and Tardos, 2005; Emoto et al., 2012). We have obtained this DP algorithm by starting from a specification and by provably correct derivation steps, arrived at the new, computationally efficient recurrence above which solves the constrained problem. Often, the solutions obtained this way resemble hand-coded DP algorithms which involve ad-hoc and specific reasoning where we have to resort to special case analysis to demonstrate correctness and computational complexity, after the algorithm is coded.
2.5 Tupling semirings to avoid backtracing
The above cases have demonstrated the use of arbitrary semirings where some scalar-valued, numerical solution is required. It is often the case for optimization problems (involving the use of selection semirings such min-plus, ) that we also want to know which solutions lead to the optimal (semiring) value. The usual solution to this (given in most DP literature) is backtracing, which retains a list of decisions at each stage and a series of “back pointers” to the previous decision, and then recovers the unknown decisions by following the sequence of pointers backwards.
In fact, there is an alternative and conceptually simpler solution made possible with the use of appropriate semirings. In particular we will focus on the generator semiring . We can always exploit what is known as the tupling trick to compute two different semirings simultaneously (Bird and de Moor, 1996). If we map the semiring values used during the DP computations inside a pair , then we can simultaneously update a semiring total while retaining the values selected in that stage. For example, the arg-max-plus selection, also known as the Viterbi, semiring (Goodman, 1999; Emoto et al., 2012),
(34) |
has operators given explicitly by,
(35) | ||||
with identities and . Furthermore, it is straightforward to construct a semiring which extends the Viterbi semiring by maintaining a ranked list of optima, i.e. computing the top optimal solutions, not merely the single highest scoring one (Goodman, 1999).
In most practical situations, for instance, where the mapping function in the DP problem is real-valued and thus have effectively zero probability of not being unique, there will only be a single, rather than potentially multiple, optimal solutions. In that case, we can remove the ambiguities in the selection with a simpler semiring,
(36) |
with operators,
(37) | ||||
Clearly, the semiring is the tupling of max-plus with in such a way as to compute both the value of the optimal solution alongside the values used to compute it.
Backtracing and the simple (Viterbi) tupled semiring will usually be similar in terms of computational complexity. Any particular, practical implementation may well require a more detailed investigation of the specifics of the particular data structures in the DP recurrence and the software and/or hardware platforms involved. For instance, while semiring tupling does require list concatenation and array structures could certainly pose a complexity issue, when implemented instead as linked lists this concatenation takes time, and indeed in practice, DP algorithm recurrences derived using the methods described here reduce to a sequence of list append operations, each for linked lists.
However, the specifics of lower-level implementation complexity are incidental: the overall argument is one of high-level conceptual clarity and systematic derivation, since the tupling construction requires no modification to the algebraic derivations given here. For instance, backtracing requires a way to traverse the DP decisions correctly in the reverse order, which will be special to each DP problem. With tupled semirings and semiring polymorphic generator functions, all that is required is to change the semiring of the DP generator algorithm function as described above, we do not need to know anything about how the generator algorithm works. Additionally, tupling semirings is trivially compatible with any set of multiple lifting constraints where hand-coding of special implementations of backtracking through the same set of multiple interacting constraints, would be error-prone.
2.6 Constructing new DP algorithms from old
The above sections have explained how to specify a combinatorial problem in an arbitrary semiring and how to derive an efficient algorithm to solve it. It has demonstrated how the use of semiring lifting allows us to modify an existing DP algorithm specification with a constraint, which can then be solved efficiently using constrained semiring fusion (19). Here, we show how this gives us a way of creating new, semiring polymorphic DP generators from existing ones such as . To see this, note that the semiring homomorphism with is the identity homomorphism for values in the semiring , i.e. it maps sets of lists, into the same sets of lists unchanged. Thus we obtain,
(38) | ||||
where the last step invokes (19). We have shown that , which we denote by , this is the generator which computes a constrained configuration set. Now, fixing , acceptance criteria and constraint map , we notice that depends only upon the semiring and map . Thus it, too, is semiring polymorphic since we can replace the and in with any arbitrary semiring and mapping to obtain . It follows that we can consider as a new semiring polymorphic generator function derived from the existing generator, . This implies, in particular:
-
1.
If is the generator of for the problem in (1), then the new, derived polymorphic generator is the generator for the constraint augmented problem where and is implemented by , and which are fixed in (implicit to) . This, of course, just a way of expressing an algorithm for efficiently computing in terms of an algorithm for efficiently computing which is implicit to the constrained semiring fusion theorem (19).
-
2.
Being semiring polymorphic, this new generator function satisfies all the conditions of semiring fusion (8), i.e. with an arbitrary semiring homomorphism , we have .
-
3.
We can repeat this process of augmenting an existing specification solved by use of a semiring polymorphic generator to derive novel, polymorphic DP algorithm with multiple, simultaneous constraints. This is possible, essentially, because lifting can always be “nested”, i.e. lifted semirings can themselves be lifted.
These implications have practical consequences in applications, which we now illustrate. Above, we demonstrated how to derive an algorithm for the min-plus problem over subsequence combinations (33) from the min-plus problem over subsequences, by semiring lifting applied to the polymorphic generator for subsequences, (26) which we repeat here for convenience,
(39) | ||||
which is known as an efficient DP algorithm for solving the specification over an arbitrary semiring and mapping by computing . The resulting polymorphic generator of combinations, (30), is a straightforward DP Bellman recursion for solving specifications over subsequence combinations of length . For semirings wherein the operators can be evaluated in constant time, this has time complexity. It is interesting and useful in its own right so we provide a pseudocode implementation here, Algorithm 1.
-
function polycombs()
for
-
for
if
else
-
return
-
As a somewhat more complex example, for some applications, there is a need to perform computations over non-empty subsequences, that is subsequences without the empty sub-sequence . Analogous to the subsequence problem, we can define the non-empty subsequence problem in an arbitrary semiring as,
(40) |
where the constraint function is true if the configuration is non-empty. For instance, for the sequence , the set of non-empty subsequences consists of the set
(41) |
which has size . To use semiring lifting we need a constraint algebra for , for which we define an existence constraint algebra (see Appendix B: Constraint lifting proofs) with the constant constraint map which partitions the set of subsequences generated by the recurrence (26), into empty and non-empty subsequences,
(42) | ||||
suppressing the superscript dependence of here on for clarity. The last line can be rewritten,
(43) | ||||
so that as expected in the empty subsequence case. Focusing on the case we want, , we have,
(44) |
which, being expressed entirely in terms of the case , allows us to ignore the lifting altogether to obtain the following semiring polymorphic generator for non-empty subsequences,
(45) | ||||
which solves and requires only steps.
We now build on this result further by augmenting this recurrence with additional constraints, to provide a novel class of algorithms for special kinds of non-empty subsequences. Algorithms derived in this subsection include solutions to the longest increasing subsequence problem, which occurs frequently in applications such as computational genomics (Zhang, 2003). This problem can be specified as,
(46) |
where the constraint constraint returns true if is an increasing subsequence. This problem is in the form of (1) with semiring with map which counts the length of the list, . For example, for the sequence, the constrained configuration set is
(47) |
and .
Starting from the non-empty subsequence recurrence (45) derived above, we can augment this with a constraint that the subsequence elements must be in an ordered chain according to some binary relation which we write . For example the ordering holds that must be less than . Here, we require a somewhat more complex relation in which both sequence and the value must be ordered, so that we can define a lifting algebra using what we call a sequential-value ordering operator,
(48) |
over tuples , where is a special tuple which act like an annihilator or zero element. Operator is left but not right, associative and it does not have an identity, so, a lifting algebra using this operator, is not a “standard” algebra (such as a monoid, group or semigroup). The lack of identity means that it cannot be applied to empty sequences. Nonetheless, the acceptance criteria if and otherwise, allows us to filter away non-empty subsequences which are not in sequentially increasing order, provided the operator is scanned across the subsequence in left-right order.
To apply this constraint, we can simplify the lifting algebra using this ordering operator
(49) |
which, when substituted into (45), gives us
(50) | ||||
for all . The first line simplifies to , and the second line can be manipulated to obtain
(51) | ||||
To implement this DP recurrence, we next need to choose the lifting set . In this setting, we will typically have a unique (finite) list, e.g. one unique value per . Thus, the lifting set consists of the values from this set, e.g. , and the lift mapping functions merely index this set, e.g. . Note that with this particular lifting set, there is a one-one mapping between and any , thus, we can reduce the lifting set to and lift mapping to , so that the ordering operator becomes,
(52) |
These reductions allow us to simplify the above recurrence 51 to
(53) | ||||
Finally, note that, the second line adds a constant term to each , is associative, and the value of the first line is independent of , we can move this term from the second line to the first, leading to the following polymorphic DP recursion for increasing sequential subsequences,
(54) | ||||
with the projection . In terms of computational complexity, the recurrence must be computed for all and the second requires steps. Note that, the third line does not change the value of for obtained at the previous iteration, so that, iterating over , only the term needs updating in the second line. Thus, the algorithm requires steps.
The longest increasing sub-sequences DP algorithm which computes is obtained as a special case of (54) with the semiring and the lift mapping ,
(55) | ||||
so that . Compared to existing, classical implementations of this algorithm in the literature (Zhang, 2003), we note that, the algebraic simplifications afforded by our approach makes it transparent that there is no need to perform semiring products in the second line, which may lead to computational savings in practice.
Whilst, for the longest increasing subsequences problem, there are somewhat more efficient algorithms which exploit the special structure of the problem, the generalized ordered subsequences DP algorithm derived here, (51), being polymorphic, can be applied to any arbitrary binary relation :
(56) |
For example, we immediately obtain an algorithm for semiring computations over all non-decreasing subsequences (ordering ), or, for subsequences consisting of sets, all subsequences ordered by inclusion, .
3 Applications
In this section we will investigate some practical applications of the algebraic theory developed above.
3.1 Segmentation
A problem of perennial importance in statistics and signal processing is that of segmentation, or dividing up a sequence of data items or a time series for , into contiguous, non-overlapping intervals (segments) for with . Thus, is a segment of length one. An example is the problem of (1D) piecewise regression, which involves fitting a functional curve to segments, and minimizing the sum of model fit errors , where for being the fit error within each interval . The optimal model parameters can be estimated using any statistical model-fitting procedure (Little, 2019). Thus, the input of the problem is the time series , and the output, after solving the DP problem, will be a set of indicators, from which a complete model of the time series can be recovered.
Similar to equation (1), we can specify the segmentation problem as a combinatorial optimization problem,
(57) |
where is the all possible segmentation. For , the set of configurations is
(58) |
An DP algorithm for this problem was devised by Richard Bellman as follows (Kleinberg and Tardos, 2005). The optimal segmentation ending at index can be obtained by combining all the “smaller” optimal segmentations with the following segments , for all . This gives rise to the following Bellman recursion,
(59) | ||||
This recursion efficiently solves the problem (57), so that .
Using the theory in Section 2, by abstracting this recursion over an arbitrary semiring and semiring map function , we obtain the polymorphic segmentation generator algorithm,
(60) | ||||
Using this polymorphic recursion, we can, for example, obtain the optimal configuration as well , using the tupled selection semiring, see Section 2.5.
Since the segment fit errors are, generally, all non-negative, and shorter segments are typically more accurately modelled than larger segments (given the same model structure across segments), the problem as stated above usually has a “degenerate” optimal solution with only the ‘diagonal’ segments of length 1, selected. To avoid the collapse onto this degenerate solution, we can regularize the sum (Little, 2019),
(61) |
for the regularization constant where counts the number of segments in the configuration . It is simple to modify the semiring polymorphic DP recursion (60) to include this regularization term simply by choosing the semiring mapping , so that using the min-sum semiring .
While this regularization approach is simple, it does not offer much control over the segmentation quality, as the appropriate choice of the single parameter can be difficult to obtain. For example, some choices lead to over and under-fitting in different parts of the same signal, see Figure 2(a). Instead, a more effective level of control can be obtained by directly constraining the segmentation to a fixed number of segments, which we can express with the specification,
(62) |
This is a constrained semiring problem of the form (9) where if the size of is , over the min-plus semiring . To apply semiring lifting, the constraint algebra needs to count the number of segments up to the fixed number of segments , which implies we need the lifting algebra and constraint mapping function , with acceptance condition if . Next, inserting the corresponding lifted semiring into (60) we obtain,
(63) | ||||
The first line above simplifies to for and otherwise, and the second line becomes,
(64) | ||||
using the group product simplification (23) in the second step. Finally, to solve (62), we apply the acceptance condition in the min-sum semiring , to obtain
(65) |
which computes the result in time with memory. In practice, this algorithm produces much more predictable results than the basic algorithm, see Figure 2(b). Interestingly, it is well-known in machine learning circles that the ubiquitous -means clustering problem (Little, 2019), which is computationally intractable for non-scalar data items and therefore approximated using heuristic algorithms, can be solved exactly using the algorithm derived above for scalar data (Gronlund et al., 2018). However, existing presentations in the literature are not formally proven correct and thus our presentation here is, to our knowledge, the first formally correct derivation from specification.
Furthermore, it is trivial to adapt the acceptance criteria above to e.g. solve constraints of the form , giving an upper and lower bound on the number of segments, by modifying when . The corresponding DP algorithm is derived from the specification as follows,
(66) | ||||
where here, is the semiring polymorphic generator given in (64).
The segment count constraint above is fairly straightforward and has been (re)-invented in an ad-hoc manner before (Terzi and Tsaparas, 2006). We will next show how to derive a segmentation algorithm for segmentation problems with much more elaborate constraints which would be far more difficult to derive without systematic analytical tools such as we describe in this paper. While the segment count constraint is certainly very practical, there are other ways to control the segmentation since we may not know the number of segments in advance. The length, , of each segment is a property of key practical importance. For example, it would be extremely useful in many applications to control the minimum length of each segment,
(67) |
which is in the form of (9) using the constraint if , i.e. the set of lengths of all the segments in is at least , over the min-sum semiring . Following the procedure above, we have the lifting algebra and lift mapping function . For the semiring lifted segmentation recursion (63), the first line becomes,
(68) |
We also need the product (20), which becomes,
(69) |
This lifting algebra is a monoid without analytical (and unique) inverses, so, to make progress, we need to find an explicit expression for the set for . There are three cases to consider,
(70) |
and upon inserting this into the product above, we arrive at,
(71) |
so that the second line of the lifted segmentation recursion (63) can be simplified,
(72) | ||||
for all . Using the acceptance condition if we have an time DP algorithm to find the required solution, using the derived recurrence above and min-plus semiring . As previously, a simple modification of the acceptance function allows, for example, computing optimal segmentations across a range of minimum segment lengths. Applied to the scalar -means problem, this modification would be a viable approach to avoiding the problem of degenerate clusters assigned few or no items (Little, 2019).
We find that constrained DP segmented regression, derived using the algebraic methods introduced here, usually produces very interpretable results, even for problems where the segmentation boundaries may be quite difficult to determine using other methods, particularly when the signal-to-noise ratio is low, see Figure 1. For example, methods such as L1 trend filtering (Kim et al., 2009) suffer from the problem that there is often no single, unambiguous segmentation, see for example Figure 1(d) and Figure 2(d). This is because it is better to consider such L1-based methods as smoothing algorithms arising from a convex relaxation of the combinatorial segmentation problem. This clearly shows the advantage of constrained, exact combinatorial optimization in applications such statistical time series analysis, made practical by the algebraic approach described in this paper.


3.2 Sequence alignment
Our next application focus is sequence alignments, a problem of central importance to computational biology, natural language processing and signal processing. For example, in genomic sequence analysis, we are often interested in knowing how closely related two DNA or RNA base pair sequences are, and this can be assessed by computing the most plausible series of mutations (insertions and deletions) needed in order to bring the two sequences and into alignment. This alignment problem is specified as an optimal matching problem finding the minimum cost transformation from sequence into sequence ,
(73) |
where configurations set consists of all possible sequence transformations. These transformations are restricted to insertions, deletions or simple matches (no transformation required) for pair sequences at positions in the sequences, and . More specifically, an insert operation aligns the sequences at position pair with the pair at incurring a cost , a deletion aligns the sequences at position pair with the pair at at cost , and a match aligns the sequences at pair with the pair at incurring cost . For example, for sequences of length and , there are 5 possible ways of transforming into , so that the set of transformations is,
(74) | ||||
One of the earliest and most widely used methods for minimizing this cost is the Needleman-Wunsch (NW) DP algorithm (Pachter and Sturmfels, 2005), the usual presentation of which is given in the min-sum semiring,
(75) | ||||
for all and , where is the cost of the alignment of the first sequence at position , with the second sequence at position . The optimal alignment is obtained at .
To apply our results, we construct a semiring polymorphic abstraction of the above,
(76) | ||||
We can now put this semiring polymorphic generator to use for various purposes. One application is counting all possible alignments. Semiring fusion (8) tells us that using the count semiring with . A closed-form formula for this number of alignments, denoted is not known, but by expanding above we find , , and , which simplifies to the following recurrence,
(77) |
This recursion describes the well-known Delannoy numbers which for is the integer sequence Sloane (2021, sequence A001850), with leading order asymptotic approximation . Thus, semiring polymorphism allows us to show that brute-force computation of all alignments would be intractable as it requires exponential time complexity, whereas the factorized DP NW implementation has e.g. quadratic, computational cost (Figure 3).
One practical problem with the standard NW algorithm (75) is that it places no constraint on how far the sequences can become out of alignment. After all, any two DNA/RNA sequences are related by an arbitrary number of insertions/deletions, but this has no biological significance in general. It would be useful to bound e.g. the sum of the absolute difference in sequence positions, so that we can exclude spurious alignments between sequences which bear no meaningful relationship to each other. We can specify this constrained sequence alignment problem as,
(78) |
which is in the form of (9) when if in the min-plus semiring .
To solve (78), we can set up the simple constraint algebra and with acceptance criteria . As this algebra is a group, we can insert this into (23) to obtain,
(79) |
which we write as for convenience. Inserting this into (76), we arrive at,
(80) | ||||
for all and . Thus, .
Further rearrangements of (80) based on case analysis are possible and may improve the readability of the algorithm, but as they do not generally improve implementation efficiency, we do not explore further here. The length of alignments, lying between and , should be taken into account when choosing the acceptance function and thereby bounding the alignment difference sum. The result is an time complexity algorithm for maximum sum of absolute alignment differences .
Although the alignment difference sum is convenient algebraically, another constraint which may be useful is the maximum absolute alignment difference. Bounding this quantity gives more precise control over the extent to which the sequences can become misaligned before the sequences are considered not to be matched at all. To implement this using the algebraic theory developed above, we need the constraint algebra and algebra , where is the upper bound on the possible sequence misalignment. Because is a monoid, we need to modify the general lifted product (20) as follows,
(81) |
Now, we need to find an explicit expression for the set for . Similar to the situation with constrained segmentations above, there are three cases to consider:
(82) |
which gives rise the following general lifted product,
(83) |
which we also denote by for convenience. Inserting this into (80) gives us a novel, time DP algorithm for NW sequence alignments with an (arbitrary) constraint on the maximum absolute difference of misalignments (Figure 3).

3.3 Discrete event combinations
As a final application exposition, in many contexts, it is important to be able to compute quantities over sequences of discrete events. An important application from reliability engineering is computing the probability of a combination of components in a complex engineered system failing, when each failure has a given probability. A common specification for such discrete event combinations as the semiring problem,
(84) |
where is the set of all possible sequences of events, each event having probability we will focus on the basic failure/non-failure case where for survival and for failure and where is the size of sequences of events being considered. Thus is the total probability over all possible sequences of fail/non-fail events. This specification is in the form of (1) over the probability semiring for semiring mapping . For , the set of all possible sequences of events is,
(85) |
There are such sequences. A simple semiring polymorphic generator recursion for all possible sequences of fail/non-fail events, is the following,
(86) | ||||
where represents component non-failure and component failure at event number .
In practice, engineers are interested in the more complex case of the total probability of all possible sequences where failures in events occurs. That means we need to constrain event sequences so that exactly failures, coded as , appear in each sequence. The corresponding constrained discrete event combinations problem is,
(87) |
which is in the form of (9) where if . For and , we have,
(88) | ||||
Note that this is similar to, but subtly different from, the problem of selecting subset size as the constraint, (30). Using our algebraic theory, we express this constraint using the simple algebra which adds up the number of failures and constraint map where and acceptance criteria if and false otherwise. Since is a group, we insert this into (23) to obtain,
(89) |
which we can then immediately insert into (86) to get
(90) | ||||
suppressing semiring superscripts of for clarity. This simplifies to the following semiring polymorphic generator recursion,
(91) | ||||
for all and . In the probability semiring then and correspond to probabilities of failure and non-failure on event , respectively. An application of constrained semiring fusion (19) obtains the algorithm . This time complexity algorithm is extremely similar to that of Radke and Evanoff (1994) which was derived through special, ad-hoc reasoning. Of course, being semiring polymorphic, we can put the generator recursion (91) to other uses such as determining the most probable component failure combination (max-product semiring) or using this as a differential component in a machine learning system (softmax semiring).
4 Related work
Several formal approaches to DP exist in the literature, at various levels of abstraction. The seminal work of Karp and Held (1967) is based on representing DP recurrences as discrete sequential decision processes, where monotonicity justifies optimizing an associated global objective function. This framework is not polymorphic. The work of de Moor (1991) and others (Bird and de Moor, 1996) bases an abstraction of DP on category theory and relations such as inequalities, for combinatorial problems over arbitrary algebraic data types. It remains to be explored how to apply this relational approach to important DP problems which are not focussed on optimization problems, such as computing complete likelihoods for hidden Markov models (the forward-backward algorithm) (Little, 2019), or expectations for parameter estimation in natural language processing problems (Li and Eisner, 2009), for which semirings are a natural formalism.
An interesting precursor is the model of DP described in Helman and Rosenthal (1985). This describes restricted forms of some of the ideas which are precisely formulated and stated in full generality here, including the key role of the separation of computational structure from the values which are computed, and a special kind of homomorphic map over structural operators, into “choice-product” operators. It is not polymorphic. Implicit semiring polymorphism features in DP algorithms found in many specialized application domains, such as natural language processing over graphs and hypergraphs (Goodman, 1999; Li and Eisner, 2009; Huang, 2008) and more recently in differentiable algorithms for machine learning (Mensch and Blondel, 2018). These studies refer to special DP algorithms and do not address the general DP algorithm derivation problem, as we do here.
Perhaps most closely related to our approach is the semiring filter fusion model of Emoto et al. (2012), which, while not explicitly aimed at DP, covers some algorithms which our framework addresses. It does not address the important relationship between specification and correct algorithm. While polymorphic, it is restricted to sequential decision processes which can be expressed as free homomorphisms over associative list joins. To our knowledge, this article was first to introduce algebraic lifting, albeit lacking proof details and in a limited form restricted to monoids, which we expand in much greater generality and depth here. These limitations of Emoto et al. (2012) appear to rule out non-sequential DP algorithms e.g. sequence alignment, edit distance and dynamic time warping, and algorithms requiring constraints based on more complex lifting algebras such as ordered subsequences.
5 Discussion and conclusions
The paper can be summarised as follows:
-
•
A method is presented for deriving efficient and correct algorithms which solve DP problems specified as semiring objectives evaluated over combinatorial configurations. This makes use of semiring polymorphism and shortcut fusion from constructive algorithmics.
-
•
We show that more complex problems with multiple, simultaneous combinatorial constraints can be solved within the same semiring formalism through semiring lifting, when these constraints can be given in separable algebraic form.
-
•
We show broadly applicable algebraic simplifications which can substantially improve the computational time complexity of these derived algorithms, where access to the form of the semiring generator is available, such as in the case of widely available, explicit DP Bellman recursions.
-
•
Through the use of the tupling trick, we demonstrate a problem-agnostic alternative to backtracing in DP algorithms which does not require any knowledge of the specific DP algorithm.
-
•
Finally, derivations of multiple problems across a range of application areas are given, which show the effectiveness of our framework for a very wide class of problems to which DP is applicable.
While we can always express DP recurrences in a general computer language, to do so over semirings requires special programming effort and overhead. Modern languages which generalize classical computation to various settings such as probabilistic or weighted logic exist and it would be interesting to see how to implement the DP framework of this paper in those languages. For example, semiring programming is a proposed overarching framework which can be considered as a strict generalization of the polymorphic recurrences presented here (Belle and de Raedt, 2020), although this work does not address algorithm derivation. Similarly, we can view our polymorphic DP algorithms as special kinds of sum-product function evaluations (Friesen and Domingos, 2016), although, as with semiring programming, this only describes a representation framework.
Our approach to the derivation of algorithms for constrained combinatorial problems, requires writing these constraints in separable form using algebras such as groups, monoids or semigroups. While this is a very broad formalism, there will be some constraints which cannot be written in this form. Future work may be able to provide similar algebraic derivations when the separability requirement is relaxed. Furthermore, the precise mapping between the approach developed in this paper and e.g. DP algorithms specified as general discrete-continuous mathematical optimization problems, remains an open topic.
Another issue which has not been raised is that of parallel DP implementations. Similar approaches based on constructive algorithmics demonstrate how to produce algorithms which are inherently parallel in the MapReduce framework, but these rely on associative operators and are restricted to the setting of functional recurrences over free list semiring homomorphisms (Emoto et al., 2012). While DP algorithms derived using our framework are not immediately parallelisable in this way, our framework does not rule out exploiting existing inherently parallel recurrences in the form of free list homomorphisms, and for these recurrences, the constraint lifting algebra developed here retains this inherently parallel structure. The drawback is that, in some cases, it may not be possible to simplify the lifted semiring product down to constant time complexity as in (23). Future investigations may explore general DP parallelisation frameworks (Galil and Park, 1994).
A limitation of our approach as developed so far, is that it does not exploit some of the more “advanced” DP speed-up tricks which have been developed for special situations. A particular example of this is the situation where the mapping function in segmentation problems satisfies a special concavity/convexity property (Yao, 1980), enabling a reduction in computational complexity from to . It will be interesting future work to attempt to incorporate this and other tricks, in our framework.
Another limitation of our approach is that it does not provide a way to derive semiring polymorphic Bellman sequential decision process (SDP) recursions for arbitrary combinatorial generators, we must rely upon the existence of such recursions for specific combinatorial objects. A better approach would be to be able to derive these semiring-structured SDPs from specification, which is addressed to a certain extent in the constructive algorithmics literature (Bird and de Moor, 1996) and would be a valuable direction for future research leading from this paper.
As we hope we have been able to persuade, semiring polymorphism is not an abstract curiosity: it is an extremely useful tool for DP algorithm derivation, as it is in many other areas of computing (Belle and de Raedt, 2020; Friesen and Domingos, 2016; Goodman, 1999; Huang, 2008; Pachter and Sturmfels, 2005; Mensch and Blondel, 2018; Sniedovich, 2011). It offers a simple route to deriving correct DP algorithms from specifications and quantifying computational complexity and deriving novel algorithms in a simple, modular way through semiring lifting. It plays a central role in clarifying what we understand to be an essential conceptual principle of DP, which is the separation of combinatorial structure, combinatorial constraint and value computation.
Appendix A: Proof of DP semiring fusion
We use the automated free theorem generator Haskell package (Boehme, 2021) to prove (8). Assume that the function is implemented in some pure, lazy functional language (a language without side effects and without the empty type). The type of the parameters of consists of, respectively, two binary operators , the mapping function where is an arbitrary type, and the constants , and produces a result of type ,
(92) |
where is an arbitrary type. According to Wadler’s free theorem (Wadler, 1989), this type declaration above implies the following theorem.
Theorem 1.
For two algebraic structures and , assume are arbitrary types and function is a map between them. Assume also the existence of binary operators and , constants and and mapping functions , . If, for all and , the function satisfies:
then shortcut fusion applies to the function ,
(93) |
If left and right distributes over and are the associated identity constants, the algebraic object is a semiring. We use the shorthand to denote and the semiring homomorphism satisfying by . Theorem 8 is a corollary.
Corollary.
DP semiring fusion. Given the generator semiring with the mapping function for all , and another, arbitrary semiring with mapping function , if there exists a homomorphism mapping which additionally satisfies for all , then for a function with type given in (92):
(94) |
Appendix B: Constraint lifting proofs
This section is a generalization of the arguments given in Emoto et al. (2012), whilst providing and clarifying essential proof details missing from that work. The formulation of DP constraints as single operator algebras over finite sets requires the use of (semiring) lifting or formal sums as a structural tool for deriving DP constrained fusion. This also provides a definition of the lifted semiring .
Given a semiring and constraint algebra , define semiring-valued formal sums as objects indicating that there are “occurrences” of the element . By convention, elements taking the value are not listed. Accordingly, when two such formal sums are added, the summation acts much like vector addition in the semiring
(95) |
for all . We take this to define the lifted semiring sum elementwise, for all . Clearly, this inherits all the properties of , including commutativity and idempotency. The left/right identity constant satisfying is just .
Next, we describe the generic change of variables (pushforward) formula for such formal sums. Consider an arbitrary function acting to transform values from the algebra . We can ask what happens to a lifted semiring object under this transformation. To do this, construct the product semiring object on ,
(96) |
where the lifted semiring unit function is defined as
(97) |
Then we can “marginalize out” the original variable to arrive at the change of variables formula (familiar to probability theory),
(98) | ||||
where the last step holds if has a unique inverse.
A key step in proving the constrained version of DP semiring fusion, is to be able to fuse the composition of the constraint filtering followed by a semiring homomorphism, into a single semiring homomorphism. To do this, we will lift the constraint filtering over the set . Assume the shorthand and where the acceptance function if and otherwise. We write
(99) |
Thus, denotes the result of first filtering the set of lists to retain any lists on which the constraint evaluates to , and then applying the homomorphism to the remaining lists. Now, for to be a semiring homomorphism, it must preserve semiring structure. For it to be consistent with the filtering, it must also preserve the action of the filtering under .
Turning to the semiring sum, we have,
(100) | ||||
To explain the second step: note that forming the union of sets of lists has no effect on the computation of the constraint value which determines the result of filtering. Thus, the union of sets of lists is invariant under the action of the filter. The third step follows because is a semiring homomorphism.
Somewhat more complex is the semiring product, for which we have
(101) | ||||
Clearly, this motivates the definition of the lifted semiring product as .
The second step above deserves further explanation. We need to be able to push the filter inside the cross-join, which is critical to defining a semiring homomorphism. Recall that the cross-join of two sets of lists involves joining together each list in with each list of . For general lists whose constraints evaluate to and respectively, then due to the separability of the constraint algebra, the constraint value of their join is . If we group together into one set , all those lists whose constraints evaluate to and into another set , all those lists whose constraints evaluate to , then their cross-join will consist of sets of lists, all of which have constraints evaluating to . Finally, for a given and without further information on the properties of , we can find the values of such that by exhaustively considering all possible pairs. Clearly, if is specialized in some way, particularly with regards to the existence of inverses, then this exhaustive search can be reduced, and this is the basis of our algebraic simplifications for special cases such as group lifting algebras.
A semiring homomorphism must map identities. For empty sets which are the identity for , we simply require,
(102) |
Similarly, sets of empty lists act as identities for the cross-join operator. In this case, we must have . If we set , then we have,
(103) | ||||
and similarly for . This shows the lifted semiring identity to be .
Finally, we need to consider the homomorphic mapping of sets with single element configurations e.g. terms like . Under the action of the filter , such terms are only retained if the constraint mapping , whereupon they contribute a value to the semiring value of the homomorphism . Otherwise, they do not contribute anything to the semiring sum. It follows that,
(104) | ||||
which we write as the mapping . To summarize then, (100)-(104) show that is a semiring homomorphism performing the lift mapping :
(105) |
The next step is to reconstruct the result of DP constraint filtering , from the lifted result. This involves computing the effect of the transformation mapping the lifting algebra into the value in of the predicate , on an arbitrary lifted semiring object . The joint product function on is written using the Boolean-semiring unit function:
(106) | ||||
We then project onto the second parameter of to obtain,
(107) | ||||
where the last line holds if has a unique inverse. We use the notation as a shorthand for over the semiring and the acceptance criteria .
Putting everything above together, we can show the following:
(108) | ||||
which constitutes a proof of theorem (19).
Theorem 2.
DP semiring constrained fusion. Given the generator semiring with the mapping function , and another, arbitrary semiring with mapping function , the constraint algebra with constraint mapping function , acceptance criteria , constraint filtering function and projection function , then for a function with type (92):
(109) |
Appendix C: A selection of semirings
A table of some useful (numerical) semirings is given below, for more details on these and other semirings, the book by Golan (1999) is an excellent reference.
Name | Example application | Set | Operations | Identities |
---|---|---|---|---|
Arithmetic | Solution counting | |||
Generator | Exhaustive listing | |||
Boolean | Solution existence | |||
Arithmetic | Probabilistic likelihood | |||
Tropical | Minimum negative log likelihood | |||
Softmax | Differentiable minimum negative log likelihood | |||
Viterbi | Minimum negative log likelihood with optimal solution | |||
Expectation | Expectation-maximization | |||
Bottleneck | Fuzzy constraint satisfaction | |||
Relational | Database queries |
Appendix D: Some useful constraint algebras
References
- Belle and de Raedt [2020] V. Belle and Luc de Raedt. Semiring programming: A semantic framework for generalized sum product problems. International Journal of Approximate Reasoning, 126:181–201, 2020.
- Bellman [1957] Richard Bellman. Dynamic Programming. Princeton University Press, 1957.
- Bird and de Moor [1996] Richard S. Bird and Oege de Moor. Algebra of Programming. Prentice-Hall, 1996.
- Boehme [2021] S. Boehme. free-theorems: Automatic generation of free theorems, 2021.
- de Moor [1991] Oege de Moor. Categories, Relations and Dynamic Programming. PhD thesis, University of Oxford, 1991.
- de Moor [1999] Oege de Moor. Dynamic programming as a software component. In CSCC 1999, Athens, Greece, 1999.
- Emoto et al. [2012] Kento Emoto, Sebastian Fischer, and Zhenjiang Hu. Filter-embedding semiring fusion for progamming with MapReduce. Formal Aspects of Computing, (24):623–645, 2012.
- Friesen and Domingos [2016] A.L. Friesen and P. Domingos. The sum-product theorem: A foundation for learning tractable models. In Proceedings of the 33rd International Conference on Machine Learning, ICML, volume 48, pages 1909–1918, New York, USA, 2016.
- Galil and Park [1994] Z. Galil and K. Park. Parallel algorithms for dynamic programming recurrences with more than O(1) dependency. Journal of Parallel and Distributed Computing, 21(2), 1994.
- Golan [1999] Jonathan S. Golan. Semirings and their Applications. Springer Netherlands, 1 edition, 1999.
- Goodman [1999] J. Goodman. Semiring parsing. Computational Linguistics, 25(4), 1999.
- Gronlund et al. [2018] A. Gronlund, K.G. Larsen, A. Mathiasen, J.S. Nielsen, S. Schneider, and M. Song. Fast exact k-means, k-medians and Bregman divergence clustering in 1D. arXiv, page arXiv:1701.07204v4, 2018.
- Helman and Rosenthal [1985] P. Helman and A. Rosenthal. A comprehensive model of dynamic programming. SIAM Journal on Algebraic Discrete Methods, 6(2):319–333, 1985.
- Huang [2008] L. Huang. Advanced dynamic programming in semiring and hypergraph frameworks. In COLING 2008, pages 1–18, Manchester, UK, 2008. Coling 2008 Organizing Committee.
- Jeuring [1993] J.T. Jeuring. Theories for Algorithm Calculation. PhD thesis, Utrecht University, 1993.
- Karp and Held [1967] R.M. Karp and M. Held. Finite-state processes and dynamic programming. SIAM Journal on Applied Mathematics, 15(3):693–718, 1967.
- Kim et al. [2009] S.-J. Kim, K. Koh, S. Boyd, and D. Gorinevsky. L1 trend filtering. SIAM Rreview, 51(2):339–360, 2009.
- Kleinberg and Tardos [2005] Jon Kleinberg and Eva Tardos. Algorithm Design. Addison-Wesley Longman Publishing Co., Inc., 2005.
- Li and Eisner [2009] Z. Li and J. Eisner. First- and second-order expectation semirings with applications to minimum-risk training on translation forests. In Proceedings of the 2009 Conference on Empirical Methods in Natural Language Processing, pages 40–51, Singapore, 2009. ACL.
- Little [2019] Max A. Little. Machine Learning for Signal Processing. Oxford University Press, Oxford, UK, 2019.
- Mensch and Blondel [2018] A. Mensch and M. Blondel. Differentiable dynamic programming for structured prediction and attention. Proceedings of the 35th International Conference on Machine Learning, 80:3462–3471, 2018.
- Pachter and Sturmfels [2005] L. Pachter and B. Sturmfels. Algebraic Statistics for Computational Biology. Cambridge University Press, 2005.
- Radke and Evanoff [1994] G.E. Radke and J. Evanoff. A fast recursive algorithm to compute the probability of M-out-of-N events. In Proceedings of Annual Reliability and Maintainability Symposium (RAMS), pages 114–117, Anaheim, CA, USA, 1994. IEEE.
- Sloane [2021] N.J.A. Sloane. The on-line encyclopedia of integer sequences, 2021.
- Sniedovich [2011] M. Sniedovich. Dynamic Programming: Foundations and Principles. CRC Press, Boca Raton, US, 2nd edition, 2011.
- Terzi and Tsaparas [2006] E. Terzi and P. Tsaparas. Efficient algorithms for sequence segmentation. In Proceedings of the 2006 SIAM International Conference on Data Mining. SIAM, 2006.
- Wadler [1989] Philip Wadler. Theorems for free! In FPCA ’89: Proceedings of the fourth international conference on Functional programming languages and computer architecture, London, UK, 1989. Association for Computing Machinery.
- Yao [1980] F.F. Yao. Efficient dynamic programming using quadrangle inequalities. In Proceedings of the 12th Annual ACM Symposium on the Theory of Computing, pages 429–435, 1980.
- Zhang [2003] H. Zhang. Alignment of BLAST high-scoring segment pairs based on the longest increasing subsequence algorithm. Bioinformatics, 19(11):1391–1396, 2003.