quantrs2-tytan 0.1.3

High-level quantum annealing interface inspired by Tytan for the QuantRS2 framework
Documentation
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Comprehensive tests for problem decomposition features.

use ndarray::{Array2, ArrayD, IxDyn};
use quantrs2_tytan::problem_decomposition::*;
use quantrs2_tytan::sampler::{SampleResult, Sampler};
use std::collections::HashMap;

#[test]
fn test_graph_partitioner_kernighan_lin() {
    let partitioner = GraphPartitioner::with_config(PartitioningAlgorithm::KernighanLin, 2);

    // Create a test QUBO matrix with clear structure
    let mut qubo = Array2::zeros((8, 8));
    
    // Create two clusters: {0,1,2,3} and {4,5,6,7}
    // Strong intra-cluster connections
    for i in 0..4 {
        for j in 0..4 {
            if i != j {
                qubo[[i, j]] = -2.0; // Prefer variables in same group to have same value
            }
        }
    }
    for i in 4..8 {
        for j in 4..8 {
            if i != j {
                qubo[[i, j]] = -2.0;
            }
        }
    }
    
    // Weak inter-cluster connections
    for i in 0..4 {
        for j in 4..8 {
            qubo[[i, j]] = 0.1;
            qubo[[j, i]] = 0.1;
        }
    }

    let result = partitioner.partition(&qubo);
    assert!(result.is_ok());
    
    let subproblems = result.unwrap();
    assert!(!subproblems.is_empty());
    
    // Verify subproblems have reasonable sizes
    for subproblem in &subproblems {
        assert!(subproblem.variables.len() <= 50); // reasonable max size
        assert!(!subproblem.variables.is_empty());
    }
    
    // Verify coverage - all variables should be in at least one subproblem
    let mut covered_vars = std::collections::HashSet::new();
    for subproblem in &subproblems {
        for &var in &subproblem.variables {
            covered_vars.insert(var);
        }
    }
    assert_eq!(covered_vars.len(), 8);
}

#[test]
fn test_graph_partitioner_spectral() {
    let partitioner = GraphPartitioner::with_config(PartitioningAlgorithm::Spectral, 2);

    // Create a ring graph QUBO
    let size = 10;
    let mut qubo = Array2::zeros((size, size));
    
    for i in 0..size {
        let next = (i + 1) % size;
        qubo[[i, next]] = -1.0;
        qubo[[next, i]] = -1.0;
    }

    let result = partitioner.partition(&qubo);
    assert!(result.is_ok());
    
    let subproblems = result.unwrap();
    assert!(!subproblems.is_empty());
    
    // For a ring graph, should be able to partition reasonably
    println!("Spectral partitioning created {} subproblems", subproblems.len());
    for (idx, subproblem) in subproblems.iter().enumerate() {
        println!("Subproblem {}: {} variables", idx, subproblem.variables.len());
    }
}

#[test]
fn test_graph_partitioner_multilevel() {
    let partitioner = GraphPartitioner::with_config(PartitioningAlgorithm::Multilevel, 2);

    // Create a grid-like QUBO
    let grid_size = 6; // 6x6 grid = 36 variables
    let size = grid_size * grid_size;
    let mut qubo = Array2::zeros((size, size));
    
    // Connect neighbors in grid
    for i in 0..grid_size {
        for j in 0..grid_size {
            let idx = i * grid_size + j;
            
            // Right neighbor
            if j + 1 < grid_size {
                let right_idx = i * grid_size + (j + 1);
                qubo[[idx, right_idx]] = -0.5;
                qubo[[right_idx, idx]] = -0.5;
            }
            
            // Bottom neighbor
            if i + 1 < grid_size {
                let bottom_idx = (i + 1) * grid_size + j;
                qubo[[idx, bottom_idx]] = -0.5;
                qubo[[bottom_idx, idx]] = -0.5;
            }
        }
    }

    let result = partitioner.partition(&qubo);
    assert!(result.is_ok());
    
    let subproblems = result.unwrap();
    assert!(!subproblems.is_empty());
    
    // Should create multiple subproblems of reasonable size
    assert!(subproblems.len() >= 2);
    for subproblem in &subproblems {
        assert!(subproblem.variables.len() <= 20);
    }
}

