1use crate::models::algebraic::{LinearConstraint, ObjectiveSense, ILP};
9use crate::models::graph::TravelingSalesman;
10use crate::reduction;
11use crate::rules::ilp_helpers::{mccormick_product, one_hot_decode};
12use crate::rules::traits::{ReduceTo, ReductionResult};
13use crate::topology::{Graph, SimpleGraph};
14
15#[derive(Debug, Clone)]
17pub struct ReductionTSPToILP {
18 target: ILP<bool>,
19 num_vertices: usize,
21 source_edges: Vec<(usize, usize)>,
23}
24
25impl ReductionResult for ReductionTSPToILP {
26 type Source = TravelingSalesman<SimpleGraph, i64>;
27 type Target = ILP<bool>;
28
29 fn target_problem(&self) -> &ILP<bool> {
30 &self.target
31 }
32
33 fn extract_solution(
36 &self,
37 target_solution: &<Self::Target as crate::traits::Problem>::Solution,
38 ) -> crate::rules::ExtractionResult<<Self::Source as crate::traits::Problem>::Solution> {
39 crate::rules::traits::validate_target_solution(self.target_problem(), target_solution)?;
40
41 Ok({
42 let n = self.num_vertices;
43
44 let tour = one_hot_decode(target_solution, n, n, 0)?;
45
46 let mut edge_selection = vec![false; self.source_edges.len()];
48 for k in 0..n {
49 let u = tour[k];
50 let v = tour[(k + 1) % n];
51 let edge = self
52 .source_edges
53 .iter()
54 .position(|&(a, b)| (a == u && b == v) || (a == v && b == u))
55 .ok_or_else(|| {
56 crate::rules::ExtractionError::invalid(format!(
57 "target tour uses absent source edge ({u}, {v})"
58 ))
59 })?;
60 edge_selection[edge] = true;
61 }
62
63 edge_selection
64 })
65 }
66}
67
68#[reduction(transform = {
74 exact {
75 num_vars = "num_vertices^2 + 2 * num_vertices * num_edges",
76 },
77 upper_bound {
78 max_constraint_magnitude_bits = "2",
79 num_constraints = "num_vertices^2 * (num_vertices - 1) + 2 * num_vertices + 6 * num_vertices * num_edges",
80 num_nonzeros = "2 * num_vertices^3 + 14 * num_vertices * num_edges",
81 },
82})]
83impl ReduceTo<ILP<bool>> for TravelingSalesman<SimpleGraph, i64> {
84 type Result = ReductionTSPToILP;
85
86 fn reduce_to(&self) -> Result<Self::Result, crate::rules::ReductionError> {
87 let n = self.graph().num_vertices();
88 let graph = self.graph();
89 let edges_with_weights = self.edges();
90 let source_edges: Vec<(usize, usize)> =
91 edges_with_weights.iter().map(|&(u, v, _)| (u, v)).collect();
92 let edge_weights: Vec<i64> = edges_with_weights
93 .iter()
94 .map(|&(_, _, weight)| weight)
95 .collect();
96 let m = source_edges.len();
97
98 let num_x = n * n;
105 let num_y = 2 * m * n;
106 let num_vars = num_x + num_y;
107
108 let x_idx = |v: usize, k: usize| -> usize { v * n + k };
109 let y_idx =
110 |edge: usize, k: usize, dir: usize| -> usize { num_x + edge * 2 * n + 2 * k + dir };
111
112 let mut constraints = Vec::new();
113
114 for v in 0..n {
116 let terms: Vec<(usize, i64)> = (0..n).map(|k| (x_idx(v, k), 1)).collect();
117 constraints.push(LinearConstraint::eq(terms, 1));
118 }
119
120 for k in 0..n {
122 let terms: Vec<(usize, i64)> = (0..n).map(|v| (x_idx(v, k), 1)).collect();
123 constraints.push(LinearConstraint::eq(terms, 1));
124 }
125
126 for v in 0..n {
130 for w in 0..n {
131 if v == w {
132 continue;
133 }
134 if graph.has_edge(v, w) {
135 continue;
136 }
137 for k in 0..n {
138 constraints.push(LinearConstraint::le(
139 vec![(x_idx(v, k), 1), (x_idx(w, (k + 1) % n), 1)],
140 1,
141 ));
142 }
143 }
144 }
145
146 for (e, &(u, v)) in source_edges.iter().enumerate() {
151 for k in 0..n {
152 let k_next = (k + 1) % n;
153
154 let y_fwd = y_idx(e, k, 0);
156 let xu = x_idx(u, k);
157 let xv_next = x_idx(v, k_next);
158 constraints.extend(mccormick_product(y_fwd, xu, xv_next));
159
160 let y_rev = y_idx(e, k, 1);
162 let xv = x_idx(v, k);
163 let xu_next = x_idx(u, k_next);
164 constraints.extend(mccormick_product(y_rev, xv, xu_next));
165 }
166 }
167
168 let mut objective: Vec<(usize, i64)> = Vec::new();
170 for (e, &w) in edge_weights.iter().enumerate() {
171 for k in 0..n {
172 objective.push((y_idx(e, k, 0), w));
173 objective.push((y_idx(e, k, 1), w));
174 }
175 }
176
177 let target = ILP::new(num_vars, constraints, objective, ObjectiveSense::Minimize)
178 .map_err(<Self as ReduceTo<ILP<bool>>>::target_construction)?;
179
180 Ok(ReductionTSPToILP {
181 target,
182 num_vertices: n,
183 source_edges,
184 })
185 }
186}
187
188#[cfg(feature = "example-db")]
189pub(crate) fn canonical_rule_example_specs() -> Vec<crate::example_db::specs::RuleExampleSpec> {
190 vec![crate::example_db::specs::RuleExampleSpec {
191 id: "travelingsalesman_to_ilp",
192 build: || {
193 let source = TravelingSalesman::new(
194 SimpleGraph::new(4, vec![(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]),
195 vec![10, 15, 20, 35, 25, 30],
196 );
197 crate::example_db::specs::rule_example_via_ilp::<_, bool>(source)
198 },
199 }]
200}
201
202#[cfg(test)]
203#[path = "../unit_tests/rules/travelingsalesman_ilp.rs"]
204mod tests;