quantrs2-anneal 0.1.3

Quantum annealing support 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! Telecommunications Industry Optimization
//!
//! This module provides optimization solutions for the telecommunications industry,
//! including network topology optimization, traffic routing, infrastructure placement,
//! spectrum allocation, and quality of service optimization.

use super::{
    ApplicationError, ApplicationResult, IndustryConstraint, IndustryObjective, IndustrySolution,
    OptimizationProblem,
};
use crate::ising::IsingModel;
use crate::qubo::{QuboBuilder, QuboFormulation};
use crate::simulator::{AnnealingParams, ClassicalAnnealingSimulator};
use std::collections::HashMap;

use std::fmt::Write;
/// Network Topology Optimization Problem
#[derive(Debug, Clone)]
pub struct NetworkTopologyOptimization {
    /// Number of network nodes
    pub num_nodes: usize,
    /// Potential connections between nodes
    pub potential_connections: Vec<(usize, usize)>,
    /// Connection costs
    pub connection_costs: Vec<f64>,
    /// Connection capacities
    pub connection_capacities: Vec<f64>,
    /// Traffic demand matrix \[source\]\[destination\]
    pub traffic_demands: Vec<Vec<f64>>,
    /// Reliability requirements for connections
    pub reliability_requirements: Vec<f64>,
    /// Maximum network latency allowed
    pub max_latency: f64,
    /// Redundancy requirements
    pub redundancy_level: usize,
    /// Quality of Service constraints
    pub qos_constraints: Vec<IndustryConstraint>,
}

impl NetworkTopologyOptimization {
    /// Create a new network topology optimization problem
    pub fn new(
        num_nodes: usize,
        potential_connections: Vec<(usize, usize)>,
        connection_costs: Vec<f64>,
        traffic_demands: Vec<Vec<f64>>,
    ) -> ApplicationResult<Self> {
        if connection_costs.len() != potential_connections.len() {
            return Err(ApplicationError::InvalidConfiguration(
                "Connection costs must match number of potential connections".to_string(),
            ));
        }

        if traffic_demands.len() != num_nodes {
            return Err(ApplicationError::InvalidConfiguration(
                "Traffic demand matrix dimension mismatch".to_string(),
            ));
        }

        for row in &traffic_demands {
            if row.len() != num_nodes {
                return Err(ApplicationError::InvalidConfiguration(
                    "Traffic demand matrix is not square".to_string(),
                ));
            }
        }

        Ok(Self {
            num_nodes,
            potential_connections: potential_connections.clone(),
            connection_costs,
            connection_capacities: vec![100.0; potential_connections.len()], // Default capacity
            traffic_demands,
            reliability_requirements: vec![0.99; potential_connections.len()], // 99% reliability
            max_latency: 100.0,                                                // 100ms max latency
            redundancy_level: 2,                                               // Dual redundancy
            qos_constraints: Vec::new(),
        })
    }

    /// Set connection capacities
    pub fn set_connection_capacities(&mut self, capacities: Vec<f64>) -> ApplicationResult<()> {
        if capacities.len() != self.potential_connections.len() {
            return Err(ApplicationError::InvalidConfiguration(
                "Capacities must match number of potential connections".to_string(),
            ));
        }

        self.connection_capacities = capacities;
        Ok(())
    }

    /// Calculate network connectivity
    #[must_use]
    pub fn calculate_connectivity(&self, topology: &NetworkTopology) -> f64 {
        let mut connectivity_matrix = vec![vec![false; self.num_nodes]; self.num_nodes];

        // Mark direct connections
        for (i, &active) in topology.active_connections.iter().enumerate() {
            if active {
                let (u, v) = self.potential_connections[i];
                connectivity_matrix[u][v] = true;
                connectivity_matrix[v][u] = true;
            }
        }

        // Floyd-Warshall to find all-pairs connectivity
        for k in 0..self.num_nodes {
            for i in 0..self.num_nodes {
                for j in 0..self.num_nodes {
                    connectivity_matrix[i][j] |=
                        connectivity_matrix[i][k] && connectivity_matrix[k][j];
                }
            }
        }

        // Calculate connectivity ratio
        let mut connected_pairs = 0;
        let total_pairs = self.num_nodes * (self.num_nodes - 1);

        for i in 0..self.num_nodes {
            for j in 0..self.num_nodes {
                if i != j && connectivity_matrix[i][j] {
                    connected_pairs += 1;
                }
            }
        }

        f64::from(connected_pairs) / total_pairs as f64
    }