#[test]
fn test_hierarchical_solver_basic() {
    let config = HierarchicalSolverConfig {
        coarsening_strategy: CoarseningStrategy::MatchingBased,
        max_levels: 3,
        coarsening_threshold: 10,
        solver_strategy: SolverStrategy::Adaptive {
            small_problem_threshold: 50,
            timeout_per_level: std::time::Duration::from_secs(30),
        },
        refinement_config: RefinementConfig {
            method: RefinementMethod::FiducciaMattheyses,
            max_iterations: 50,
            improvement_threshold: 1e-4,
        },
        vcycle_config: VCycleConfig {
            max_vcycles: 3,
            convergence_tolerance: 1e-6,
            smoothing_iterations: 2,
        },
    };

    let mut solver = HierarchicalSolver::new(config);

    // Create a medium-sized QUBO problem
    let size = 20;
    let mut qubo = Array2::zeros((size, size));
    
    // Add some structure - blocks with internal coupling
    for block in 0..4 {
        let start = block * 5;
        let end = (block + 1) * 5;
        
        for i in start..end {
            for j in start..end {
                if i != j {
                    qubo[[i, j]] = -1.0; // Prefer same values within block
                }
            }
        }
    }

    // Add some inter-block coupling
    for i in 0..size-1 {
        qubo[[i, i+1]] = 0.1;
        qubo[[i+1, i]] = 0.1;
    }

    let mut var_map = HashMap::new();
    for i in 0..size {
        var_map.insert(format!("x{}", i), i);
    }

    let result = solver.solve(&qubo, &var_map, 100);
    assert!(result.is_ok());
    
    let sample_result = result.unwrap();
    assert!(!sample_result.samples.is_empty());
    
    // Verify solution format
    let best_sample = &sample_result.samples[0];
    assert_eq!(best_sample.assignments.len(), size);
    
    // All variables should be assigned
    for i in 0..size {
        let var_name = format!("x{}", i);
        assert!(best_sample.assignments.contains_key(&var_name));
    }
}

#[test]
fn test_hierarchical_solver_vcycle() {
    let config = HierarchicalSolverConfig {
        coarsening_strategy: CoarseningStrategy::MatchingBased,
        max_levels: 2,
        coarsening_threshold: 5,
        solver_strategy: SolverStrategy::VCycle,
        refinement_config: RefinementConfig {
            method: RefinementMethod::LocalSearch,
            max_iterations: 20,
            improvement_threshold: 1e-5,
        },
        vcycle_config: VCycleConfig {
            max_vcycles: 2,
            convergence_tolerance: 1e-5,
            smoothing_iterations: 1,
        },
    };

    let mut solver = HierarchicalSolver::new(config);

    // Create a simple clustering problem
    let size = 12;
    let mut qubo = Array2::zeros((size, size));
    
    // Create 3 clusters of 4 variables each
    for cluster in 0..3 {
        let start = cluster * 4;
        let end = (cluster + 1) * 4;
        
        // Strong intra-cluster connections
        for i in start..end {
            for j in start..end {
                if i != j {
                    qubo[[i, j]] = -2.0;
                }
            }
        }
    }
    
    // Weak inter-cluster repulsion
    for cluster1 in 0..3 {
        for cluster2 in cluster1+1..3 {
            let start1 = cluster1 * 4;
            let end1 = (cluster1 + 1) * 4;
            let start2 = cluster2 * 4;
            let end2 = (cluster2 + 1) * 4;
            
            for i in start1..end1 {
                for j in start2..end2 {
                    qubo[[i, j]] = 0.5;
                    qubo[[j, i]] = 0.5;
                }
            }
        }
    }

    let mut var_map = HashMap::new();
    for i in 0..size {
        var_map.insert(format!("v{}", i), i);
    }

    let result = solver.solve(&qubo, &var_map, 50);
    assert!(result.is_ok());
    
    let sample_result = result.unwrap();
    assert!(!sample_result.samples.is_empty());
    
    // Check that solution is reasonable
    let best_sample = &sample_result.samples[0];
    println!("Best energy: {}", best_sample.energy);
    
    // For this problem, optimal solution should have clusters with consistent values
    // (all 0 or all 1 within each cluster)
    for cluster in 0..3 {
        let start = cluster * 4;
        let cluster_values: Vec<bool> = (start..start+4)
            .map(|i| *best_sample.assignments.get(&format!("v{}", i)).unwrap())
            .collect();
        
        // All values in cluster should be the same
        let first_value = cluster_values[0];
        let all_same = cluster_values.iter().all(|&v| v == first_value);
        
        if !all_same {
            println!("Cluster {} values: {:?}", cluster, cluster_values);
        }
        // Note: Due to the heuristic nature, this might not always be perfect
        // but should be reasonable most of the time
    }
}

