problemreductions/rules/
maximummatching_ilp.rs1use crate::models::algebraic::{LinearConstraint, ObjectiveSense, ILP};
10use crate::models::graph::MaximumMatching;
11use crate::reduction;
12use crate::rules::traits::{ReduceTo, ReductionResult};
13use crate::topology::{Graph, SimpleGraph};
14
15#[derive(Debug, Clone)]
22pub struct ReductionMatchingToILP {
23 target: ILP<bool>,
24}
25
26impl ReductionResult for ReductionMatchingToILP {
27 type Source = MaximumMatching<SimpleGraph, i64>;
28 type Target = ILP<bool>;
29
30 fn target_problem(&self) -> &ILP<bool> {
31 &self.target
32 }
33
34 fn extract_solution(
39 &self,
40 target_solution: &<Self::Target as crate::traits::Problem>::Solution,
41 ) -> crate::rules::ExtractionResult<<Self::Source as crate::traits::Problem>::Solution> {
42 crate::rules::traits::validate_target_solution(self.target_problem(), target_solution)?;
43
44 Ok(target_solution.iter().map(|&value| value == 1).collect())
45 }
46}
47
48#[reduction(transform = {
49 exact {
50 num_vars = "num_edges",
51 },
52 upper_bound {
53 max_constraint_magnitude_bits = "2",
54 num_constraints = "num_vertices",
55 num_nonzeros = "2 * num_edges",
56 },
57})]
58impl ReduceTo<ILP<bool>> for MaximumMatching<SimpleGraph, i64> {
59 type Result = ReductionMatchingToILP;
60
61 fn reduce_to(&self) -> Result<Self::Result, crate::rules::ReductionError> {
62 let num_vars = self.graph().num_edges(); let v2e = self.vertex_to_edges();
67 let constraints: Vec<LinearConstraint> = (0..self.graph().num_vertices())
68 .filter_map(|vertex| v2e.get(&vertex))
69 .filter(|edges| !edges.is_empty())
70 .map(|edges| {
71 let terms: Vec<(usize, i64)> = edges.iter().map(|&e| (e, 1)).collect();
72 LinearConstraint::le(terms, 1)
73 })
74 .collect();
75
76 let weights = self.weights();
78 let objective: Vec<(usize, i64)> = weights
79 .iter()
80 .enumerate()
81 .map(|(edge, &weight)| (edge, weight))
82 .collect();
83
84 let target = ILP::new(num_vars, constraints, objective, ObjectiveSense::Maximize)
85 .map_err(<Self as ReduceTo<ILP<bool>>>::target_construction)?;
86
87 Ok(ReductionMatchingToILP { target })
88 }
89}
90
91#[cfg(feature = "example-db")]
92pub(crate) fn canonical_rule_example_specs() -> Vec<crate::example_db::specs::RuleExampleSpec> {
93 vec![crate::example_db::specs::RuleExampleSpec {
94 id: "maximummatching_to_ilp",
95 build: || {
96 let (n, edges) = crate::topology::small_graphs::petersen();
97 let source = MaximumMatching::unit_weights(SimpleGraph::new(n, edges));
98 crate::example_db::specs::rule_example_via_ilp::<_, bool>(source)
99 },
100 }]
101}
102
103#[cfg(test)]
104#[path = "../unit_tests/rules/maximummatching_ilp.rs"]
105mod tests;