    /// Calculate network latency
    #[must_use]
    pub fn calculate_network_latency(&self, topology: &NetworkTopology) -> f64 {
        // Simplified latency calculation based on path lengths
        let mut distance_matrix = vec![vec![f64::INFINITY; self.num_nodes]; self.num_nodes];

        // Initialize distances
        for i in 0..self.num_nodes {
            distance_matrix[i][i] = 0.0;
        }

        for (i, &active) in topology.active_connections.iter().enumerate() {
            if active {
                let (u, v) = self.potential_connections[i];
                let latency = 1.0; // Simplified: 1ms per hop
                distance_matrix[u][v] = latency;
                distance_matrix[v][u] = latency;
            }
        }

        // Floyd-Warshall for shortest paths
        for k in 0..self.num_nodes {
            for i in 0..self.num_nodes {
                for j in 0..self.num_nodes {
                    if distance_matrix[i][k] + distance_matrix[k][j] < distance_matrix[i][j] {
                        distance_matrix[i][j] = distance_matrix[i][k] + distance_matrix[k][j];
                    }
                }
            }
        }

        // Average latency for all connected pairs
        let mut total_latency = 0.0;
        let mut connected_pairs = 0;

        for i in 0..self.num_nodes {
            for j in 0..self.num_nodes {
                if i != j && distance_matrix[i][j] < f64::INFINITY {
                    total_latency += distance_matrix[i][j];
                    connected_pairs += 1;
                }
            }
        }

        if connected_pairs > 0 {
            total_latency / f64::from(connected_pairs)
        } else {
            f64::INFINITY
        }
    }

    /// Calculate total network cost
    #[must_use]
    pub fn calculate_total_cost(&self, topology: &NetworkTopology) -> f64 {
        topology
            .active_connections
            .iter()
            .enumerate()
            .filter(|(_, &active)| active)
            .map(|(i, _)| self.connection_costs[i])
            .sum()
    }
}

impl OptimizationProblem for NetworkTopologyOptimization {
    type Solution = NetworkTopology;
    type ObjectiveValue = f64;

    fn description(&self) -> String {
        format!(
            "Network topology optimization with {} nodes and {} potential connections",
            self.num_nodes,
            self.potential_connections.len()
        )
    }

    fn size_metrics(&self) -> HashMap<String, usize> {
        let mut metrics = HashMap::new();
        metrics.insert("num_nodes".to_string(), self.num_nodes);
        metrics.insert(
            "num_potential_connections".to_string(),
            self.potential_connections.len(),
        );
        metrics.insert(
            "num_qos_constraints".to_string(),
            self.qos_constraints.len(),
        );
        metrics
    }

    fn validate(&self) -> ApplicationResult<()> {
        if self.num_nodes < 2 {
            return Err(ApplicationError::DataValidationError(
                "At least 2 nodes required".to_string(),
            ));
        }

        if self.potential_connections.is_empty() {
            return Err(ApplicationError::DataValidationError(
                "At least one potential connection required".to_string(),
            ));
        }

        // Validate node indices in connections
        for &(u, v) in &self.potential_connections {
            if u >= self.num_nodes || v >= self.num_nodes {
                return Err(ApplicationError::DataValidationError(
                    "Connection references invalid node index".to_string(),
                ));
            }
        }

        // Check positive costs and capacities
        for &cost in &self.connection_costs {
            if cost < 0.0 {
                return Err(ApplicationError::DataValidationError(
                    "Connection costs must be non-negative".to_string(),
                ));
            }
        }

        for &capacity in &self.connection_capacities {
            if capacity <= 0.0 {
                return Err(ApplicationError::DataValidationError(
                    "Connection capacities must be positive".to_string(),
                ));
            }
        }

        Ok(())
    }

