8. Open variable lists¶
A fixed-size array works well when the number of decisions is known before search starts. Some problems instead have solutions of different lengths: routes can visit different numbers of nodes, for example, and a pattern can contain different numbers of symbols. An open variable list lets the model decide its length and creates variables as they are needed.
This chapter uses OpenIntVarList to find simple routes in a directed graph. It builds on spaces and cloning from Getting started, and on automata from Extensional constraints. Branching is discussed in more detail in Branching.
8.1. Routes of unknown length¶
The graph in Program 8.1 has five nodes, numbered zero to four. We want all routes from node zero to node four that visit each node at most once. There are cycles in the graph, but a simple route can contain at most five nodes. This gives a finite bound on the list length without excluding any solution.
class OpenRoute : public Script {
protected:
/// Number of graph nodes and maximal route length
static const int n = 5;
/// Node IDs in route order, including source and destination
OpenIntVarList route;
public:
/// Branching to use for the route
enum {
BRANCH_INCREMENTAL, ///< Assign the current prefix before extending it
BRANCH_LENGTH ///< Choose the complete route length first
};
/// Construct the model
OpenRoute(const Options& opt)
: Script(opt), route(*this,IntSet(0,n-1),n) {
// State 5 consumes the source node. Each remaining transition consumes
// the destination of a graph arc; only node 4 is an accepting state.
DFA paths(5,{
{5,0,0},
{0,1,1}, {0,2,2}, {0,4,4},
{1,2,2}, {1,4,4},
{2,1,1}, {2,3,3},
{3,2,2}, {3,4,4}
},{4});
extensional(*this,route,paths);
distinct(*this,route);
// Ordinary brancher posting order gives length-first search when wanted.
if (opt.branching() == BRANCH_LENGTH)
branch(*this,route.length(),INT_VAL_MIN());
branch(*this,route,INT_VAR_NONE(),INT_VAL_MIN());
}
Download: open-route.cpp
The member route contains the node variables in route order, including
the source and destination. Its constructor supplies their common domain
IntSet(0,n-1) and a maximum length n. It does not create an array of
n node variables. The list has a separate integer variable
route.length() for its eventual length.
The automaton paths describes the graph. Its extra start state five
consumes the source node zero. The other transitions consume the destination
of a graph arc, and only state four is accepting. The open-list overload of
extensional therefore constrains the route to start at zero, follow
graph arcs, and end at four. The distinct constraint excludes revisits.
Both constraints follow the list as it grows.
The regular constraint prunes the node variables as the prefix grows. It also checks whether an accepting continuation fits within the maximum list length. Values that require too many further positions are removed. When the list closes, the route must end in an accepting state. This filtering does not use the domains of positions not yet constructed or holes in the length domain, and it does not directly prune the length variable.
8.2. The prefix and the eventual length¶
known_length() counts the positions that have been constructed. Their
variables can still be unassigned. Indexed access with route[i] is
limited to this prefix; it does not create a new position.
The minimum of length() requires that many positions to exist.
Propagation constructs them, using the list’s variable factory and any
transition callback. Requiring more positions can itself post constraints
that require a longer prefix. This continues until the required positions
have been constructed or the space fails.
There are also explicit operations for growing a list. materialize(home,n)
requires at least n positions, and get(home,i) requires and returns
the variable at position i. Both restrict the eventual length. After
get, check whether the space has failed before using the returned
variable; on failure the handle can be uninitialized. An index at or beyond
the maximum eventual length raises Int::OutOfLimits. append(home,x)
adds an existing variable belonging to the current space and requires the
length to include it. Appending the same unassigned variable twice throws
Int::ArgumentSame; this also applies to variables returned by a factory.
Equal assigned values can occur at different positions, subject to the
constraints on the list.
close(home) first constructs any positions required by the minimum
length, then assigns the eventual length to the number of constructed
positions. Closing determines the number of positions. It does not assign
their variables.
8.3. Choosing values and length¶
The open-list brancher selects among the constructed variables using ordinary
variable and value selectors. In the route example, INT_VAR_NONE() and
INT_VAL_MIN() assign positions from left to right, trying smaller node
numbers first. Once these variables are assigned, the brancher first tries
closing the list. Its other alternative requires one more position and
continues selecting values. Propagation can require more than one new
position when the list grows.
To choose the complete length first, post a brancher on route.length()
before the list brancher. Branchers run in posting order, so the length is
assigned and propagation constructs the required positions before the list
brancher selects their values. The conditional brancher in the program
supports this comparison. Build the downloaded source as described in
Compiling, linking, and executing, then run:
./open-route
./open-route -branching length
Both searches find the same five routes. They use different search trees and can return the routes in different orders. The default search constructs a route incrementally; the second search tries the shorter lengths first. The better order depends on the problem.
Selectors and filters operate on the constructed prefix. Filter and print
callbacks receive the position in the list. Variables rejected by the filter
can remain unassigned when the list brancher finishes. Action and CHB selectors
require the whole list to have been constructed when the brancher is posted;
otherwise posting throws Int::UnknownBranching.
Whenever the application permits it, give the list a finite maximum length. Exploring longer routes can be very expensive even if a few short solutions are easy to find.
8.4. Constraints that follow growth¶
An open list has its own constraint overloads. Passing the current prefix to a constraint on a fixed array would constrain only the variables already present. It would not arrange for later positions to join that constraint.
Besides distinct and the regular extensional constraint used above,
integer lists support relations between consecutive variables, sequence
and sliding_sum over each complete window, min and max of the
eventual nonempty sequence, and value precedence through precede. The
open distinct constraint is value consistent; its propagation-level
argument does not select stronger filtering.
sequence filters each complete window separately; it does not provide
domain consistency across overlapping windows. Its propagation-level argument
is ignored. sliding_sum uses bounds propagation when its lower and upper
sum bounds differ. For equality, it supports bounds or domain propagation;
the default is domain propagation for windows of size at most two and bounds
propagation for larger windows. A list shorter than the window size has no
complete windows and satisfies either constraint.
For min and max, bounds are enforced as positions appear. Once the
list closes, at least one position must equal the result. Closing an empty
list therefore fails. The result variable can also occur as a list element.
For precede, every occurrence of the later value requires an earlier
occurrence of its predecessor; neither value is required to occur. Its
propagation-level argument is ignored.
Regular constraints are available for integer and Boolean lists. The complete sequence must be accepted by the automaton when the list closes; intermediate prefixes need not be accepted words.
Propagator authors can follow growth through OpenViewList, described in Views of open variable lists.
8.5. Cloning and callbacks¶
The copy constructor updates route just as it updates an ordinary
variable array. Handles referring to the same list in one space continue
to share a list in the clone, but the clone has its own mutable state.
Growing or closing one space’s list does not change the other space.
/// Constructor for cloning \a s, including the space-local open list
OpenRoute(OpenRoute& s) : Script(s) {
route.update(*this,s.route);
}
/// Perform copying during cloning
virtual Space*
copy(void) {
return new OpenRoute(*this);
}
/// Print the materialized route (complete in a solution)
virtual void
print(std::ostream& os) const {
os << "\t";
for (int i=0; i<route.known_length(); i++) {
if (i > 0)
os << " -> ";
os << route[i];
}
os << " (length " << route.length() << ")" << std::endl;
}
};
The print function visits known_length() positions. In a solution,
branching has determined the length and assigned the variables, so this is
the complete route.
OpenBoolVarList supplies the corresponding factory for Boolean
variables. The generic OpenVarList template also accepts a factory
for another variable type, such as SetVar or FloatVar. Such a list
shares the storage and cloning machinery, but not all integer-list
constraints and branching overloads exist for that variable type.
A factory creates the variable at a position in the space passed to it. An optional transition callback can post constraints after a position is added. The function objects are shared between clones. They must be deterministic and safe for concurrent calls, and must own or share any captured data. They must not capture a space or its variable handles. Use the supplied space and, in a transition callback, the supplied list to access the current model.
Factories and transitions run inside Space::NoGPI contexts, including
transitions called by a direct append. Propagators posted there have
space-local information and zero AFC; identifiers and groups remain
available. A callback can use a local Space::UseGPI context for postings
that should accumulate ordinary AFC. Nested list construction starts its
own NoGPI context. Each context restores the previous setting when it is
destroyed.
For the lifetime, cloning, and rewriting rules of these contexts, see Scoped control of propagator information.