Skip to main content

problemreductions/models/graph/
strong_connectivity_augmentation.rs

1//! Strong Connectivity Augmentation problem implementation.
2//!
3//! The Strong Connectivity Augmentation problem asks whether adding a bounded
4//! set of weighted candidate arcs can make a directed graph strongly connected.
5
6use crate::registry::{FieldInfo, ProblemSchemaEntry, VariantDimension};
7use crate::topology::DirectedGraph;
8use crate::traits::Problem;
9use crate::types::WeightElement;
10use num_traits::Zero;
11use serde::{Deserialize, Deserializer, Serialize};
12use std::cmp::Ordering;
13use std::collections::BTreeSet;
14
15inventory::submit! {
16    ProblemSchemaEntry {
17        name: "StrongConnectivityAugmentation",
18        display_name: "Strong Connectivity Augmentation",
19        aliases: &[],
20        dimensions: &[
21            VariantDimension::new("weight", "i64", &["i64"]),
22        ],
23        category: crate::registry::ProblemCategory::Graph,
24        module_path: module_path!(),
25        description: "Add a bounded set of weighted candidate arcs to make a digraph strongly connected",
26        fields: &[
27            FieldInfo { name: "graph", type_name: "DirectedGraph", description: "The initial directed graph G=(V,A)" },
28            FieldInfo { name: "candidate_arcs", type_name: "Vec<(usize, usize, W)>", description: "Candidate augmenting arcs (u, v, w(u,v)) not already present in G" },
29            FieldInfo { name: "bound", type_name: "W::Sum", description: "Upper bound B on the total added weight" },
30        ],
31    }
32}
33
34/// Strong Connectivity Augmentation.
35///
36/// Given a directed graph `G = (V, A)`, weighted candidate arcs not already in
37/// `A`, and a bound `B`, determine whether some subset of the candidate arcs
38/// has total weight at most `B` and makes the augmented digraph strongly
39/// connected.
40#[derive(Debug, Clone, Serialize)]
41pub struct StrongConnectivityAugmentation<W: WeightElement> {
42    graph: DirectedGraph,
43    candidate_arcs: Vec<(usize, usize, W)>,
44    bound: W::Sum,
45}
46
47impl<W: WeightElement> StrongConnectivityAugmentation<W> {
48    /// Fallible constructor used by CLI validation and deserialization.
49    pub fn try_new(
50        graph: DirectedGraph,
51        candidate_arcs: Vec<(usize, usize, W)>,
52        bound: W::Sum,
53    ) -> Result<Self, crate::registry::ConstructionError> {
54        if !matches!(
55            bound.partial_cmp(&W::Sum::zero()),
56            Some(Ordering::Equal | Ordering::Greater)
57        ) {
58            return Err("bound must be nonnegative".to_string().into());
59        }
60
61        let num_vertices = graph.num_vertices();
62        let mut seen_pairs = BTreeSet::new();
63
64        for (u, v, weight) in &candidate_arcs {
65            if *u >= num_vertices || *v >= num_vertices {
66                return Err(format!(
67                    "candidate arc ({}, {}) references vertex >= num_vertices ({})",
68                    u, v, num_vertices
69                )
70                .into());
71            }
72            if !matches!(
73                weight.to_sum().partial_cmp(&W::Sum::zero()),
74                Some(Ordering::Greater)
75            ) {
76                return Err(format!("candidate arc ({}, {}) weight must be positive", u, v).into());
77            }
78            if graph.has_arc(*u, *v) {
79                return Err(format!(
80                    "candidate arc ({}, {}) already exists in the base graph",
81                    u, v
82                )
83                .into());
84            }
85            if !seen_pairs.insert((*u, *v)) {
86                return Err(format!("duplicate candidate arc ({}, {})", u, v).into());
87            }
88        }
89
90        Ok(Self {
91            graph,
92            candidate_arcs,
93            bound,
94        })
95    }
96
97    /// Create a new strong connectivity augmentation instance.
98    ///
99    /// # Panics
100    ///
101    /// Panics if a candidate arc endpoint is out of range, if a candidate arc
102    /// already exists in the base graph, or if candidate arcs contain
103    /// duplicates.
104    pub fn new(
105        graph: DirectedGraph,
106        candidate_arcs: Vec<(usize, usize, W)>,
107        bound: W::Sum,
108    ) -> Self {
109        Self::try_new(graph, candidate_arcs, bound).unwrap_or_else(|msg| panic!("{msg}"))
110    }
111
112    /// Get the base directed graph.
113    pub fn graph(&self) -> &DirectedGraph {
114        &self.graph
115    }
116
117    /// Get the candidate augmenting arcs.
118    pub fn candidate_arcs(&self) -> &[(usize, usize, W)] {
119        &self.candidate_arcs
120    }
121
122    /// Get the upper bound on the total added weight.
123    pub fn bound(&self) -> &W::Sum {
124        &self.bound
125    }
126
127    /// Get the number of vertices in the base graph.
128    pub fn num_vertices(&self) -> usize {
129        self.graph.num_vertices()
130    }
131
132    /// Get the number of arcs in the base graph.
133    pub fn num_arcs(&self) -> usize {
134        self.graph.num_arcs()
135    }
136
137    /// Get the number of potential augmenting arcs.
138    pub fn num_potential_arcs(&self) -> usize {
139        self.candidate_arcs.len()
140    }
141
142    /// Check whether the problem uses non-unit weights.
143    pub fn is_weighted(&self) -> bool {
144        !W::IS_UNIT
145    }
146
147    /// Check whether a configuration is a satisfying augmentation.
148    pub fn is_valid_solution(
149        &self,
150        config: &[bool],
151    ) -> Result<bool, crate::traits::EvaluationError> {
152        self.evaluate_config(config)
153    }
154
155    fn evaluate_config(&self, config: &[bool]) -> Result<bool, crate::traits::EvaluationError> {
156        if config.len() != self.candidate_arcs.len() {
157            return Ok(false);
158        }
159
160        let mut total = W::Sum::zero();
161        let mut augmented_arcs = self.graph.arcs();
162
163        for ((u, v, weight), &selected) in self.candidate_arcs.iter().zip(config.iter()) {
164            if selected {
165                total = W::checked_add_to_sum(
166                    total,
167                    weight.to_sum(),
168                    "summing strong-connectivity augmentation weights",
169                )?;
170                if total > self.bound {
171                    return Ok(false);
172                }
173                augmented_arcs.push((*u, *v));
174            }
175        }
176
177        Ok(DirectedGraph::new(self.graph.num_vertices(), augmented_arcs).is_strongly_connected())
178    }
179}
180
181impl<W> Problem for StrongConnectivityAugmentation<W>
182where
183    W: WeightElement + crate::variant::VariantParam,
184{
185    const NAME: &'static str = "StrongConnectivityAugmentation";
186    type Solution = Vec<bool>;
187    type Value = crate::types::Or;
188
189    crate::problem_parameters![
190        ("num_arcs", num_arcs),
191        ("num_potential_arcs", num_potential_arcs),
192        ("num_vertices", num_vertices),
193    ];
194
195    fn variant() -> Vec<(&'static str, &'static str)> {
196        crate::variant_params![W]
197    }
198
199    fn evaluate(
200        &self,
201        config: &Self::Solution,
202    ) -> Result<crate::types::Or, crate::traits::EvaluationError> {
203        if config.len() != self.candidate_arcs.len() {
204            return Err(crate::traits::EvaluationError::InvalidConfiguration(
205                "arc-selection length does not match the candidate arcs".into(),
206            ));
207        }
208        Ok(crate::types::Or(self.evaluate_config(config)?))
209    }
210}
211
212impl<W> crate::solvers::BruteForceProblem for StrongConnectivityAugmentation<W>
213where
214    W: WeightElement + crate::variant::VariantParam,
215{
216    fn dimensions(&self) -> Vec<usize> {
217        vec![2; self.candidate_arcs.len()]
218    }
219}
220
221crate::declare_variants! {
222    default StrongConnectivityAugmentation<i64> => "2^num_potential_arcs",
223}
224
225crate::register_brute_force! {
226    StrongConnectivityAugmentation<i64> decode |_, indices: Vec<usize>| crate::config::config_to_bits(&indices),
227}
228
229#[derive(Deserialize)]
230struct StrongConnectivityAugmentationData<W: WeightElement> {
231    graph: DirectedGraph,
232    candidate_arcs: Vec<(usize, usize, W)>,
233    bound: W::Sum,
234}
235
236impl<'de, W> Deserialize<'de> for StrongConnectivityAugmentation<W>
237where
238    W: WeightElement + Deserialize<'de>,
239    W::Sum: Deserialize<'de>,
240{
241    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
242    where
243        D: Deserializer<'de>,
244    {
245        let data = StrongConnectivityAugmentationData::<W>::deserialize(deserializer)?;
246        Self::try_new(data.graph, data.candidate_arcs, data.bound).map_err(serde::de::Error::custom)
247    }
248}
249
250#[cfg(feature = "example-db")]
251pub(crate) fn canonical_model_example_specs() -> Vec<crate::example_db::specs::ModelExampleSpec> {
252    vec![crate::example_db::specs::ModelExampleSpec {
253        id: "strong_connectivity_augmentation",
254        // Path digraph 0→1→2→3→4 (not strongly connected — no back-edges).
255        // Nine candidate arcs are all individually affordable, but only the
256        // pair (4→1, w=3) + (1→0, w=5) = 8 = B achieves strong connectivity.
257        instance: Box::new(StrongConnectivityAugmentation::new(
258            DirectedGraph::new(5, vec![(0, 1), (1, 2), (2, 3), (3, 4)]),
259            vec![
260                (4, 0, 10), // direct fix, too expensive
261                (4, 3, 3),  // 4-escape to dead end
262                (4, 2, 3),  // 4-escape to dead end
263                (4, 1, 3),  // correct 4-escape
264                (3, 0, 7),  // too expensive to combine
265                (3, 1, 3),  // dead-end intermediate
266                (2, 0, 7),  // too expensive to combine
267                (2, 1, 3),  // dead-end intermediate
268                (1, 0, 5),  // the closing arc
269            ],
270            8,
271        )),
272        optimal_config: serde_json::json!(vec![
273            false, false, false, true, false, false, false, false, true
274        ]),
275        optimal_value: serde_json::json!(true),
276    }]
277}
278
279#[cfg(test)]
280#[path = "../../unit_tests/models/graph/strong_connectivity_augmentation.rs"]
281mod tests;