-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmax_cut.rs
More file actions
223 lines (201 loc) · 6.57 KB
/
Copy pathmax_cut.rs
File metadata and controls
223 lines (201 loc) · 6.57 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
223
//! MaxCut problem implementation.
//!
//! The Maximum Cut problem asks for a partition of vertices into two sets
//! that maximizes the total weight of edges crossing the partition.
use crate::registry::{FieldInfo, ProblemSchemaEntry};
use crate::topology::{Graph, SimpleGraph};
use crate::traits::{OptimizationProblem, Problem};
use crate::types::{Direction, SolutionSize, WeightElement};
use num_traits::Zero;
use serde::{Deserialize, Serialize};
inventory::submit! {
ProblemSchemaEntry {
name: "MaxCut",
module_path: module_path!(),
description: "Find maximum weight cut in a graph",
fields: &[
FieldInfo { name: "graph", type_name: "G", description: "The graph with edge weights" },
FieldInfo { name: "edge_weights", type_name: "Vec<W>", description: "Edge weights w: E -> R" },
],
}
}
/// The Maximum Cut problem.
///
/// Given a weighted graph G = (V, E) with edge weights w_e,
/// find a partition of V into sets S and V\S such that
/// the total weight of edges crossing the cut is maximized.
///
/// # Representation
///
/// Each vertex is assigned a binary value:
/// - 0: vertex is in set S
/// - 1: vertex is in set V\S
///
/// An edge contributes to the cut if its endpoints are in different sets.
///
/// # Type Parameters
///
/// * `G` - The graph type (e.g., `SimpleGraph`, `KingsSubgraph`, `UnitDiskGraph`)
/// * `W` - The weight type for edges (e.g., `i32`, `f64`)
///
/// # Example
///
/// ```
/// use problemreductions::models::graph::MaxCut;
/// use problemreductions::topology::SimpleGraph;
/// use problemreductions::types::SolutionSize;
/// use problemreductions::{Problem, Solver, BruteForce};
///
/// // Create a triangle with unit weights
/// let graph = SimpleGraph::new(3, vec![(0, 1), (1, 2), (0, 2)]);
/// let problem = MaxCut::new(graph, vec![1, 1, 1]);
///
/// // Solve with brute force
/// let solver = BruteForce::new();
/// let solutions = solver.find_all_best(&problem);
///
/// // Maximum cut in triangle is 2 (any partition cuts 2 edges)
/// for sol in solutions {
/// let size = problem.evaluate(&sol);
/// assert_eq!(size, SolutionSize::Valid(2));
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaxCut<G, W> {
/// The underlying graph structure.
graph: G,
/// Weights for each edge (in the same order as graph.edges()).
edge_weights: Vec<W>,
}
impl<G: Graph, W: Clone + Default> MaxCut<G, W> {
/// Create a MaxCut problem from a graph with specified edge weights.
///
/// # Arguments
/// * `graph` - The underlying graph
/// * `edge_weights` - Weights for each edge (must match graph.num_edges())
pub fn new(graph: G, edge_weights: Vec<W>) -> Self {
assert_eq!(
edge_weights.len(),
graph.num_edges(),
"edge_weights length must match num_edges"
);
Self {
graph,
edge_weights,
}
}
/// Create a MaxCut problem with unit weights.
pub fn unweighted(graph: G) -> Self
where
W: From<i32>,
{
let edge_weights = vec![W::from(1); graph.num_edges()];
Self {
graph,
edge_weights,
}
}
/// Get a reference to the underlying graph.
pub fn graph(&self) -> &G {
&self.graph
}
/// Get the edges with weights.
pub fn edges(&self) -> Vec<(usize, usize, W)> {
self.graph
.edges()
.into_iter()
.zip(self.edge_weights.iter())
.map(|((u, v), w)| (u, v, w.clone()))
.collect()
}
/// Get the weight of an edge by its index.
pub fn edge_weight_by_index(&self, idx: usize) -> Option<&W> {
self.edge_weights.get(idx)
}
/// Get the weight of an edge between vertices u and v.
pub fn edge_weight(&self, u: usize, v: usize) -> Option<&W> {
// Find the edge index
for (idx, (eu, ev)) in self.graph.edges().iter().enumerate() {
if (*eu == u && *ev == v) || (*eu == v && *ev == u) {
return self.edge_weights.get(idx);
}
}
None
}
/// Get edge weights only.
pub fn edge_weights(&self) -> Vec<W> {
self.edge_weights.clone()
}
/// Compute the cut size for a given partition configuration.
pub fn cut_size(&self, config: &[usize]) -> W::Sum
where
W: WeightElement,
{
let partition: Vec<bool> = config.iter().map(|&c| c != 0).collect();
cut_size(&self.graph, &self.edge_weights, &partition)
}
}
impl<G: Graph, W: WeightElement> MaxCut<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 MaxCut<G, W>
where
G: Graph + crate::variant::VariantParam,
W: WeightElement + crate::variant::VariantParam,
{
const NAME: &'static str = "MaxCut";
type Metric = SolutionSize<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]) -> SolutionSize<W::Sum> {
// All cuts are valid, so always return Valid
let partition: Vec<bool> = config.iter().map(|&c| c != 0).collect();
SolutionSize::Valid(cut_size(&self.graph, &self.edge_weights, &partition))
}
}
impl<G, W> OptimizationProblem for MaxCut<G, W>
where
G: Graph + crate::variant::VariantParam,
W: WeightElement + crate::variant::VariantParam,
{
type Value = W::Sum;
fn direction(&self) -> Direction {
Direction::Maximize
}
}
/// Compute the total weight of edges crossing the cut.
///
/// # Arguments
/// * `graph` - The graph structure
/// * `edge_weights` - Weights for each edge (same order as `graph.edges()`)
/// * `partition` - Boolean slice indicating which set each vertex belongs to
pub(crate) fn cut_size<G, W>(graph: &G, edge_weights: &[W], partition: &[bool]) -> W::Sum
where
G: Graph,
W: WeightElement,
{
let mut total = W::Sum::zero();
for ((u, v), weight) in graph.edges().iter().zip(edge_weights.iter()) {
if *u < partition.len() && *v < partition.len() && partition[*u] != partition[*v] {
total += weight.to_sum();
}
}
total
}
crate::declare_variants! {
MaxCut<SimpleGraph, i32> => "2^(omega * num_vertices / 3)",
}
#[cfg(test)]
#[path = "../../unit_tests/models/graph/max_cut.rs"]
mod tests;