    fn to_qubo(&self) -> ApplicationResult<(crate::ising::QuboModel, HashMap<String, usize>)> {
        let mut builder = QuboBuilder::new();
        let num_connections = self.potential_connections.len();
        let mut string_var_map = HashMap::new();

        // Create string variable mapping
        for i in 0..num_connections {
            string_var_map.insert(format!("x_{i}"), i);
        }

        // Binary variables: x[i] = 1 if connection i is active
        for i in 0..num_connections {
            // Cost term
            builder.add_bias(i, self.connection_costs[i]);

            // Connectivity benefit (negative to encourage connections)
            let connectivity_benefit = -50.0; // Encourage network connectivity
            builder.add_bias(i, connectivity_benefit);
        }

        // Redundancy constraints: ensure multiple paths between critical nodes
        let redundancy_penalty = 1000.0;
        for node in 0..self.num_nodes {
            let mut adjacent_connections = Vec::new();

            for (conn_idx, &(u, v)) in self.potential_connections.iter().enumerate() {
                if u == node || v == node {
                    adjacent_connections.push(conn_idx);
                }
            }

            // Penalty for having too few connections per node
            if adjacent_connections.len() >= self.redundancy_level {
                for i in 0..adjacent_connections.len() {
                    for j in (i + 1)..adjacent_connections.len() {
                        let var1 = adjacent_connections[i];
                        let var2 = adjacent_connections[j];
                        // Encourage having multiple connections per node
                        builder.add_coupling(var1, var2, -redundancy_penalty / 2.0);
                    }
                }
            }
        }

        // Traffic capacity constraints
        let capacity_penalty = 500.0;
        for (conn_idx, &(u, v)) in self.potential_connections.iter().enumerate() {
            let traffic_demand = self.traffic_demands[u][v] + self.traffic_demands[v][u];
            let capacity = self.connection_capacities[conn_idx];

            if traffic_demand > capacity {
                // Penalty for insufficient capacity
                builder.add_bias(conn_idx, capacity_penalty * (traffic_demand - capacity));
            }
        }

        Ok((builder.build(), string_var_map))
    }

    fn evaluate_solution(
        &self,
        solution: &Self::Solution,
    ) -> ApplicationResult<Self::ObjectiveValue> {
        let total_cost = self.calculate_total_cost(solution);
        let connectivity = self.calculate_connectivity(solution);
        let latency = self.calculate_network_latency(solution);

        // Multi-objective: minimize cost and latency, maximize connectivity
        let connectivity_weight = 100.0;
        let latency_penalty = 10.0;

        Ok(total_cost + latency_penalty * latency - connectivity_weight * connectivity)
    }

    fn is_feasible(&self, solution: &Self::Solution) -> bool {
        // Check connectivity requirements
        let connectivity = self.calculate_connectivity(solution);
        if connectivity < 0.8 {
            // At least 80% connectivity
            return false;
        }

        // Check latency constraints
        let latency = self.calculate_network_latency(solution);
        if latency > self.max_latency {
            return false;
        }

        // Check traffic capacity constraints
        for (conn_idx, &active) in solution.active_connections.iter().enumerate() {
            if active {
                let (u, v) = self.potential_connections[conn_idx];
                let traffic_demand = self.traffic_demands[u][v] + self.traffic_demands[v][u];
                let capacity = self.connection_capacities[conn_idx];

                if traffic_demand > capacity * 1.1 {
                    // Allow 10% overutilization
                    return false;
                }
            }
        }

        true
    }
}

/// Network Topology Solution
#[derive(Debug, Clone)]
pub struct NetworkTopology {
    /// Which connections are active
    pub active_connections: Vec<bool>,
    /// Total network cost
    pub total_cost: f64,
    /// Network connectivity ratio
    pub connectivity: f64,
    /// Average network latency
    pub average_latency: f64,
    /// Network performance metrics
    pub performance_metrics: TelecomMetrics,
}

/// Telecommunications performance metrics
#[derive(Debug, Clone)]
pub struct TelecomMetrics {
    /// Network throughput (Gbps)
    pub throughput: f64,
    /// Packet loss rate
    pub packet_loss_rate: f64,
    /// Jitter (ms)
    pub jitter: f64,
    /// Network availability
    pub availability: f64,
    /// Mean time between failures (hours)
    pub mtbf: f64,
    /// Coverage area (km²)
    pub coverage_area: f64,
}

impl IndustrySolution for NetworkTopology {
    type Problem = NetworkTopologyOptimization;

