Skip to content

Commit ecc0ad5

Browse files
committed
Add verified Phase 2 direct QUBO reductions
1 parent 37aa878 commit ecc0ad5

25 files changed

Lines changed: 1735 additions & 29 deletions

‎docs/paper/reductions.typ‎

Lines changed: 186 additions & 0 deletions
Large diffs are not rendered by default.

‎problemreductions-cli/tests/cli_tests.rs‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ fn path_text_preserves_variant_conversion_steps() {
5151

5252
#[test]
5353
fn polynomial_comparison_default_layout_and_opt_in_proofs() {
54-
let args = ["path", "MIS", "QUBO", "--compare", "--limit", "3"];
54+
// The feedback-arc route adds a quadratic-size candidate; retain both equivalent set-packing routes.
55+
let args = ["path", "MIS", "QUBO", "--compare", "--limit", "4"];
5556
let output = pred().args(args).output().unwrap();
5657
assert!(output.status.success());
5758
let text = String::from_utf8(output.stdout).unwrap();
@@ -63,14 +64,14 @@ fn polynomial_comparison_default_layout_and_opt_in_proofs() {
6364
assert!(text.contains("Path 1") && text.contains("num_vars"));
6465
assert!(!text.contains("[upper bound]") && !text.contains("[exact]"));
6566
assert!(text[pairs..unresolved]
66-
.contains("0 dominated, 1 equivalent, 2 proven incomparable, 0 unresolved"));
67+
.contains("1 dominated, 1 equivalent, 4 proven incomparable, 0 unresolved"));
6768
assert!(!text.contains("worst case:") && !text.contains("Generic candidate front"));
6869
assert!(text.contains("Paths 1, 2: proven incomparable"));
69-
assert!(text.contains("Paths 2, 3: Path 2 ≡ Path 3"));
70+
assert!(text.contains("Paths 2, 4: Path 2 ≡ Path 4"));
7071
assert!(
7172
text.contains("Ignores exact-cancellation families") && text.contains("bounded strata")
7273
);
73-
assert!(text.contains("2 proven incomparable, 0 unresolved"));
74+
assert!(text.contains("4 proven incomparable, 0 unresolved"));
7475
assert!(
7576
!text.contains("Field proofs") && !text.contains("Witness {") && !text.contains("f/g → ∞")
7677
);
@@ -80,7 +81,7 @@ fn polynomial_comparison_default_layout_and_opt_in_proofs() {
8081
let text = String::from_utf8(output.stdout).unwrap();
8182
assert!(
8283
text.contains("Paths 1, 2: proven incomparable")
83-
&& text.contains("Paths 2, 3: Path 2 ≡ Path 3")
84+
&& text.contains("Paths 2, 4: Path 2 ≡ Path 4")
8485
);
8586
assert!(text.contains("Field proofs") && text.contains("f/g → ∞"));
8687
assert!(text.contains("f ≡ g after expansion"));
@@ -92,14 +93,14 @@ fn polynomial_comparison_default_layout_and_opt_in_proofs() {
9293
let view = &json["polynomial_comparison"];
9394
assert_eq!(view["schema_version"], 5);
9495
assert_eq!(view["mode"], "generic");
95-
assert_eq!(view["counts"]["Incomparable"], 2);
96+
assert_eq!(view["counts"]["Incomparable"], 4);
9697
assert!(view.get("generic_counts").is_none());
9798
assert!(view.get("generic_candidate_front").is_none());
9899
assert!(view["pairs"][0]["fields"]["num_vars"]["forward"]["certificate"].is_object());
99-
let identity = &view["pairs"][2]["fields"]["num_vars"]["forward"]["certificate"];
100+
let identity = &view["pairs"][4]["fields"]["num_vars"]["forward"]["certificate"];
100101
assert_eq!(identity["kind"], "identity");
101102
assert_eq!(identity.as_object().unwrap().len(), 1);
102-
assert!(view["pairs"][2]["fields"]["num_vars"]
103+
assert!(view["pairs"][4]["fields"]["num_vars"]
103104
.get("generic")
104105
.is_none());
105106
let output = pred()

‎src/models/misc/stacker_crane.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ impl StackerCrane {
250250
true
251251
}
252252

253-
fn mixed_graph_adjacency(&self) -> Vec<Vec<(usize, i64)>> {
253+
pub(crate) fn mixed_graph_adjacency(&self) -> Vec<Vec<(usize, i64)>> {
254254
let mut adjacency = vec![Vec::new(); self.num_vertices];
255255

256256
for (&(tail, head), &length) in self.arcs.iter().zip(&self.arc_lengths) {
@@ -265,7 +265,7 @@ impl StackerCrane {
265265
adjacency
266266
}
267267

268-
fn shortest_path_length(
268+
pub(crate) fn shortest_path_length(
269269
&self,
270270
adjacency: &[Vec<(usize, i64)>],
271271
source: usize,

‎src/rules/cyclicordering_ilp.rs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,12 @@ impl ReduceTo<ILP<i64, i64, Bounded>> for CyclicOrdering {
5555
"counting cyclic-ordering variables",
5656
)
5757
})?;
58-
let bound = Self::exact_i64(n, "bounding ordering ranks")?;
58+
let bound =
59+
<Self as ReduceTo<ILP<i64, i64, Bounded>>>::exact_i64(n, "bounding ordering ranks")?;
5960
let mut variables = vec![
60-
IntegerVariable::new(Some(0), Some(bound - 1))
61-
.map_err(Self::target_construction)?;
61+
IntegerVariable::new(Some(0), Some(bound - 1)).map_err(
62+
<Self as ReduceTo<ILP<i64, i64, Bounded>>>::target_construction
63+
)?;
6264
n
6365
];
6466
variables.resize(count, IntegerVariable::binary());
@@ -74,7 +76,7 @@ impl ReduceTo<ILP<i64, i64, Bounded>> for CyclicOrdering {
7476
));
7577
}
7678
let target = ILP::with_variables(variables, constraints, vec![], ObjectiveSense::Minimize)
77-
.map_err(Self::target_construction)?;
79+
.map_err(<Self as ReduceTo<ILP<i64, i64, Bounded>>>::target_construction)?;
7880
crate::rules::ilp_helpers::validate_bounded_constraint_arithmetic::<Self>(&target)?;
7981
Ok(Self::Result {
8082
target,

‎src/rules/cyclicordering_qubo.rs‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
//! Direct exact integer encoding of CyclicOrdering.
2+
use crate::models::algebraic::QUBO;
3+
use crate::models::decision::Decision;
4+
use crate::models::misc::CyclicOrdering;
5+
use crate::rules::qubo_helpers::QuboBuilder;
6+
use crate::rules::qubo_helpers::{pair_index, tournament_ranks};
7+
use crate::rules::traits::validate_target_witness;
8+
use crate::rules::{ExtractionResult, ReduceTo, ReductionError, ReductionResult};
9+
#[derive(Debug, Clone)]
10+
pub struct ReductionCyclicOrderingToQUBO {
11+
target: Decision<QUBO<i64>>,
12+
size: usize,
13+
}
14+
impl ReductionResult for ReductionCyclicOrderingToQUBO {
15+
type Source = CyclicOrdering;
16+
type Target = Decision<QUBO<i64>>;
17+
fn target_problem(&self) -> &Self::Target {
18+
&self.target
19+
}
20+
fn extract_solution(
21+
&self,
22+
bits: &Vec<bool>,
23+
) -> ExtractionResult<<Self::Source as crate::Problem>::Solution> {
24+
validate_target_witness(
25+
&self.target,
26+
bits,
27+
|v| v.0,
28+
"QUBO does not certify a source witness",
29+
)?;
30+
tournament_ranks(self.size, bits)
31+
}
32+
}
33+
#[crate::aggregate_reduction(identity)]
34+
impl crate::rules::AggregateReductionResult for ReductionCyclicOrderingToQUBO {}
35+
#[crate::reduction(transform = { exact { num_vars = "num_elements * (num_elements - 1) / 2" }, upper_bound { num_quadratic_terms = "(num_elements * (num_elements - 1) / 2)^2" } })]
36+
impl ReduceTo<Decision<QUBO<i64>>> for CyclicOrdering {
37+
type Result = ReductionCyclicOrderingToQUBO;
38+
fn reduce_to(&self) -> Result<Self::Result, ReductionError> {
39+
type Builder = QuboBuilder<CyclicOrdering, Decision<QUBO<i64>>>;
40+
let n = self.num_elements();
41+
let mut q = Builder::new(Builder::dimension(n, n.saturating_sub(1))? / 2);
42+
q.tournament(n, &[], 1)?;
43+
for &(a, b, c) in self.triples() {
44+
let mut terms = Vec::with_capacity(3);
45+
let mut required = 2;
46+
for (i, j) in [(a, b), (b, c), (c, a)] {
47+
if i < j {
48+
terms.push((pair_index(n, i, j), 1));
49+
} else {
50+
terms.push((pair_index(n, j, i), -1));
51+
required -= 1;
52+
}
53+
}
54+
q.affine_square(&terms, required)?;
55+
}
56+
let (target, constant) = q.finish()?;
57+
let bound = constant.checked_neg().ok_or_else(Builder::overflow)?;
58+
Ok(ReductionCyclicOrderingToQUBO {
59+
target: Decision::new(target, bound),
60+
size: n,
61+
})
62+
}
63+
}
64+
#[cfg(feature = "example-db")]
65+
pub(crate) fn canonical_rule_example_specs() -> Vec<crate::example_db::specs::RuleExampleSpec> {
66+
vec![crate::example_db::specs::RuleExampleSpec {
67+
id: "cyclicordering_qubo",
68+
build: || {
69+
crate::example_db::specs::rule_example_with_witness::<_, Decision<QUBO<i64>>>(
70+
CyclicOrdering::new(3, vec![(0, 1, 2)]),
71+
crate::export::SolutionPair {
72+
source_config: serde_json::json!([0, 1, 2]),
73+
target_config: serde_json::json!([true, true, true]),
74+
},
75+
)
76+
},
77+
}]
78+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
//! Direct exact integer encoding of ExactCoverBy3Sets.
2+
use crate::models::algebraic::QUBO;
3+
use crate::models::decision::Decision;
4+
use crate::models::set::ExactCoverBy3Sets;
5+
use crate::rules::qubo_helpers::QuboBuilder;
6+
use crate::rules::traits::validate_target_witness;
7+
use crate::rules::{ExtractionResult, ReduceTo, ReductionError, ReductionResult};
8+
9+
#[derive(Debug, Clone)]
10+
pub struct ReductionExactCoverBy3SetsToQUBO {
11+
target: Decision<QUBO<i64>>,
12+
}
13+
impl ReductionResult for ReductionExactCoverBy3SetsToQUBO {
14+
type Source = ExactCoverBy3Sets;
15+
type Target = Decision<QUBO<i64>>;
16+
fn target_problem(&self) -> &Self::Target {
17+
&self.target
18+
}
19+
fn extract_solution(
20+
&self,
21+
bits: &Vec<bool>,
22+
) -> ExtractionResult<<Self::Source as crate::Problem>::Solution> {
23+
validate_target_witness(
24+
&self.target,
25+
bits,
26+
|v| v.0,
27+
"QUBO does not certify a source witness",
28+
)?;
29+
Ok(bits.clone())
30+
}
31+
}
32+
#[crate::aggregate_reduction(identity)]
33+
impl crate::rules::AggregateReductionResult for ReductionExactCoverBy3SetsToQUBO {}
34+
#[crate::reduction(transform = { exact { num_vars = "num_subsets" }, upper_bound { num_quadratic_terms = "(num_subsets)^2" } })]
35+
impl ReduceTo<Decision<QUBO<i64>>> for ExactCoverBy3Sets {
36+
type Result = ReductionExactCoverBy3SetsToQUBO;
37+
fn reduce_to(&self) -> Result<Self::Result, ReductionError> {
38+
type Builder = QuboBuilder<ExactCoverBy3Sets, Decision<QUBO<i64>>>;
39+
let mut q = Builder::new(self.num_subsets());
40+
for u in 0..self.universe_size() {
41+
let bits = self
42+
.subsets()
43+
.iter()
44+
.enumerate()
45+
.filter_map(|(j, t)| t.contains(&u).then_some(j))
46+
.collect::<Vec<_>>();
47+
q.square(&bits, 1, 1)?;
48+
}
49+
let (target, constant) = q.finish()?;
50+
let bound = constant.checked_neg().ok_or_else(Builder::overflow)?;
51+
Ok(ReductionExactCoverBy3SetsToQUBO {
52+
target: Decision::new(target, bound),
53+
})
54+
}
55+
}
56+
#[cfg(feature = "example-db")]
57+
pub(crate) fn canonical_rule_example_specs() -> Vec<crate::example_db::specs::RuleExampleSpec> {
58+
vec![crate::example_db::specs::RuleExampleSpec {
59+
id: "exactcoverby3sets_qubo",
60+
build: || {
61+
crate::example_db::specs::rule_example_with_witness::<_, Decision<QUBO<i64>>>(
62+
ExactCoverBy3Sets::new(6, vec![[0, 1, 2], [3, 4, 5], [0, 3, 4]]),
63+
crate::export::SolutionPair {
64+
source_config: serde_json::json!([true, true, false]),
65+
target_config: serde_json::json!([true, true, false]),
66+
},
67+
)
68+
},
69+
}]
70+
}
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
//! Direct exact integer encoding of GroupingBySwapping.
2+
use crate::models::algebraic::QUBO;
3+
use crate::models::decision::Decision;
4+
use crate::models::misc::GroupingBySwapping;
5+
use crate::rules::qubo_helpers::QuboBuilder;
6+
use crate::rules::qubo_helpers::{pair_index, tournament_ranks};
7+
use crate::rules::traits::validate_target_witness;
8+
use crate::rules::{ExtractionResult, ReduceTo, ReductionError, ReductionResult};
9+
#[derive(Debug, Clone)]
10+
pub struct ReductionGroupingBySwappingToQUBO {
11+
target: Decision<QUBO<i64>>,
12+
source: GroupingBySwapping,
13+
}
14+
impl ReductionResult for ReductionGroupingBySwappingToQUBO {
15+
type Source = GroupingBySwapping;
16+
type Target = Decision<QUBO<i64>>;
17+
fn target_problem(&self) -> &Self::Target {
18+
&self.target
19+
}
20+
fn extract_solution(
21+
&self,
22+
bits: &Vec<bool>,
23+
) -> ExtractionResult<<Self::Source as crate::Problem>::Solution> {
24+
validate_target_witness(
25+
&self.target,
26+
bits,
27+
|v| v.0,
28+
"QUBO does not certify a source witness",
29+
)?;
30+
let ranks = tournament_ranks(self.source.alphabet_size(), bits)?;
31+
let mut string = self.source.string().to_vec();
32+
let mut swaps = Vec::new();
33+
for i in 1..string.len() {
34+
let mut j = i;
35+
while j > 0 && ranks[string[j - 1]] > ranks[string[j]] {
36+
string.swap(j - 1, j);
37+
swaps.push(j - 1);
38+
j -= 1;
39+
}
40+
}
41+
if swaps.len() > self.source.budget() {
42+
return Err(crate::rules::ExtractionError::invalid(
43+
"inversion count exceeds the swap budget",
44+
));
45+
}
46+
if !string.is_empty() {
47+
swaps.resize(self.source.budget(), string.len() - 1);
48+
}
49+
Ok(swaps)
50+
}
51+
}
52+
#[crate::aggregate_reduction(identity)]
53+
impl crate::rules::AggregateReductionResult for ReductionGroupingBySwappingToQUBO {}
54+
#[crate::reduction(transform = { exact { num_vars = "alphabet_size * (alphabet_size - 1) / 2" }, upper_bound { num_quadratic_terms = "alphabet_size * (alphabet_size - 1) * (alphabet_size - 2) / 2" } })]
55+
impl ReduceTo<Decision<QUBO<i64>>> for GroupingBySwapping {
56+
type Result = ReductionGroupingBySwappingToQUBO;
57+
fn reduce_to(&self) -> Result<Self::Result, ReductionError> {
58+
type Builder = QuboBuilder<GroupingBySwapping, Decision<QUBO<i64>>>;
59+
let n = self.alphabet_size();
60+
let mut q = Builder::new(Builder::dimension(n, n.saturating_sub(1))? / 2);
61+
for (p, &i) in self.string().iter().enumerate() {
62+
for &j in &self.string()[p + 1..] {
63+
if i < j {
64+
q.add_constant(1)?;
65+
let v = pair_index(n, i, j);
66+
q.add(v, v, -1)?;
67+
} else if i > j {
68+
let v = pair_index(n, j, i);
69+
q.add(v, v, 1)?;
70+
}
71+
}
72+
}
73+
let max_swaps =
74+
Builder::dimension(self.string_len(), self.string_len().saturating_sub(1))? / 2;
75+
let budget =
76+
i64::try_from(self.budget().min(max_swaps)).map_err(|_| Builder::overflow())?;
77+
let max_swaps = i64::try_from(max_swaps).map_err(|_| Builder::overflow())?;
78+
q.tournament(
79+
n,
80+
&[],
81+
max_swaps.checked_add(1).ok_or_else(Builder::overflow)?,
82+
)?;
83+
let (target, constant) = q.finish()?;
84+
let bound = budget.checked_sub(constant).ok_or_else(Builder::overflow)?;
85+
Ok(ReductionGroupingBySwappingToQUBO {
86+
target: Decision::new(target, bound),
87+
source: self.clone(),
88+
})
89+
}
90+
}
91+
#[cfg(feature = "example-db")]
92+
pub(crate) fn canonical_rule_example_specs() -> Vec<crate::example_db::specs::RuleExampleSpec> {
93+
vec![crate::example_db::specs::RuleExampleSpec {
94+
id: "groupingbyswapping_qubo",
95+
build: || {
96+
crate::example_db::specs::rule_example_with_witness::<_, Decision<QUBO<i64>>>(
97+
GroupingBySwapping::new(3, vec![0, 1, 2, 0], 2),
98+
crate::export::SolutionPair {
99+
source_config: serde_json::json!([2, 1]),
100+
target_config: serde_json::json!([true, true, true]),
101+
},
102+
)
103+
},
104+
}]
105+
}

‎src/rules/minimumfeedbackarcset_ilp.rs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,10 @@ impl ReduceTo<ILP<i64, i64, Bounded>> for MinimumFeedbackArcSet<i64> {
7878
// o_v = m + v (integer: topological order of vertex v)
7979

8080
let mut constraints = Vec::new();
81-
let n_i64 = Self::exact_i64(n, "encoding the topological order")?;
81+
let n_i64 = <Self as ReduceTo<ILP<i64, i64, Bounded>>>::exact_i64(
82+
n,
83+
"encoding the topological order",
84+
)?;
8285

8386
// Binary bounds: y_a <= 1 for a in 0..m
8487
for a in 0..m {
@@ -113,12 +116,12 @@ impl ReduceTo<ILP<i64, i64, Bounded>> for MinimumFeedbackArcSet<i64> {
113116
let mut variables = vec![IntegerVariable::binary(); num_vars];
114117
variables[m..].fill(
115118
IntegerVariable::new(Some(0), Some((n_i64 - 1).max(0)))
116-
.map_err(Self::target_construction)?,
119+
.map_err(<Self as ReduceTo<ILP<i64, i64, Bounded>>>::target_construction)?,
117120
);
118121

119122
let target =
120123
ILP::with_variables(variables, constraints, objective, ObjectiveSense::Minimize)
121-
.map_err(Self::target_construction)?;
124+
.map_err(<Self as ReduceTo<ILP<i64, i64, Bounded>>>::target_construction)?;
122125

123126
Ok(ReductionFASToILP {
124127
target,

0 commit comments

Comments
 (0)