diff --git a/pumpkin-crates/constraints/src/constraints/table.rs b/pumpkin-crates/constraints/src/constraints/table.rs index 431eb0d0c..84ebf4176 100644 --- a/pumpkin-crates/constraints/src/constraints/table.rs +++ b/pumpkin-crates/constraints/src/constraints/table.rs @@ -1,9 +1,22 @@ +//! Defines the [`table`] and [`negative_table`] constraints. +//! +//! A table constraint restricts a tuple of variables to the rows of a table, and a negative table +//! excludes those rows. +//! Both are decomposed into clauses. +//! The table introduces a row selector for every row, which is a predicate that is true when the +//! variables take the values of that row. + use std::collections::BTreeMap; +use std::collections::BTreeSet; +use std::iter::once; use pumpkin_core::Solver; use pumpkin_core::constraints::Constraint; use pumpkin_core::constraints::NegatableConstraint; +use pumpkin_core::containers::HashMap; +use pumpkin_core::containers::HashSet; use pumpkin_core::predicate; +use pumpkin_core::predicates::Predicate; use pumpkin_core::proof::ConstraintTag; use pumpkin_core::variables::IntegerVariable; use pumpkin_core::variables::Literal; @@ -14,8 +27,9 @@ use pumpkin_core::variables::Literal; /// ```ignore /// (x1, x2, x3) in {(1, 3, 5), (3, 1, 4)} /// ``` -/// This has two solutions: either the first tuple of values is assigned to the variables, or the -/// second. The set of value tuples is the 'table'. +/// This has two solutions. +/// Either the first tuple of values is assigned to the variables, or the second. +/// The set of value tuples is the 'table'. /// /// In the XCSP3 specification, this is the "positive table" /// (). @@ -33,12 +47,12 @@ pub fn table( /// Create the negative [table](https://sofdem.github.io/gccat/gccat/Cin_relation.html#uid22830) [`NegatableConstraint`]. /// -/// A negative table is essentially a set of conflicts over the given variables. For example: +/// A negative table excludes every assignment in which the variables take the values of one of the +/// tuples. For example: /// ```ignore /// (x1, x2, x3) not in {(1, 3, 5), (3, 1, 4)} /// ``` -/// This prevents any solution where the variables have both the first and the second tuple as -/// values. +/// Neither tuple is a solution. /// /// In the XCSP3 specification, this is the "negative table" /// (). @@ -61,57 +75,282 @@ struct Table { } impl Table { - fn encode(self, solver: &mut Solver, reification_literal: Option) { - // 1. Create a variable `y_i` that selects the row from the table which is chosen. - let ys: Vec<_> = (0..self.table.len()) - .map(|_| solver.new_literal()) - .collect(); - - // 2. Setup the implications between values and `ys`. - for (col, x_col) in self.xs.iter().enumerate() { - // A map from domain values to the `ys` variables that support this value. - let mut values = BTreeMap::new(); + /// Posts the decomposition of the table, implied by `reification_literal` if it is given. + /// + /// - The rows that cannot be selected are removed (see [`Self::remove_unselectable_rows`]). + /// - Every remaining row gets a row selector (see [`Self::create_row_selectors`]). + /// - Every column links its variable to the row selectors (see [`Self::encode_column`]). + /// - At least one row selector is true. + fn encode(mut self, solver: &mut Solver, reification_literal: Option) { + // First, we remove the rows that can never be selected, + // and give every remaining row a row selector. + let exclusions_by_column = self.remove_unselectable_rows(solver); + let row_selectors = self.create_row_selectors(solver); + + // Next, we link the variable of every column to the row selectors. + for column in 0..self.xs.len() { + self.encode_column( + solver, + column, + &row_selectors, + &exclusions_by_column, + reification_literal, + ); + } - // For every value in this column, aggregate the `ys` that support it. - for (row, &y_row) in ys.iter().enumerate() { - let value = self.table[row][col]; + // At least one of the remaining rows is selected. + // A row selector can be an assignment of a variable, + // so the clause also contains the exclusions of all removed rows. + // Every column records all of them, so we take them from the first column. + let selected = row_selectors.iter().map(RowSelector::predicate); + let all_exclusions = exclusions_by_column + .first() + .into_iter() + .flat_map(|column_exclusions| column_exclusions.values().flatten().copied()); + self.add_clause_implied_by(solver, selected.chain(all_exclusions), reification_literal); + } - let supports = values.entry(value).or_insert(vec![]); - supports.push(y_row); + /// Removes the rows that cannot be selected, so that they get no row selector and no clauses. + /// + /// - A row with a value outside the domain of its variable is removed. Its exclusion is the + /// predicate that assigns its first such value, which does not hold. For example, the + /// exclusion of the row `[3, 20]` over `[x1, x2]` is `[x1 == 3]` when `x1` is at most 2. + /// - A row equal to an earlier row is removed. + /// + /// Returns, for every column, the exclusions of the rows removed because of a domain, grouped + /// by their value in that column. + fn remove_unselectable_rows(&mut self, solver: &Solver) -> Vec>> { + let mut exclusions_by_column = vec![BTreeMap::>::new(); self.xs.len()]; + let mut kept_rows: HashSet> = HashSet::default(); + + self.table.retain(|row| { + // A row whose values are all in the domains is kept, unless it equals an earlier row. + let Some(exclusion) = self + .xs + .iter() + .zip(row) + .find(|&(x, &value)| !solver.contains(x, value)) + .map(|(x, &value)| predicate![x == value]) + else { + return kept_rows.insert(row.clone()); + }; + + // Otherwise, the row is removed, + // and its exclusion is recorded under its value in every column. + for (column_exclusions, &value) in exclusions_by_column.iter_mut().zip(row) { + column_exclusions.entry(value).or_default().push(exclusion); } + false + }); - // For every value in this column, add the clause - // `condition <-> (\/ supports)` - for (value, supports) in values { - let condition = predicate![x_col == value]; - - // For every `support in supports`: `support -> condition` - for support in supports.iter() { - let mut clause = vec![support.get_false_predicate(), condition]; + exclusions_by_column + } - // Account for possible reification. - // l -> clause - clause.extend(reification_literal.iter().map(|l| l.get_false_predicate())); + /// Creates the row selector of every row. + /// + /// - A row that is the only remaining row with its value in some column is selected exactly + /// when the variable of that column takes that value. Its row selector is that assignment. + /// - Every other row gets a new literal as its row selector. + /// + /// For example, take the rows `[1, 10]`, `[2, 10]` and `[2, 20]` over `[x1, x2]`. + /// The row `[1, 10]` is the only row with `x1 == 1`, so its row selector is `[x1 == 1]`. + /// The row `[2, 20]` is the only row with `x2 == 20`, so its row selector is `[x2 == 20]`. + /// The row `[2, 10]` shares both of its values with another row, so it gets a new literal. + fn create_row_selectors(&self, solver: &mut Solver) -> Vec { + // First, we count the rows with each value, for every column. + let mut row_counts_by_column: Vec> = + vec![HashMap::default(); self.xs.len()]; + for row in &self.table { + for (row_counts, &value) in row_counts_by_column.iter_mut().zip(row) { + *row_counts.entry(value).or_default() += 1; + } + } - solver.add_clause(clause, self.constraint_tag); + // Next, every row gets the assignment of the first column in which its value is unique. + // A row without such a column gets a new literal. + self.table + .iter() + .map(|row| { + match (0..self.xs.len()) + .find(|&column| row_counts_by_column[column][&row[column]] == 1) + { + Some(column) => { + let variable = &self.xs[column]; + let value = row[column]; + RowSelector::Assignment { + column, + value, + predicate: predicate![variable == value], + } + } + None => RowSelector::NewLiteral(solver.new_literal()), } + }) + .collect() + } + + /// Posts the clauses that link the variable of `column` to the row selectors. + /// + /// A row supports a value if it has that value in `column`. + /// - If all rows support the same value, then the variable takes that value. + /// - A selected row assigns its value to the variable. + /// - A value is only assigned when one of the rows that support it is selected. A value that + /// only removed rows have is thereby removed from the domain. + /// + /// The clauses also contain the exclusions in `exclusions_by_column` of the removed rows they + /// rely on. These + /// exclusions do not hold, so they do not change what the clauses propagate. This is necessary + /// for the proof logging. + fn encode_column( + &self, + solver: &mut Solver, + column: usize, + row_selectors: &[RowSelector], + exclusions_by_column: &[BTreeMap>], + reification_literal: Option, + ) { + let variable = &self.xs[column]; + let column_exclusions = &exclusions_by_column[column]; + + // First, we group the row selectors by the value of their row in `column`. + // The row selectors of a value are its supports. + let mut selectors_by_value: BTreeMap> = BTreeMap::new(); + for (row, &row_selector) in self.table.iter().zip(row_selectors) { + selectors_by_value + .entry(row[column]) + .or_default() + .push(row_selector); + } + + // Next, we look at whether only a single value is supported. + // If this is the case, then the variable is assigned that value. + if selectors_by_value.len() == 1 + && let Some((&value, _)) = selectors_by_value.first_key_value() + { + let other_exclusions = column_exclusions + .iter() + .filter(|&(&removed_value, _)| removed_value != value) + .flat_map(|(_, exclusions)| exclusions.iter().copied()); + + self.add_clause_implied_by( + solver, + once(predicate![variable == value]).chain(other_exclusions), + reification_literal, + ); + return; + } - // `condition -> (\/ supports)` - let mut clause = vec![!condition]; - clause.extend(supports.iter().map(|l| l.get_true_predicate())); - // Account for possible reification. - clause.extend(reification_literal.iter().map(|l| l.get_false_predicate())); + // Finally, we link every value of the column to its supports in both directions. + // This includes the values that only removed rows have, which have no supports. + let values: BTreeSet = selectors_by_value + .keys() + .chain(column_exclusions.keys()) + .copied() + .collect(); + for value in values { + let assignment = predicate![variable == value]; + let supports = selectors_by_value + .get(&value) + .map_or(&[][..], Vec::as_slice); + + // A selected row assigns its value to the variable. + // A row selector that is this assignment needs no clause. + // An assignment selector relies on the exclusions of the removed rows with its value. + for support in supports + .iter() + .filter(|support| support.predicate() != assignment) + { + let support_exclusions = support.exclusions(exclusions_by_column); + self.add_clause_implied_by( + solver, + [!support.predicate(), assignment] + .into_iter() + .chain(support_exclusions.iter().copied()), + reification_literal, + ); + } - solver.add_clause(clause, self.constraint_tag); + // The value is only assigned when one of the rows that support it is selected, + // or the exclusion of a removed row with that value holds. + // This clause always holds if a row selector is this assignment, + // or if the value is not in the domain. + let is_own_support = supports + .iter() + .any(|support| support.predicate() == assignment); + if is_own_support || !solver.contains(variable, value) { + continue; } + let value_exclusions = column_exclusions.get(&value).into_iter().flatten().copied(); + self.add_clause_implied_by( + solver, + once(!assignment) + .chain(supports.iter().map(RowSelector::predicate)) + .chain(value_exclusions), + reification_literal, + ); } + } + + /// Adds the clause of `predicates`, extended with the negation of `reification_literal` if it + /// is given. + fn add_clause_implied_by( + &self, + solver: &mut Solver, + predicates: impl IntoIterator, + reification_literal: Option, + ) { + let negated_reification = reification_literal.map(|literal| literal.get_false_predicate()); + solver.add_clause( + predicates.into_iter().chain(negated_reification), + self.constraint_tag, + ); + } +} - // 4. Enforce at least one `y` to be true. - let poster = solver.add_constraint(crate::constraints::clause(ys, self.constraint_tag)); - if let Some(literal) = reification_literal { - poster.implied_by(literal); - } else { - poster.post(); +/// The predicate that is true when a row of the table is selected (see +/// [`Table::create_row_selectors`]). +#[derive(Clone, Copy)] +enum RowSelector { + /// A new literal, introduced for the row. + NewLiteral(Literal), + /// The assignment of `value` to the variable of `column`, in which no other remaining row has + /// `value`. + Assignment { + column: usize, + value: i32, + predicate: Predicate, + }, +} + +impl RowSelector { + fn predicate(&self) -> Predicate { + match self { + RowSelector::NewLiteral(literal) => literal.get_true_predicate(), + RowSelector::Assignment { predicate, .. } => *predicate, + } + } + + /// Returns the exclusions that the row selector relies on. + /// + /// An assignment relies on the row being the only remaining row with `value` in `column`, so it + /// relies on the exclusions of the removed rows with `value` in `column`. + /// + /// For example, take the rows `[1, 10]`, `[1, 30]`, `[2, 30]` and `[3, 10]` over `[x1, x2]`, + /// when `x1` is at most 2. + /// The row `[3, 10]` is removed, and its exclusion is `[x1 == 3]`. + /// The row `[1, 10]` is then the only remaining row with `x2 == 10`, + /// so its row selector is `[x2 == 10]`, which relies on that exclusion. + /// The clause stating that this row assigns `x1 == 1` is therefore + /// `[x2 != 10] \/ [x1 == 1] \/ [x1 == 3]`. + fn exclusions<'a>( + &self, + exclusions_by_column: &'a [BTreeMap>], + ) -> &'a [Predicate] { + match self { + RowSelector::NewLiteral(_) => &[], + RowSelector::Assignment { column, value, .. } => exclusions_by_column[*column] + .get(value) + .map_or(&[], Vec::as_slice), } } } @@ -150,6 +389,8 @@ struct NegativeTable { impl Constraint for NegativeTable { fn post(self, solver: &mut Solver) { + // Every row is excluded by a clause, + // which states that one of the variables differs from its value in the row. for row in self.table { let clause: Vec<_> = self .xs @@ -163,13 +404,14 @@ impl Constraint for NegativeTable { } fn implied_by(self, solver: &mut Solver, reification_literal: Literal) { + // As in `post`, but each clause only holds when `reification_literal` is true. for row in self.table { let clause: Vec<_> = self .xs .iter() .zip(row) .map(|(x, value)| predicate![x != value]) - .chain(std::iter::once(reification_literal.get_false_predicate())) + .chain(once(reification_literal.get_false_predicate())) .collect(); solver.add_clause(clause, self.constraint_tag); @@ -207,9 +449,9 @@ mod tests { let x1 = solver.new_named_bounded_integer(1, 2, "x1"); let x2 = solver.new_named_sparse_integer([10, 20, 30], "x2"); - // Rows 2 and 3 are the only support for `x2 == 30`, and are exactly the rows that support - // `x1 == 2`. Fixing `x1 == 1` should eliminate both of them, which should in turn prune - // `30` from the domain of `x2`. + // Rows 3 and 4 are the only rows that support `x2 == 30` and `x1 == 2`. + // Fixing `x1 == 1` excludes both of them, + // which in turn removes `30` from the domain of `x2`. let rows = vec![vec![1, 10], vec![1, 20], vec![2, 30], vec![2, 30]]; table(vec![x1, x2], rows, constraint_tag).post(&mut solver); @@ -223,4 +465,98 @@ mod tests { assert_eq!(solver.upper_bound(&x2), 20); } + + #[test] + fn rows_that_can_never_be_selected_are_not_encoded() { + let mut solver = Solver::default(); + + let constraint_tag = solver.new_constraint_tag(); + let x1 = solver.new_named_bounded_integer(1, 2, "x1"); + let x2 = solver.new_named_sparse_integer([10, 20, 30], "x2"); + + // Row 2 is a duplicate of row 1. + // Rows 3 and 4 contain a value outside the domain of `x1` and of `x2`. + // The four remaining rows share each of their values with another row, + // so each of them gets a new literal as its row selector. + let rows = vec![ + vec![1, 10], + vec![1, 10], + vec![3, 30], + vec![2, 40], + vec![1, 20], + vec![2, 10], + vec![2, 20], + ]; + let num_domains_before = solver.get_domains().count(); + table(vec![x1, x2], rows, constraint_tag).post(&mut solver); + assert_eq!(solver.get_domains().count(), num_domains_before + 4); + + let result = solver.propagate_to_fixpoint(); + assert_eq!(result, CSPSolverExecutionFlag::Feasible); + assert!(!solver.contains(&x2, 30)); + } + + #[test] + fn row_with_a_unique_value_is_selected_by_its_assignment() { + let mut solver = Solver::default(); + + let constraint_tag = solver.new_constraint_tag(); + let reification_literal = solver.new_literal(); + let x1 = solver.new_named_bounded_integer(1, 2, "x1"); + let x2 = solver.new_named_sparse_integer([10, 20], "x2"); + + // Row 1 is the only row with `x1 == 1`, and row 3 the only row with `x2 == 20`. + // Only row 2 gets a new literal as its row selector. + let rows = vec![vec![1, 10], vec![2, 10], vec![2, 20]]; + let num_domains_before = solver.get_domains().count(); + table(vec![x1, x2], rows, constraint_tag).implied_by(&mut solver, reification_literal); + assert_eq!(solver.get_domains().count(), num_domains_before + 1); + + solver.add_clause([predicate![x2 == 20]], constraint_tag); + let result = solver.propagate_to_fixpoint(); + assert_eq!(result, CSPSolverExecutionFlag::Feasible); + assert_eq!(solver.lower_bound(&x1), 1); + + solver.add_clause([reification_literal.get_true_predicate()], constraint_tag); + let result = solver.propagate_to_fixpoint(); + assert_eq!(result, CSPSolverExecutionFlag::Feasible); + assert_eq!(solver.lower_bound(&x1), 2); + } + + #[test] + fn column_with_a_single_remaining_value_is_fixed_when_reification_holds() { + let mut solver = Solver::default(); + + let constraint_tag = solver.new_constraint_tag(); + let reification_literal = solver.new_literal(); + let x1 = solver.new_named_bounded_integer(1, 2, "x1"); + let x2 = solver.new_named_sparse_integer([10, 20, 30], "x2"); + + // After removing the row with `x1 == 3`, every row has `x2 == 10`. + let rows = vec![vec![1, 10], vec![2, 10], vec![3, 20]]; + table(vec![x1, x2], rows, constraint_tag).implied_by(&mut solver, reification_literal); + + let result = solver.propagate_to_fixpoint(); + assert_eq!(result, CSPSolverExecutionFlag::Feasible); + assert_eq!(solver.upper_bound(&x2), 30); + + solver.add_clause([reification_literal.get_true_predicate()], constraint_tag); + + let result = solver.propagate_to_fixpoint(); + assert_eq!(result, CSPSolverExecutionFlag::Feasible); + assert_eq!(solver.lower_bound(&x2), 10); + assert_eq!(solver.upper_bound(&x2), 10); + } + + #[test] + fn table_without_selectable_rows_is_infeasible() { + let mut solver = Solver::default(); + + let constraint_tag = solver.new_constraint_tag(); + let x1 = solver.new_named_bounded_integer(1, 2, "x1"); + + table(vec![x1], vec![vec![3], vec![4]], constraint_tag).post(&mut solver); + + assert!(solver.is_inconsistent()); + } }