    fn from_binary(problem: &Self::Problem, binary_solution: &[i8]) -> ApplicationResult<Self> {
        let num_connections = problem.potential_connections.len();
        let mut active_connections = vec![false; num_connections];

        // Decode binary solution
        for i in 0..num_connections.min(binary_solution.len()) {
            active_connections[i] = binary_solution[i] == 1;
        }

        let total_cost = problem.calculate_total_cost(&Self {
            active_connections: active_connections.clone(),
            total_cost: 0.0,
            connectivity: 0.0,
            average_latency: 0.0,
            performance_metrics: TelecomMetrics {
                throughput: 0.0,
                packet_loss_rate: 0.0,
                jitter: 0.0,
                availability: 0.0,
                mtbf: 0.0,
                coverage_area: 0.0,
            },
        });

        let connectivity = problem.calculate_connectivity(&Self {
            active_connections: active_connections.clone(),
            total_cost: 0.0,
            connectivity: 0.0,
            average_latency: 0.0,
            performance_metrics: TelecomMetrics {
                throughput: 0.0,
                packet_loss_rate: 0.0,
                jitter: 0.0,
                availability: 0.0,
                mtbf: 0.0,
                coverage_area: 0.0,
            },
        });

        let average_latency = problem.calculate_network_latency(&Self {
            active_connections: active_connections.clone(),
            total_cost: 0.0,
            connectivity: 0.0,
            average_latency: 0.0,
            performance_metrics: TelecomMetrics {
                throughput: 0.0,
                packet_loss_rate: 0.0,
                jitter: 0.0,
                availability: 0.0,
                mtbf: 0.0,
                coverage_area: 0.0,
            },
        });

        // Calculate performance metrics
        let num_active = active_connections.iter().filter(|&&x| x).count();
        let performance_metrics = TelecomMetrics {
            throughput: num_active as f64 * 10.0, // 10 Gbps per connection
            packet_loss_rate: 0.001,              // 0.1% packet loss
            jitter: 2.0,                          // 2ms jitter
            availability: 0.999,                  // 99.9% availability
            mtbf: 8760.0,                         // 1 year MTBF
            coverage_area: num_active as f64 * 100.0, // 100 km² per connection
        };

        Ok(Self {
            active_connections,
            total_cost,
            connectivity,
            average_latency,
            performance_metrics,
        })
    }

    fn summary(&self) -> HashMap<String, String> {
        let mut summary = HashMap::new();
        summary.insert("type".to_string(), "Network Topology".to_string());
        summary.insert("total_cost".to_string(), format!("${:.2}", self.total_cost));
        summary.insert(
            "connectivity".to_string(),
            format!("{:.1}%", self.connectivity * 100.0),
        );
        summary.insert(
            "average_latency".to_string(),
            format!("{:.1} ms", self.average_latency),
        );
        summary.insert(
            "throughput".to_string(),
            format!("{:.1} Gbps", self.performance_metrics.throughput),
        );
        summary.insert(
            "availability".to_string(),
            format!("{:.3}%", self.performance_metrics.availability * 100.0),
        );

        let num_active = self.active_connections.iter().filter(|&&x| x).count();
        summary.insert("active_connections".to_string(), num_active.to_string());

        summary
    }

    fn metrics(&self) -> HashMap<String, f64> {
        let mut metrics = HashMap::new();
        metrics.insert("total_cost".to_string(), self.total_cost);
        metrics.insert("connectivity".to_string(), self.connectivity);
        metrics.insert("average_latency".to_string(), self.average_latency);
        metrics.insert(
            "throughput".to_string(),
            self.performance_metrics.throughput,
        );
        metrics.insert(
            "packet_loss_rate".to_string(),
            self.performance_metrics.packet_loss_rate,
        );
        metrics.insert("jitter".to_string(), self.performance_metrics.jitter);
        metrics.insert(
            "availability".to_string(),
            self.performance_metrics.availability,
        );
        metrics.insert("mtbf".to_string(), self.performance_metrics.mtbf);
        metrics.insert(
            "coverage_area".to_string(),
            self.performance_metrics.coverage_area,
        );

        let num_active = self.active_connections.iter().filter(|&&x| x).count();
        metrics.insert("active_connections".to_string(), num_active as f64);

        metrics
    }

