Skip to main content

quantrs2_sim/qaoa_optimization/
qaoaoptimizer_solve_classically_group.rs

1//! # QAOAOptimizer - solve_classically_group Methods
2//!
3//! This module contains method implementations for `QAOAOptimizer`.
4//!
5//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)
6
7use crate::error::Result;
8use scirs2_core::random::prelude::*;
9
10use super::types::QAOAProblemType;
11
12use super::qaoaoptimizer_type::QAOAOptimizer;
13
14impl QAOAOptimizer {
15    /// Solve problem classically for comparison
16    pub(super) fn solve_classically(&self) -> Result<f64> {
17        match self.problem_type {
18            QAOAProblemType::MaxCut => self.solve_maxcut_classically(),
19            QAOAProblemType::MaxWeightIndependentSet => self.solve_mwis_classically(),
20            _ => self.solve_brute_force(),
21        }
22    }
23    /// Solve MWIS classically (greedy)
24    pub(super) fn solve_mwis_classically(&self) -> Result<f64> {
25        let mut vertices: Vec<usize> = (0..self.graph.num_vertices).collect();
26        vertices.sort_by(|&a, &b| {
27            let weight_a = self.graph.vertex_weights.get(a).unwrap_or(&1.0);
28            let weight_b = self.graph.vertex_weights.get(b).unwrap_or(&1.0);
29            weight_b
30                .partial_cmp(weight_a)
31                .unwrap_or(std::cmp::Ordering::Equal)
32        });
33        let mut selected = vec![false; self.graph.num_vertices];
34        let mut total_weight = 0.0;
35        for &v in &vertices {
36            let mut can_select = true;
37            for &u in &vertices {
38                if selected[u] && self.graph.adjacency_matrix[[u, v]] > 0.0 {
39                    can_select = false;
40                    break;
41                }
42            }
43            if can_select {
44                selected[v] = true;
45                total_weight += self.graph.vertex_weights.get(v).unwrap_or(&1.0);
46            }
47        }
48        Ok(total_weight)
49    }
50}