Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions docs/paper/reductions.typ
Original file line number Diff line number Diff line change
Expand Up @@ -14926,6 +14926,72 @@ The following reductions to Integer Linear Programming are straightforward formu
vertices as a Boolean vector. Target feasibility maps to the source Boolean value.
]

#let sat_ilp = load-example("Satisfiability", "ILP")
#let sat_ilp_sol = sat_ilp.solutions.at(0)
#reduction-rule("Satisfiability", "ILP",
example: true,
example-caption: [One binary variable per SAT variable and one inequality per clause],
extra: [
#pred-commands(
"pred create --example " + rule-spec(sat_ilp) + " -o sat.json",
"pred path " + problem-spec(sat_ilp.source) + " " + problem-spec(sat_ilp.target) + " --limit 1 -o paths.json",
"jq '.paths[0]' paths.json > route.json",
"pred reduce sat.json --via route.json -o bundle.json",
"pred solve bundle.json",
"pred evaluate sat.json --config " + cli-config(sat_ilp_sol.source_config),
)

The source clauses, given as signed literal lists, are
#sat_ilp.source.instance.clauses.map(c => [$(#fmt-values(c.literals))$]).join(", ").
They produce #sat_ilp.target.instance.variables.len() binary variables and
#sat_ilp.target.instance.constraints.len() rows. At the stored ILP witness
$(#fmt-values(sat_ilp_sol.target_config))$, the rows evaluate to
#sat_ilp.target.instance.constraints.map(row => {
let lhs = row.terms.fold(0, (sum, (i, c)) => sum + c * sat_ilp_sol.target_config.at(i))
$#lhs >= #row.rhs$
}).join(", ").
Reading each bit as a truth value gives the satisfying assignment
$(#fmt-values(sat_ilp_sol.source_config))$.
Appending an empty clause adds the row $0 >= 1$, making the ILP infeasible.
],
)[
Encode CNF satisfiability directly with one binary variable per Boolean variable
and one inequality per clause. The encoding follows from the truth values of
the literal occurrences.
][
_Construction._ (1) Introduce a binary variable $x_i$ for each source variable
$i$. (2) For each clause $C$, let $P$ and $N$ list the variable indices of its
positive and negative literal occurrences, respectively. Add
$ sum_(i in P) x_i - sum_(j in N) x_j >= 1 - |N|. $
The ILP sums coefficients of repeated variables and removes zero coefficients.
Use an empty minimization objective.

_Correctness._ ($arrow.r.double$) A satisfying assignment makes at least one
occurrence true in each clause. A positive occurrence contributes $x_i$ to
this count and a negative one contributes $1-x_i$. Moving the constant terms
to the right gives the clause row, which the assignment therefore satisfies.
($arrow.l.double$) In a feasible binary assignment, a clause with every
literal false would have left-hand side $-|N|$, violating its row. Thus each
clause is true under the corresponding Boolean assignment.

Repeated literals contribute according to their multiplicities.
Opposite occurrences of the same variable contribute a total of
one true literal, so any row containing such a pair is redundant, even if other
terms survive normalization. An empty clause gives the impossible row
$0 >= 1$, making the entire formula infeasible. A formula with no clauses gives
no rows and every binary assignment is feasible.

_Overhead._ For $n$ variables, $m$ clauses, and $L$ literal occurrences,
the target has exactly $n$ variables and $m$ rows. Each occurrence contributes
at most one nonzero after normalization, giving at most $L$ nonzeros. The
magnitudes of coefficients, right-hand sides, and binary endpoints are at
most $L+1$, so $L+1$ magnitude bits suffice since $L+1 < 2^(L+1)$.

_Solution extraction._ Validate that the target assignment is feasible and
read each $x_i = 1$ as true. Completed ILP feasibility maps to the source
Boolean value.
]