    fn export_format(&self) -> ApplicationResult<String> {
        let mut output = String::new();
        output.push_str("# Network Topology Optimization Report\n\n");

        output.push_str("## Network Summary\n");
        writeln!(output, "Total Cost: ${:.2}", self.total_cost)
            .expect("writing to String is infallible");
        writeln!(output, "Connectivity: {:.1}%", self.connectivity * 100.0)
            .expect("writing to String is infallible");
        writeln!(output, "Average Latency: {:.1} ms", self.average_latency)
            .expect("writing to String is infallible");

        output.push_str("\n## Performance Metrics\n");
        write!(
            output,
            "Throughput: {:.1} Gbps\n",
            self.performance_metrics.throughput
        )
        .expect("writing to String is infallible");
        write!(
            output,
            "Packet Loss Rate: {:.3}%\n",
            self.performance_metrics.packet_loss_rate * 100.0
        )
        .expect("writing to String is infallible");
        write!(
            output,
            "Jitter: {:.1} ms\n",
            self.performance_metrics.jitter
        )
        .expect("writing to String is infallible");
        write!(
            output,
            "Availability: {:.3}%\n",
            self.performance_metrics.availability * 100.0
        )
        .expect("writing to String is infallible");
        writeln!(output, "MTBF: {:.1} hours", self.performance_metrics.mtbf)
            .expect("writing to String is infallible");
        write!(
            output,
            "Coverage Area: {:.1} km²\n",
            self.performance_metrics.coverage_area
        )
        .expect("writing to String is infallible");

        output.push_str("\n## Active Connections\n");
        for (i, &active) in self.active_connections.iter().enumerate() {
            if active {
                writeln!(output, "Connection {}: Active", i + 1)
                    .expect("writing to String is infallible");
            }
        }

        Ok(output)
    }
}

/// Spectrum Allocation Optimization Problem
#[derive(Debug, Clone)]
pub struct SpectrumAllocation {
    /// Number of frequency bands
    pub num_bands: usize,
    /// Number of geographic regions
    pub num_regions: usize,
    /// Interference matrix between bands
    pub interference_matrix: Vec<Vec<f64>>,
    /// Service demand by region and band
    pub service_demands: Vec<Vec<f64>>,
    /// Band availability by region
    pub band_availability: Vec<Vec<bool>>,
    /// Regulatory constraints
    pub regulatory_constraints: Vec<IndustryConstraint>,
    /// Quality of Service requirements
    pub qos_requirements: Vec<f64>,
}

impl SpectrumAllocation {
    /// Create new spectrum allocation problem
    pub fn new(
        num_bands: usize,
        num_regions: usize,
        interference_matrix: Vec<Vec<f64>>,
        service_demands: Vec<Vec<f64>>,
    ) -> ApplicationResult<Self> {
        if interference_matrix.len() != num_bands {
            return Err(ApplicationError::InvalidConfiguration(
                "Interference matrix dimension mismatch".to_string(),
            ));
        }

        Ok(Self {
            num_bands,
            num_regions,
            interference_matrix,
            service_demands,
            band_availability: vec![vec![true; num_bands]; num_regions],
            regulatory_constraints: Vec::new(),
            qos_requirements: vec![0.95; num_regions],
        })
    }

    /// Calculate interference for a given allocation
    #[must_use]
    pub fn calculate_interference(&self, allocation: &SpectrumSolution) -> f64 {
        let mut total_interference = 0.0;

        for region in 0..self.num_regions {
            for band1 in 0..self.num_bands {
                for band2 in 0..self.num_bands {
                    if band1 != band2
                        && allocation.band_assignments[region][band1]
                        && allocation.band_assignments[region][band2]
                    {
                        total_interference += self.interference_matrix[band1][band2];
                    }
                }
            }
        }

        total_interference
    }
}

/// Spectrum Allocation Solution
#[derive(Debug, Clone)]
pub struct SpectrumSolution {
    /// Band assignments \[region\]\[band\] = assigned
    pub band_assignments: Vec<Vec<bool>>,
    /// Total interference
    pub total_interference: f64,
    /// Service coverage achieved
    pub service_coverage: Vec<f64>,
    /// Spectrum utilization efficiency
    pub spectrum_efficiency: f64,
}

/// Binary wrapper for Network Topology Optimization that works with binary solutions
#[derive(Debug, Clone)]
pub struct BinaryNetworkTopologyOptimization {
    inner: NetworkTopologyOptimization,
}

