Skip to main content

problemreductions/rules/
optimallineararrangement_ilp.rs

1//! Reduction from OptimalLinearArrangement to ILP (Integer Linear Programming).
2//!
3//! Position-assignment with absolute-value auxiliaries:
4//! - Binary x_{v,p}: vertex v gets position p
5//! - Integer position variables p_v = sum_p p * x_{v,p}
6//! - Non-negative z_{u,v} per edge for |p_u - p_v|
7//! - abs_diff_le constraints: z_{u,v} >= p_u - p_v, z_{u,v} >= p_v - p_u
8//! - Minimize: sum z_{u,v}
9
10use crate::models::algebraic::{LinearConstraint, ObjectiveSense, ILP};
11use crate::models::graph::OptimalLinearArrangement;
12use crate::reduction;
13use crate::rules::traits::{ReduceTo, ReductionResult};
14use crate::topology::{Graph, SimpleGraph};
15
16/// Result of reducing OptimalLinearArrangement to ILP.
17///
18/// Variable layout (`ILP<i64>`, non-negative integers):
19/// - `x_{v,p}` at index `v * n + p`, bounded to {0,1}
20/// - `p_v` at index `n^2 + v`, integer position in {0, ..., n-1}
21/// - `z_e` at index `n^2 + n + e`, non-negative integer for edge length
22#[derive(Debug, Clone)]
23pub struct ReductionOLAToILP {
24    target: ILP<i64>,
25    num_vertices: usize,
26}
27
28impl ReductionResult for ReductionOLAToILP {
29    type Source = OptimalLinearArrangement<SimpleGraph>;
30    type Target = ILP<i64>;
31
32    fn target_problem(&self) -> &ILP<i64> {
33        &self.target
34    }
35
36    /// Extract: for each vertex v, output its position p (the unique p with x_{v,p} = 1).
37    fn extract_solution(
38        &self,
39        target_solution: &<Self::Target as crate::traits::Problem>::Solution,
40    ) -> crate::rules::ExtractionResult<<Self::Source as crate::traits::Problem>::Solution> {
41        crate::rules::traits::validate_target_solution(self.target_problem(), target_solution)?;
42
43        crate::rules::ilp_helpers::one_hot_decode_rows(
44            target_solution,
45            self.num_vertices,
46            self.num_vertices,
47            0,
48        )
49    }
50}
51
52#[reduction(
53    transform = exact {
54        num_vars = "num_vertices^2 + num_vertices + num_edges",
55        num_constraints = "2 * num_vertices + num_vertices^2 + num_vertices + num_vertices + 3 * num_edges",
56    },
57    unavailable = {
58        num_nonzeros = "the exact target parameter is not represented by this reduction's symbolic transform",
59    }
60)]
61impl ReduceTo<ILP<i64>> for OptimalLinearArrangement<SimpleGraph> {
62    type Result = ReductionOLAToILP;
63
64    fn reduce_to(&self) -> Result<Self::Result, crate::rules::ReductionError> {
65        let n = self.num_vertices();
66        let graph = self.graph();
67        let edges = graph.edges();
68        let m = edges.len();
69
70        let num_x = n * n;
71        let num_vars = num_x + n + m;
72
73        let x_idx = |v: usize, p: usize| -> usize { v * n + p };
74        let p_idx = |v: usize| -> usize { num_x + v };
75        let z_idx = |e: usize| -> usize { num_x + n + e };
76
77        let mut constraints = Vec::new();
78        let n_i64 = <Self as ReduceTo<ILP<i64>>>::exact_i64(n, "encoding a vertex position")?;
79
80        // Assignment: each vertex in exactly one position
81        for v in 0..n {
82            let terms: Vec<(usize, i64)> = (0..n).map(|p| (x_idx(v, p), 1)).collect();
83            constraints.push(LinearConstraint::eq(terms, 1));
84        }
85
86        // Assignment: each position has exactly one vertex
87        for p in 0..n {
88            let terms: Vec<(usize, i64)> = (0..n).map(|v| (x_idx(v, p), 1)).collect();
89            constraints.push(LinearConstraint::eq(terms, 1));
90        }
91
92        // Binary bounds for x variables (`ILP<i64>`)
93        for v in 0..n {
94            for p in 0..n {
95                constraints.push(LinearConstraint::le(vec![(x_idx(v, p), 1)], 1));
96            }
97        }
98
99        // Position variable linking: p_v = sum_p p * x_{v,p}
100        // Reformulated as: p_v - sum_p p * x_{v,p} = 0
101        for v in 0..n {
102            let mut terms: Vec<(usize, i64)> = vec![(p_idx(v), 1)];
103            for p in 0..n {
104                terms.push((
105                    x_idx(v, p),
106                    -<Self as ReduceTo<ILP<i64>>>::exact_i64(p, "encoding a vertex position")?,
107                ));
108            }
109            constraints.push(LinearConstraint::eq(terms, 0));
110        }
111
112        // Position bounds: 0 <= p_v <= n-1
113        for v in 0..n {
114            constraints.push(LinearConstraint::le(vec![(p_idx(v), 1)], n_i64 - 1));
115        }
116
117        // Absolute value: z_e >= |p_u - p_v| for each edge e = {u, v}
118        for (e, &(u, v)) in edges.iter().enumerate() {
119            // z_e >= p_u - p_v
120            constraints.push(LinearConstraint::ge(
121                vec![(z_idx(e), 1), (p_idx(u), -1), (p_idx(v), 1)],
122                0,
123            ));
124            // z_e >= p_v - p_u
125            constraints.push(LinearConstraint::ge(
126                vec![(z_idx(e), 1), (p_idx(v), -1), (p_idx(u), 1)],
127                0,
128            ));
129            // z_e <= n-1 (max possible position difference)
130            constraints.push(LinearConstraint::le(vec![(z_idx(e), 1)], n_i64 - 1));
131        }
132
133        // Objective: minimize sum z_e
134        let objective: Vec<(usize, i64)> = (0..m).map(|e| (z_idx(e), 1)).collect();
135        let target = ILP::new(num_vars, constraints, objective, ObjectiveSense::Minimize)
136            .map_err(<Self as ReduceTo<ILP<i64>>>::target_construction)?;
137
138        Ok(ReductionOLAToILP {
139            target,
140            num_vertices: n,
141        })
142    }
143}
144
145#[cfg(feature = "example-db")]
146pub(crate) fn canonical_rule_example_specs() -> Vec<crate::example_db::specs::RuleExampleSpec> {
147    vec![crate::example_db::specs::RuleExampleSpec {
148        id: "optimallineararrangement_to_ilp",
149        build: || {
150            // Path P4: 0-1-2-3 (identity permutation achieves cost 3)
151            let source =
152                OptimalLinearArrangement::new(SimpleGraph::new(4, vec![(0, 1), (1, 2), (2, 3)]));
153            crate::example_db::specs::rule_example_via_ilp::<_, i64>(source)
154        },
155    }]
156}
157
158#[cfg(test)]
159#[path = "../unit_tests/rules/optimallineararrangement_ilp.rs"]
160mod tests;