-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmaximum_clique.rs
More file actions
222 lines (200 loc) · 6.53 KB
/
maximum_clique.rs
File metadata and controls
222 lines (200 loc) · 6.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
//! MaximumClique problem implementation.
//!
//! The MaximumClique problem asks for a maximum weight subset of vertices
//! such that all vertices in the subset are pairwise adjacent.
use crate::registry::{FieldInfo, ProblemSchemaEntry, VariantDimension};
use crate::topology::{Graph, SimpleGraph};
use crate::traits::Problem;
use crate::types::{Max, One, WeightElement};
use num_traits::Zero;
use serde::{Deserialize, Serialize};
inventory::submit! {
ProblemSchemaEntry {
name: "MaximumClique",
display_name: "Maximum Clique",
aliases: &[],
dimensions: &[
VariantDimension::new("graph", "SimpleGraph", &["SimpleGraph"]),
VariantDimension::new("weight", "One", &["One", "i32"]),
],
module_path: module_path!(),
description: "Find maximum weight clique in a graph",
fields: &[
FieldInfo { name: "graph", type_name: "G", description: "The underlying graph G=(V,E)" },
FieldInfo { name: "weights", type_name: "Vec<W>", description: "Vertex weights w: V -> R" },
],
}
}
/// The MaximumClique problem.
///
/// Given a graph G = (V, E) and weights w_v for each vertex,
/// find a subset S ⊆ V such that:
/// - All vertices in S are pairwise adjacent (clique constraint)
/// - The total weight Σ_{v ∈ S} w_v is maximized
///
/// # Type Parameters
///
/// * `G` - The graph type (e.g., `SimpleGraph`, `KingsSubgraph`, `UnitDiskGraph`)
/// * `W` - The weight type (e.g., `i32`, `f64`, `One`)
///
/// # Example
///
/// ```
/// use problemreductions::models::graph::MaximumClique;
/// use problemreductions::topology::SimpleGraph;
/// use problemreductions::{Problem, Solver, BruteForce};
///
/// // Create a triangle graph (3 vertices, 3 edges - complete graph)
/// let graph = SimpleGraph::new(3, vec![(0, 1), (1, 2), (0, 2)]);
/// let problem = MaximumClique::new(graph, vec![1; 3]);
///
/// // Solve with brute force
/// let solver = BruteForce::new();
/// let solutions = solver.find_all_witnesses(&problem);
///
/// // Maximum clique in a triangle (K3) is size 3
/// assert!(solutions.iter().all(|s| s.iter().sum::<usize>() == 3));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaximumClique<G, W> {
/// The underlying graph.
graph: G,
/// Weights for each vertex.
weights: Vec<W>,
}
impl<G: Graph, W: Clone + Default> MaximumClique<G, W> {
/// Create a MaximumClique problem from a graph with given weights.
pub fn new(graph: G, weights: Vec<W>) -> Self {
assert_eq!(
weights.len(),
graph.num_vertices(),
"weights length must match graph num_vertices"
);
Self { graph, weights }
}
/// Get a reference to the underlying graph.
pub fn graph(&self) -> &G {
&self.graph
}
/// Get a reference to the weights.
pub fn weights(&self) -> &[W] {
&self.weights
}
/// Check if the problem uses a non-unit weight type.
pub fn is_weighted(&self) -> bool
where
W: WeightElement,
{
!W::IS_UNIT
}
/// Check if a configuration is a valid clique.
pub fn is_valid_solution(&self, config: &[usize]) -> bool {
is_clique_config(&self.graph, config)
}
}
impl<G: Graph, W: WeightElement> MaximumClique<G, W> {
/// Get the number of vertices in the underlying graph.
pub fn num_vertices(&self) -> usize {
self.graph().num_vertices()
}
/// Get the number of edges in the underlying graph.
pub fn num_edges(&self) -> usize {
self.graph().num_edges()
}
}
impl<G, W> Problem for MaximumClique<G, W>
where
G: Graph + crate::variant::VariantParam,
W: WeightElement + crate::variant::VariantParam,
{
const NAME: &'static str = "MaximumClique";
type Value = Max<W::Sum>;
fn variant() -> Vec<(&'static str, &'static str)> {
crate::variant_params![G, W]
}
fn dims(&self) -> Vec<usize> {
vec![2; self.graph.num_vertices()]
}
fn evaluate(&self, config: &[usize]) -> Max<W::Sum> {
if !is_clique_config(&self.graph, config) {
return Max(None);
}
let mut total = W::Sum::zero();
for (i, &selected) in config.iter().enumerate() {
if selected == 1 {
total += self.weights[i].to_sum();
}
}
Max(Some(total))
}
}
/// Check if a configuration forms a valid clique.
fn is_clique_config<G: Graph>(graph: &G, config: &[usize]) -> bool {
// Collect all selected vertices
let selected: Vec<usize> = config
.iter()
.enumerate()
.filter(|(_, &v)| v == 1)
.map(|(i, _)| i)
.collect();
// Check all pairs of selected vertices are adjacent
for i in 0..selected.len() {
for j in (i + 1)..selected.len() {
if !graph.has_edge(selected[i], selected[j]) {
return false;
}
}
}
true
}
crate::declare_variants! {
MaximumClique<SimpleGraph, i32> => "1.1996^num_vertices",
default MaximumClique<SimpleGraph, One> => "1.1996^num_vertices",
}
#[cfg(feature = "example-db")]
pub(crate) fn canonical_model_example_specs() -> Vec<crate::example_db::specs::ModelExampleSpec> {
vec![crate::example_db::specs::ModelExampleSpec {
id: "maximum_clique_simplegraph_i32",
instance: Box::new(MaximumClique::new(
SimpleGraph::new(5, vec![(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (3, 4)]),
vec![1i32; 5],
)),
optimal_config: vec![0, 0, 1, 1, 1],
optimal_value: serde_json::json!(3),
}]
}
/// Check if a set of vertices forms a clique.
///
/// # Arguments
/// * `graph` - The graph
/// * `selected` - Boolean slice indicating which vertices are selected
///
/// # Panics
/// Panics if `selected.len() != graph.num_vertices()`.
#[cfg(test)]
pub(crate) fn is_clique<G: Graph>(graph: &G, selected: &[bool]) -> bool {
assert_eq!(
selected.len(),
graph.num_vertices(),
"selected length must match num_vertices"
);
// Collect selected vertices
let selected_vertices: Vec<usize> = selected
.iter()
.enumerate()
.filter(|(_, &s)| s)
.map(|(i, _)| i)
.collect();
// Check all pairs of selected vertices are adjacent
for i in 0..selected_vertices.len() {
for j in (i + 1)..selected_vertices.len() {
if !graph.has_edge(selected_vertices[i], selected_vertices[j]) {
return false;
}
}
}
true
}
#[cfg(test)]
#[path = "../../unit_tests/models/graph/maximum_clique.rs"]
mod tests;