impl BinaryNetworkTopologyOptimization {
    #[must_use]
    pub const fn new(inner: NetworkTopologyOptimization) -> Self {
        Self { inner }
    }
}

impl OptimizationProblem for BinaryNetworkTopologyOptimization {
    type Solution = Vec<i8>;
    type ObjectiveValue = f64;

    fn description(&self) -> String {
        self.inner.description()
    }

    fn size_metrics(&self) -> HashMap<String, usize> {
        self.inner.size_metrics()
    }

    fn validate(&self) -> ApplicationResult<()> {
        self.inner.validate()
    }

    fn to_qubo(&self) -> ApplicationResult<(crate::ising::QuboModel, HashMap<String, usize>)> {
        self.inner.to_qubo()
    }

    fn evaluate_solution(
        &self,
        solution: &Self::Solution,
    ) -> ApplicationResult<Self::ObjectiveValue> {
        // Convert binary solution to NetworkTopology for evaluation
        let topology_solution = NetworkTopology::from_binary(&self.inner, solution)?;
        self.inner.evaluate_solution(&topology_solution)
    }

    fn is_feasible(&self, solution: &Self::Solution) -> bool {
        // Convert binary solution to NetworkTopology for feasibility check
        if let Ok(topology_solution) = NetworkTopology::from_binary(&self.inner, solution) {
            self.inner.is_feasible(&topology_solution)
        } else {
            false
        }
    }
}

/// Create benchmark telecommunications problems
pub fn create_benchmark_problems(
    size: usize,
) -> ApplicationResult<Vec<Box<dyn OptimizationProblem<Solution = Vec<i8>, ObjectiveValue = f64>>>>
{
    let mut problems = Vec::new();

    // Problem 1: Small network topology optimization
    let potential_connections = vec![(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)];
    let connection_costs = vec![10.0, 15.0, 8.0, 12.0, 9.0];
    let traffic_demands = vec![
        vec![0.0, 5.0, 3.0, 2.0],
        vec![5.0, 0.0, 4.0, 6.0],
        vec![3.0, 4.0, 0.0, 3.0],
        vec![2.0, 6.0, 3.0, 0.0],
    ];

    let network_problem = NetworkTopologyOptimization::new(
        4, // nodes
        potential_connections,
        connection_costs,
        traffic_demands,
    )?;

    problems.push(
        Box::new(BinaryNetworkTopologyOptimization::new(network_problem))
            as Box<dyn OptimizationProblem<Solution = Vec<i8>, ObjectiveValue = f64>>,
    );

    // Problem 2: Larger network for more complex scenarios
    if size >= 6 {
        let mut large_connections = Vec::new();
        let mut large_costs = Vec::new();

        // Create a more connected network
        for i in 0..size {
            for j in (i + 1)..size {
                large_connections.push((i, j));
                large_costs.push(((i + j) as f64).mul_add(1.5, 5.0));
            }
        }

        let large_demands = vec![vec![2.0; size]; size];

        let large_network =
            NetworkTopologyOptimization::new(size, large_connections, large_costs, large_demands)?;

        problems.push(
            Box::new(BinaryNetworkTopologyOptimization::new(large_network))
                as Box<dyn OptimizationProblem<Solution = Vec<i8>, ObjectiveValue = f64>>,
        );
    }

    Ok(problems)
}

