Source code for quantum_launcher.problems.problem_initialization.maxcut

 1"""  This module contains the MaxCut class."""
 2from typing import Optional
 3import networkx as nx
 4import matplotlib.pyplot as plt
 5
 6from quantum_launcher.base import Problem
 7
 8
[docs] 9class MaxCut(Problem): 10 """ 11 Class for MaxCut Problem. 12 13 This class represents MaxCut Problem which is a combinatorial optimization problem that involves partitioning the 14 vertices of a graph into two sets such that the number of edges between the two sets is maximized. The class contains 15 an instance of the problem, so it can be passed into Quantum Launcher. 16 17 Attributes: 18 instance (nx.Graph): The graph instance representing the problem. 19 20 """ 21 22 def __init__(self, instance: nx.Graph, instance_name='unnamed'): 23 super().__init__(instance, instance_name) 24 25 @property 26 def setup(self) -> dict: 27 return { 28 'instance_name': self.instance_name 29 } 30
[docs] 31 @staticmethod 32 def from_preset(instance_name: str) -> "MaxCut": 33 match instance_name: 34 case 'default': 35 node_list = list(range(6)) 36 edge_list = [(0, 1), (0, 2), (0, 5), (1, 3), (1, 4), 37 (2, 4), (2, 5), (3, 4), (3, 5)] 38 graph = nx.Graph() 39 graph.add_nodes_from(node_list) 40 graph.add_edges_from(edge_list) 41 return MaxCut(graph, instance_name=instance_name)
42 43 def _get_path(self) -> str: 44 return f'{self.name}@{self.instance_name}' 45
[docs] 46 def visualize(self, bitstring: Optional[str] = None): 47 pos = nx.spring_layout(self.instance) 48 plt.figure(figsize=(8, 6)) 49 if bitstring is None: 50 cmap = 'skyblue' 51 else: 52 cmap = ['crimson' if bit == '1' else 'skyblue' for bit in bitstring] 53 nx.draw(self.instance, pos, with_labels=True, node_color=cmap, 54 node_size=500, edge_color='gray', font_size=10, font_weight='bold') 55 plt.title("Max-Cut Problem Instance Visualization") 56 plt.show()
57
[docs] 58 @staticmethod 59 def generate_maxcut_instance(num_vertices: int, edge_probability: float) -> "MaxCut": 60 graph = nx.gnp_random_graph(num_vertices, edge_probability) 61 return MaxCut(graph, instance_name='Generated')