#reduction-rule("NAESatisfiability", "ILP")[
Each clause must have at least one true and at least one false literal, encoded as a pair of linear inequalities per clause.
][
Expand Down
6 changes: 1 addition & 5 deletions src/models/graph/minimum_edge_cost_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,11 +288,7 @@ impl MinimumEdgeCostFlow {
}

// (3) Flow requirement: net flow into sink >= R
if balance[self.sink] < self.required_flow {
return Ok(false);
}

Ok(true)
Ok(balance[self.sink] >= self.required_flow)
}

/// Compute the edge cost for a feasible flow: sum of prices of arcs with
Expand Down
6 changes: 1 addition & 5 deletions src/models/misc/minimum_register_sufficiency_for_loops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,7 @@ impl MinimumRegisterSufficiencyForLoops {
// Check if arc1 is entirely in the gap of arc2.
let gap2_start = (s2 + l2) % n;
let dist_s1_in_gap2 = (s1 + n - gap2_start) % n;
if dist_s1_in_gap2 + l1 <= n - l2 {
return false;
}

true
dist_s1_in_gap2 + l1 > n - l2
}
}

Expand Down
21 changes: 4 additions & 17 deletions src/models/misc/rectilinear_picture_compression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,25 +203,12 @@ impl RectilinearPictureCompression {
continue;
}
// Find the rightmost column from c1 that is all-1 in row r1.
let mut c_max = n;
for c in c1..n {
if !self.matrix[r1][c] {
c_max = c;
break;
}
}
let c_max = (c1..n).find(|&c| !self.matrix[r1][c]).unwrap_or(n);
// Extend downward row by row, narrowing column range.
let mut c_end = c_max; // exclusive upper bound on columns
for r2 in r1..m {
// Narrow c_end based on row r2.
let mut new_c_end = c1;
for c in c1..c_end {
if self.matrix[r2][c] {
new_c_end = c + 1;
} else {
break;
}
}
for (r2, row) in self.matrix.iter().enumerate().skip(r1) {
// Narrow c_end based on this row.
let new_c_end = (c1..c_end).find(|&c| !row[c]).unwrap_or(c_end);
if new_c_end <= c1 {
break;
}
Expand Down
8 changes: 2 additions & 6 deletions src/rules/ksatisfiability_preemptivescheduling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,17 +277,13 @@ fn construct_schedule_from_assignment(
if pattern == 0 {
return None;
}
for pattern_index in 0..7 {
for (pattern_index, &job) in construction.clause_jobs[clause_index].iter().enumerate() {
let slot = if pattern_index + 1 == pattern {
source.num_vars() + 1
} else {
source.num_vars() + 2
};
set_task_slot(
&mut task_slots,
construction.clause_jobs[clause_index][pattern_index],
slot,
);
set_task_slot(&mut task_slots, job, slot);
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ pub(crate) mod registersufficiency_ilp;
pub(crate) mod resourceconstrainedscheduling_ilp;
pub(crate) mod rootedtreestorageassignment_ilp;
pub(crate) mod ruralpostman_ilp;
pub(crate) mod satisfiability_ilp;
pub(crate) mod schedulingtominimizeweightedcompletiontime_ilp;
pub(crate) mod schedulingwithindividualdeadlines_ilp;
pub(crate) mod sequencingtominimizemaximumcumulativecost_ilp;
Expand Down Expand Up @@ -656,6 +657,7 @@ pub(crate) fn canonical_rule_example_specs() -> Vec<crate::example_db::specs::Ru
specs.extend(resourceconstrainedscheduling_ilp::canonical_rule_example_specs());
specs.extend(rootedtreestorageassignment_ilp::canonical_rule_example_specs());
specs.extend(ruralpostman_ilp::canonical_rule_example_specs());
specs.extend(satisfiability_ilp::canonical_rule_example_specs());
specs
.extend(schedulingtominimizeweightedcompletiontime_ilp::canonical_rule_example_specs());
specs.extend(schedulingwithindividualdeadlines_ilp::canonical_rule_example_specs());
Expand Down
102 changes: 102 additions & 0 deletions src/rules/satisfiability_ilp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
//! One binary variable per SAT variable and one inequality per clause.

use crate::models::algebraic::{ILP, LinearConstraint, ObjectiveSense};
use crate::models::formula::Satisfiability;
use crate::reduction;
use crate::rules::traits::{ReduceTo, ReductionResult};
use crate::rules::{ExtractionResult, ReductionError};

#[derive(Debug, Clone)]
pub struct ReductionSATToILP {
target: ILP<bool>,
}

impl ReductionResult for ReductionSATToILP {
type Source = Satisfiability;
type Target = ILP<bool>;

fn target_problem(&self) -> &Self::Target {
&self.target
}

fn extract_solution(&self, solution: &Vec<i64>) -> ExtractionResult<Vec<bool>> {
crate::rules::traits::validate_target_witness(
self.target_problem(),
solution,
|value| value.value.is_some(),
"target ILP assignment is infeasible",
)?;
Ok(solution.iter().map(|&value| value == 1).collect())
}
}

#[crate::aggregate_reduction(ilp_feasibility)]
impl crate::rules::AggregateReductionResult for ReductionSATToILP {}

#[reduction(transform = {
exact {
num_vars = "num_vars",
num_constraints = "num_clauses",
},
upper_bound {
num_nonzeros = "num_literals",
max_constraint_magnitude_bits = "num_literals + 1",
},
})]
impl ReduceTo<ILP<bool>> for Satisfiability {
type Result = ReductionSATToILP;

fn reduce_to(&self) -> Result<Self::Result, ReductionError> {
let mut constraints = Vec::with_capacity(self.num_clauses());
for clause in self.clauses() {
let negatives = clause
.literals
.iter()
.filter(|&&literal| literal < 0)
.count();
let negatives = <Self as ReduceTo<ILP<bool>>>::exact_i64(
negatives,
"counting negative clause literals",
)?;
// ILP normalization merges duplicate terms and cancels opposite terms.
let terms = clause
.variables()
.into_iter()
.zip(clause.literals.iter().map(|literal| literal.signum()))
.collect();
constraints.push(LinearConstraint::ge(terms, 1 - negatives));
}
let target = ILP::new(
self.num_vars(),
constraints,
vec![],
ObjectiveSense::Minimize,
)
.map_err(<Self as ReduceTo<ILP<bool>>>::target_construction)?;
Ok(Self::Result { target })
}
}

#[cfg(feature = "example-db")]
pub(crate) fn canonical_rule_example_specs() -> Vec<crate::example_db::specs::RuleExampleSpec> {
use crate::models::formula::CNFClause;
vec![crate::example_db::specs::RuleExampleSpec {
id: "satisfiability_to_ilp",
build: || {
let source = Satisfiability::new(
3,
vec![
CNFClause::new(vec![1, 2, 2]),
CNFClause::new(vec![-1, 3]),
CNFClause::new(vec![-2, -3]),
CNFClause::new(vec![1, -1]),
],
);
crate::example_db::specs::rule_example_via_ilp::<_, bool>(source)
},
}]
}

#[cfg(test)]
#[path = "../unit_tests/rules/satisfiability_ilp.rs"]
mod tests;
23 changes: 11 additions & 12 deletions src/rules/unitdiskmapping/grid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,9 @@ impl MappingGrid {
/// Get all occupied coordinates.
pub fn occupied_coords(&self) -> Vec<(usize, usize)> {
let mut coords = Vec::new();
for r in 0..self.rows {
for c in 0..self.cols {
if self.content[r][c].is_occupied() {
for (r, row) in self.content.iter().enumerate() {
for (c, cell) in row.iter().enumerate() {
if cell.is_occupied() {
coords.push((r, c));
}
}
Expand All @@ -200,9 +200,9 @@ impl MappingGrid {
/// Returns a set of (row, col) for cells in the Doubled state.
pub fn doubled_cells(&self) -> std::collections::HashSet<(usize, usize)> {
let mut cells = std::collections::HashSet::new();
for r in 0..self.rows {
for c in 0..self.cols {
if matches!(self.content[r][c], CellState::Doubled { .. }) {
for (r, row) in self.content.iter().enumerate() {
for (c, cell) in row.iter().enumerate() {
if matches!(cell, CellState::Doubled { .. }) {
cells.insert((r, c));
}
}
Expand Down Expand Up @@ -250,9 +250,9 @@ impl MappingGrid {
let pos_to_idx: HashMap<(usize, usize), usize> = if config.is_some() {
let mut map = HashMap::new();
let mut idx = 0;
for r in 0..self.rows {
for c in 0..self.cols {
if self.content[r][c].is_occupied() {
for (r, row) in self.content.iter().enumerate() {
for (c, cell) in row.iter().enumerate() {
if cell.is_occupied() {
map.insert((r, c), idx);
idx += 1;
}
Expand All @@ -265,10 +265,9 @@ impl MappingGrid {

let mut lines = Vec::new();

for r in 0..self.rows {
for (r, row) in self.content.iter().enumerate() {
let mut line = String::new();
for c in 0..self.cols {
let cell = &self.content[r][c];
for (c, cell) in row.iter().enumerate() {
let s = if let Some(cfg) = config {
if let Some(&idx) = pos_to_idx.get(&(r, c)) {
if cfg.get(idx).copied().unwrap_or(0) > 0 {
Expand Down
2 changes: 0 additions & 2 deletions src/solvers/pipelines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,6 @@ register_ilp_pipeline! {
register_ilp_pipeline! {
("KSatisfiability", [("k", "K3")]),
("Satisfiability", []),
("NAESatisfiability", []),
("ILP", [("variable", "bool"), ("coefficient", "i64"), ("bounds", "general")]),
}

Expand Down Expand Up @@ -724,7 +723,6 @@ register_ilp_pipeline! {

register_ilp_pipeline! {
("Satisfiability", []),
("NAESatisfiability", []),
("ILP", [("variable", "bool"), ("coefficient", "i64"), ("bounds", "general")]),
}

Expand Down
41 changes: 41 additions & 0 deletions src/unit_tests/parameter_formula_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,47 @@ fn every_executable_parameter_formula_matches_a_constructed_target() {
assert_eq!(checked, expected, "some formula fields were not checked");
}

#[test]
fn sat_clause_rows_match_their_parameter_transform() {
use crate::models::algebraic::ILP;
use crate::models::formula::{CNFClause, Satisfiability};
use crate::traits::Problem;

let entry = crate::rules::registry::reduction_entries()
.into_iter()
.find(|entry| {
entry.source_name == Satisfiability::NAME
&& entry.target_name == ILP::<bool>::NAME
&& entry.target_variant() == ILP::<bool>::variant()
})
.unwrap();
let contract = entry.parameter_contract().unwrap();
let transform = contract.transform().unwrap();
for (n, clauses) in [
(0, vec![]),
(0, vec![vec![]]),
(4, vec![vec![1, -1], vec![-2, -2, -2, -2], vec![3, 4]]),
] {
let source = Satisfiability::new(n, clauses.into_iter().map(CNFClause::new).collect());
let predicted = transform.evaluate(&source.parameters()).unwrap();
let actual = target_parameters(entry, &source).unwrap();
for field in ["num_vars", "num_constraints"] {
assert_eq!(transform.relation(field), Some(ParameterRelation::Exact));
assert_eq!(predicted.get(field).unwrap(), actual.get(field).unwrap());
}
for field in ["num_nonzeros", "max_constraint_magnitude_bits"] {
assert_eq!(
transform.relation(field),
Some(ParameterRelation::UpperBound)
);
assert!(
predicted.get(field).unwrap() >= actual.get(field).unwrap(),
"{field}"
);
}
}
}

#[test]
fn sparse_ilp_predictions_use_construction_counts() {
use crate::models::{BiconnectivityAugmentation, Factoring, StrongConnectivityAugmentation};
Expand Down
Loading
Loading