/// Solve network topology optimization using quantum annealing
pub fn solve_network_topology(
    problem: &NetworkTopologyOptimization,
    params: Option<AnnealingParams>,
) -> ApplicationResult<NetworkTopology> {
    // Convert to QUBO
    let (qubo, _var_map) = problem.to_qubo()?;

    // Convert to Ising
    let ising = IsingModel::from_qubo(&qubo);

    // Set up annealing parameters
    let annealing_params = params.unwrap_or_else(|| {
        let mut p = AnnealingParams::default();
        p.num_sweeps = 25_000;
        p.num_repetitions = 40;
        p.initial_temperature = 5.0;
        p.final_temperature = 0.001;
        p
    });

    // Solve with classical annealing
    let simulator = ClassicalAnnealingSimulator::new(annealing_params)
        .map_err(|e| ApplicationError::OptimizationError(e.to_string()))?;

    let result = simulator
        .solve(&ising)
        .map_err(|e| ApplicationError::OptimizationError(e.to_string()))?;

    // Convert solution back to network topology
    NetworkTopology::from_binary(problem, &result.best_spins)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_network_topology_creation() {
        let connections = vec![(0, 1), (1, 2), (0, 2)];
        let costs = vec![10.0, 15.0, 12.0];
        let demands = vec![
            vec![0.0, 5.0, 3.0],
            vec![5.0, 0.0, 4.0],
            vec![3.0, 4.0, 0.0],
        ];

        let network = NetworkTopologyOptimization::new(3, connections, costs, demands)
            .expect("failed to create network topology in test");
        assert_eq!(network.num_nodes, 3);
        assert_eq!(network.potential_connections.len(), 3);
    }

    #[test]
    fn test_network_connectivity_calculation() {
        let connections = vec![(0, 1), (1, 2)];
        let costs = vec![10.0, 15.0];
        let demands = vec![
            vec![0.0, 1.0, 0.0],
            vec![1.0, 0.0, 1.0],
            vec![0.0, 1.0, 0.0],
        ];

        let network = NetworkTopologyOptimization::new(3, connections, costs, demands)
            .expect("failed to create network topology in test");

        let topology = NetworkTopology {
            active_connections: vec![true, true],
            total_cost: 25.0,
            connectivity: 0.0,
            average_latency: 0.0,
            performance_metrics: TelecomMetrics {
                throughput: 0.0,
                packet_loss_rate: 0.0,
                jitter: 0.0,
                availability: 0.0,
                mtbf: 0.0,
                coverage_area: 0.0,
            },
        };

        let connectivity = network.calculate_connectivity(&topology);
        assert_eq!(connectivity, 1.0); // All nodes connected
    }

    #[test]
    fn test_network_cost_calculation() {
        let connections = vec![(0, 1), (1, 2)];
        let costs = vec![10.0, 15.0];
        let demands = vec![vec![0.0; 3]; 3];

        let network = NetworkTopologyOptimization::new(3, connections, costs, demands)
            .expect("failed to create network topology in test");

        let topology = NetworkTopology {
            active_connections: vec![true, false],
            total_cost: 0.0,
            connectivity: 0.0,
            average_latency: 0.0,
            performance_metrics: TelecomMetrics {
                throughput: 0.0,
                packet_loss_rate: 0.0,
                jitter: 0.0,
                availability: 0.0,
                mtbf: 0.0,
                coverage_area: 0.0,
            },
        };

        let cost = network.calculate_total_cost(&topology);
        assert_eq!(cost, 10.0);
    }

    #[test]
    fn test_spectrum_allocation_creation() {
        let interference_matrix = vec![
            vec![0.0, 0.3, 0.1],
            vec![0.3, 0.0, 0.4],
            vec![0.1, 0.4, 0.0],
        ];
        let demands = vec![vec![1.0, 2.0, 3.0], vec![2.0, 1.0, 2.0]];

        let spectrum = SpectrumAllocation::new(3, 2, interference_matrix, demands)
            .expect("failed to create spectrum allocation in test");
        assert_eq!(spectrum.num_bands, 3);
        assert_eq!(spectrum.num_regions, 2);
    }

    #[test]
    fn test_network_validation() {
        let connections = vec![(0, 1), (1, 2)];
        let costs = vec![10.0, 15.0];
        let demands = vec![vec![0.0; 3]; 3];

        let network = NetworkTopologyOptimization::new(3, connections, costs, demands.clone())
            .expect("failed to create network topology in test");
        assert!(network.validate().is_ok());

        // Test invalid network (node index out of bounds)
        let invalid_connections = vec![(0, 1), (1, 5)]; // Node 5 doesn't exist
        let invalid_costs = vec![10.0, 15.0];
        let invalid_network =
            NetworkTopologyOptimization::new(3, invalid_connections, invalid_costs, demands);
        assert!(invalid_network.is_ok()); // Created successfully
        assert!(invalid_network
            .expect("failed to create invalid network in test")
            .validate()
            .is_err()); // But validation fails
    }

    #[test]
    fn test_benchmark_problems() {
        let problems =
            create_benchmark_problems(6).expect("failed to create benchmark problems in test");
        assert_eq!(problems.len(), 2);

        for problem in &problems {
            assert!(problem.validate().is_ok());
        }
    }
}