1use crate::models::algebraic::{LinearConstraint, ObjectiveSense, ILP};
11use crate::models::misc::OptimumCommunicationSpanningTree;
12use crate::reduction;
13use crate::rules::traits::{ReduceTo, ReductionResult};
14
15#[derive(Debug, Clone)]
23pub struct ReductionOptimumCommunicationSpanningTreeToILP {
24 target: ILP<bool>,
25 num_edges: usize,
26}
27
28impl ReductionResult for ReductionOptimumCommunicationSpanningTreeToILP {
29 type Source = OptimumCommunicationSpanningTree;
30 type Target = ILP<bool>;
31
32 fn target_problem(&self) -> &ILP<bool> {
33 &self.target
34 }
35
36 fn extract_solution(
37 &self,
38 target_solution: &<Self::Target as crate::traits::Problem>::Solution,
39 ) -> crate::rules::ExtractionResult<<Self::Source as crate::traits::Problem>::Solution> {
40 crate::rules::traits::validate_target_solution(self.target_problem(), target_solution)?;
41
42 Ok(target_solution[..self.num_edges]
43 .iter()
44 .map(|&value| value == 1)
45 .collect())
46 }
47}
48
49#[reduction(
50 transform = exact {
51 num_vars = "num_edges + 2 * num_edges * num_vertices * (num_vertices - 1) / 2",
52 num_constraints = "1 + num_vertices * num_vertices * (num_vertices - 1) / 2 + 2 * num_edges * num_vertices * (num_vertices - 1) / 2",
53 },
54 unavailable = {
55 num_nonzeros = "the exact target parameter is not represented by this reduction's symbolic transform",
56 }
57)]
58impl ReduceTo<ILP<bool>> for OptimumCommunicationSpanningTree {
59 type Result = ReductionOptimumCommunicationSpanningTreeToILP;
60
61 fn reduce_to(&self) -> Result<Self::Result, crate::rules::ReductionError> {
62 let n = self.num_vertices();
63 let m = self.num_edges();
64 let edges = self.edges();
65 let w = self.edge_weights();
66 let r = self.requirements();
67
68 let mut commodities: Vec<(usize, usize)> = Vec::new();
70 for s in 0..n {
71 for t in (s + 1)..n {
72 commodities.push((s, t));
73 }
74 }
75 let num_commodities = commodities.len();
76
77 let num_vars = m + 2 * m * num_commodities;
78 let mut constraints = Vec::new();
79
80 let edge_var = |edge_idx: usize| edge_idx;
82
83 let flow_var =
85 |k: usize, edge_idx: usize, dir: usize| -> usize { m + k * 2 * m + 2 * edge_idx + dir };
86
87 let tree_terms: Vec<(usize, i64)> = (0..m).map(|e| (edge_var(e), 1)).collect();
90 constraints.push(LinearConstraint::eq(
91 tree_terms,
92 Self::exact_i64(n, "encoding the spanning-tree order")? - 1,
93 ));
94
95 for (k, &(src, dst)) in commodities.iter().enumerate() {
97 for vertex in 0..n {
98 let mut terms = Vec::new();
99 for (edge_idx, &(i, j)) in edges.iter().enumerate() {
100 if j == vertex {
102 terms.push((flow_var(k, edge_idx, 0), 1));
104 terms.push((flow_var(k, edge_idx, 1), -1));
105 }
106 if i == vertex {
107 terms.push((flow_var(k, edge_idx, 1), 1));
109 terms.push((flow_var(k, edge_idx, 0), -1));
110 }
111 }
112
113 let rhs = if vertex == src {
114 -1 } else if vertex == dst {
116 1 } else {
118 0 };
120 constraints.push(LinearConstraint::eq(terms, rhs));
121 }
122 }
123
124 for k in 0..num_commodities {
126 for edge_idx in 0..m {
127 let sel = edge_var(edge_idx);
128 constraints.push(LinearConstraint::le(
130 vec![(flow_var(k, edge_idx, 0), 1), (sel, -1)],
131 0,
132 ));
133 constraints.push(LinearConstraint::le(
135 vec![(flow_var(k, edge_idx, 1), 1), (sel, -1)],
136 0,
137 ));
138 }
139 }
140
141 let mut objective: Vec<(usize, i64)> = Vec::new();
144 for (k, &(s, t)) in commodities.iter().enumerate() {
145 for (edge_idx, &(i, j)) in edges.iter().enumerate() {
146 let communication_cost = r[s][t].checked_mul(w[i][j]).ok_or_else(|| {
147 crate::rules::ReductionError::integer_overflow::<
148 OptimumCommunicationSpanningTree,
149 ILP<bool>,
150 >(
151 "multiplying a communication requirement by an edge weight"
152 )
153 })?;
154 let coeff = communication_cost;
155 if coeff != 0 {
156 objective.push((flow_var(k, edge_idx, 0), coeff));
157 objective.push((flow_var(k, edge_idx, 1), coeff));
158 }
159 }
160 }
161
162 let target = ILP::new(num_vars, constraints, objective, ObjectiveSense::Minimize)
163 .map_err(Self::target_construction)?;
164
165 Ok(ReductionOptimumCommunicationSpanningTreeToILP {
166 target,
167 num_edges: m,
168 })
169 }
170}
171
172#[cfg(feature = "example-db")]
173pub(crate) fn canonical_rule_example_specs() -> Vec<crate::example_db::specs::RuleExampleSpec> {
174 vec![crate::example_db::specs::RuleExampleSpec {
175 id: "optimum_communication_spanning_tree_to_ilp",
176 build: || {
177 let edge_weights = vec![vec![0, 1, 2], vec![1, 0, 3], vec![2, 3, 0]];
179 let requirements = vec![vec![0, 1, 1], vec![1, 0, 1], vec![1, 1, 0]];
180 let source = OptimumCommunicationSpanningTree::new(edge_weights, requirements);
181 crate::example_db::specs::rule_example_via_ilp::<_, bool>(source)
182 },
183 }]
184}
185
186#[cfg(test)]
187#[path = "../unit_tests/rules/optimumcommunicationspanningtree_ilp.rs"]
188mod tests;