#[test]
fn test_decomposition_integration() {
    // Test that graph partitioner and hierarchical solver work together
    let partitioner = GraphPartitioner::with_config(PartitioningAlgorithm::KernighanLin, 2);

    let hierarchical_config = HierarchicalSolverConfig {
        coarsening_strategy: CoarseningStrategy::MatchingBased,
        max_levels: 2,
        coarsening_threshold: 4,
        solver_strategy: SolverStrategy::Direct,
        refinement_config: RefinementConfig {
            method: RefinementMethod::LocalSearch,
            max_iterations: 30,
            improvement_threshold: 1e-4,
        },
        vcycle_config: VCycleConfig {
            max_vcycles: 1,
            convergence_tolerance: 1e-4,
            smoothing_iterations: 1,
        },
    };

    let partitioner = GraphPartitioner::new(partition_config);
    let mut hierarchical_solver = HierarchicalSolver::new(hierarchical_config);

    // Create a structured problem
    let size = 16;
    let mut qubo = Array2::zeros((size, size));
    
    // Create 4 blocks of 4 variables each
    for block in 0..4 {
        let start = block * 4;
        let end = (block + 1) * 4;
        
        for i in start..end {
            for j in start..end {
                if i != j {
                    qubo[[i, j]] = -1.5;
                }
            }
        }
    }

    // Step 1: Partition the problem
    let partition_result = partitioner.partition(&qubo);
    assert!(partition_result.is_ok());
    
    let subproblems = partition_result.unwrap();
    assert!(!subproblems.is_empty());
    
    println!("Created {} subproblems", subproblems.len());

    // Step 2: Solve each subproblem with hierarchical solver
    let mut all_solutions = Vec::new();
    
    for (idx, subproblem) in subproblems.iter().enumerate() {
        println!("Solving subproblem {} with {} variables", idx, subproblem.variables.len());
        
        let mut var_map = HashMap::new();
        for (local_idx, &global_idx) in subproblem.variables.iter().enumerate() {
            var_map.insert(format!("x{}", global_idx), local_idx);
        }
        
        let sub_result = hierarchical_solver.solve(&subproblem.qubo, &var_map, 20);
        
        if let Ok(sample_result) = sub_result {
            all_solutions.push((idx, sample_result));
        }
    }
    
    assert!(!all_solutions.is_empty());
    println!("Successfully solved {} out of {} subproblems", 
             all_solutions.len(), subproblems.len());
}

#[test]
fn test_subproblem_metrics() {
    // Test that subproblem metrics are calculated correctly
    let variables = vec![0, 1, 2, 3];
    let mut qubo = Array2::zeros((4, 4));
    
    // Create a simple connectivity pattern
    qubo[[0, 1]] = -1.0;
    qubo[[1, 0]] = -1.0;
    qubo[[1, 2]] = -0.5;
    qubo[[2, 1]] = -0.5;
    qubo[[2, 3]] = -2.0;
    qubo[[3, 2]] = -2.0;

    let subproblem = Subproblem {
        variables,
        qubo: qubo.clone(),
        metrics: SubproblemMetrics {
            connectivity: 0.0, // Will be calculated
            density: 0.0,      // Will be calculated
            cut_size: 0.0,     // Will be calculated
            modularity: 0.0,   // Will be calculated
        },
    };

    // In a real implementation, metrics would be calculated during partitioning
    // Here we just verify the structure is correct
    
    assert_eq!(subproblem.variables.len(), 4);
    assert_eq!(subproblem.qubo.shape(), &[4, 4]);
    
    // Count non-zero entries (should be 6: three pairs with symmetric entries)
    let mut non_zero_count = 0;
    for i in 0..4 {
        for j in 0..4 {
            if qubo[[i, j]].abs() > 1e-10 {
                non_zero_count += 1;
            }
        }
    }
    assert_eq!(non_zero_count, 6);
}