Skip to content

Commit

Permalink
Fix rest of lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
ElePT committed Nov 27, 2023
2 parents 7e2d969 + 5fc057a commit 0a6c8cd
Show file tree
Hide file tree
Showing 10 changed files with 100 additions and 69 deletions.
14 changes: 4 additions & 10 deletions how_tos/how_to_build_qaoa_swap_circuit.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,7 @@
"from qiskit.circuit.library import QAOAAnsatz\n",
"\n",
"num_qubits = cost_operator.num_qubits\n",
"dummy_initial_state = QuantumCircuit(\n",
" num_qubits\n",
") # the real initial state is defined later\n",
"dummy_initial_state = QuantumCircuit(num_qubits) # the real initial state is defined later\n",
"dummy_mixer_operator = QuantumCircuit(num_qubits) # the real mixer is defined later\n",
"\n",
"cost_layer = QAOAAnsatz(\n",
Expand Down Expand Up @@ -457,9 +455,7 @@
"# iterate over number of qaoa layers\n",
"for layer in range(qaoa_layers):\n",
" # assign parameters corresponding to layer\n",
" cost = swapped_cost_layer.assign_parameters(\n",
" {swapped_cost_layer.parameters[0]: gammas[layer]}\n",
" )\n",
" cost = swapped_cost_layer.assign_parameters({swapped_cost_layer.parameters[0]: gammas[layer]})\n",
" mixer = mixer_layer.assign_parameters({mixer_layer.parameters[0]: betas[layer]})\n",
"\n",
" if layer % 2 == 0:\n",
Expand Down Expand Up @@ -547,10 +543,8 @@
"basis_gates = [\"rz\", \"sx\", \"x\", \"cx\"]\n",
"#\n",
"# Now transpile to sx, rz, x, cx basis\n",
"t_final_circuit = transpile(\n",
" final_circuit, basis_gates=basis_gates, optimization_level=2\n",
")\n",
"t_final_circuit.draw(\"mpl\")\n"
"t_final_circuit = transpile(final_circuit, basis_gates=basis_gates, optimization_level=2)\n",
"t_final_circuit.draw(\"mpl\")"
],
"metadata": {
"collapsed": false,
Expand Down
16 changes: 7 additions & 9 deletions how_tos/how_to_optimize_qaoa_for_hw.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -273,13 +273,9 @@
"\n",
"theta = [1, 1, 0, 1]\n",
"# we define the edge_coloring map so that RZZGates are positioned next to SWAP gates to exploit CX cancellations\n",
"edge_coloring = {\n",
" (idx, idx + 1): (idx + 1) % 2 for idx in range(qaoa_hamiltonian.num_qubits)\n",
"}\n",
"edge_coloring = {(idx, idx + 1): (idx + 1) % 2 for idx in range(qaoa_hamiltonian.num_qubits)}\n",
"\n",
"qaoa_circ = create_qaoa_swap_circuit(\n",
" qaoa_hamiltonian, swap_strategy, edge_coloring, qaoa_layers=2\n",
")\n",
"qaoa_circ = create_qaoa_swap_circuit(qaoa_hamiltonian, swap_strategy, edge_coloring, qaoa_layers=2)\n",
"\n",
"qaoa_circ.draw(\"mpl\")"
]
Expand Down Expand Up @@ -623,6 +619,7 @@
" result = np.binary_repr(n, width=L)\n",
" return [int(digit) for digit in result]\n",
"\n",
"\n",
"def sample_most_likely(state_vector):\n",
" \"\"\"Compute the most likely binary string from state vector.\n",
" Args:\n",
Expand Down Expand Up @@ -696,11 +693,12 @@
"\n",
"# auxiliary function to plot graphs\n",
"def plot_result(G, x):\n",
" colors = ['r' if i == 0 else 'b' for i in x]\n",
" colors = [\"r\" if i == 0 else \"b\" for i in x]\n",
" pos, default_axes = nx.spring_layout(G), plt.axes(frameon=True)\n",
" nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)\n",
" nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.8, pos=pos)\n",
"\n",
"\n",
"plot_result(graph, best_result)\n"
"plot_result(graph, best_result)"
]
}
],
Expand Down
13 changes: 9 additions & 4 deletions how_tos/how_to_run_custom_cost_functions.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"source": [
"from qopt_best_practices.cost_function import evaluate_sparse_pauli\n",
"\n",
"\n",
"def cost_func_cvar_sampler(params, ansatz, hamiltonian, sampler, aggregation):\n",
"\n",
" job = sampler.run(ansatz, params)\n",
Expand Down Expand Up @@ -105,6 +106,7 @@
"# BASIC STATEVECTOR SIMULATOR BACKEND --> primitives in qiskit.primtives\n",
"\n",
"from qiskit.primitives import Sampler\n",
"\n",
"sampler = Sampler()"
],
"metadata": {
Expand Down Expand Up @@ -154,7 +156,7 @@
"from qiskit.circuit.library import QAOAAnsatz\n",
"\n",
"ansatz = QAOAAnsatz(hamiltonian, reps=2)\n",
"ansatz.draw('mpl')\n",
"ansatz.draw(\"mpl\")\n",
"ansatz.measure_all()"
],
"metadata": {
Expand Down Expand Up @@ -292,6 +294,7 @@
" result = np.binary_repr(n, width=L)\n",
" return [int(digit) for digit in result]\n",
"\n",
"\n",
"def sample_most_likely(state_vector):\n",
" values = list(state_vector.values())\n",
" n = int(np.log2(len(values)))\n",
Expand All @@ -300,6 +303,7 @@
" x.reverse()\n",
" return np.asarray(x)\n",
"\n",
"\n",
"qc = ansatz.assign_parameters(result.x)\n",
"samp_dist = sampler.run(qc, shots=int(1e4)).result().quasi_dists[0]\n",
"\n",
Expand All @@ -312,11 +316,12 @@
"\n",
"# auxiliary function to plot graphs\n",
"def plot_result(G, x):\n",
" colors = ['r' if i == 0 else 'b' for i in x]\n",
" colors = [\"r\" if i == 0 else \"b\" for i in x]\n",
" pos, default_axes = nx.spring_layout(G), plt.axes(frameon=True)\n",
" nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)\n",
" nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.8, pos=pos)\n",
"\n",
"\n",
"plot_result(build_max_cut_graph(data[\"paulis\"]), best_result)\n"
"plot_result(build_max_cut_graph(data[\"paulis\"]), best_result)"
],
"metadata": {
"collapsed": false,
Expand Down
11 changes: 6 additions & 5 deletions how_tos/how_to_select_qubits.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,8 @@
"\n",
"from qiskit.transpiler import CouplingMap\n",
"\n",
"def find_lines(\n",
" length: int, backend, coupling_map: CouplingMap | None = None\n",
") -> list[int]:\n",
"\n",
"def find_lines(length: int, backend, coupling_map: CouplingMap | None = None) -> list[int]:\n",
" \"\"\"Finds all possible lines of length `length` for a specific backend topology.\n",
"\n",
" This method can take quite some time to run on large devices since there\n",
Expand Down Expand Up @@ -209,7 +208,7 @@
" for idx in range(len(path) - 1):\n",
" fidelity *= two_qubit_fidelity[(path[idx], path[idx + 1])]\n",
"\n",
" return fidelity\n"
" return fidelity"
],
"metadata": {
"collapsed": false,
Expand All @@ -235,7 +234,9 @@
"source": [
"num_qubits = 10\n",
"path_finder = BackendEvaluator(backend)\n",
"path, fidelity, num_subsets = path_finder.evaluate(num_qubits, subset_finder=find_lines, metric_eval=evaluate_fidelity)\n",
"path, fidelity, num_subsets = path_finder.evaluate(\n",
" num_qubits, subset_finder=find_lines, metric_eval=evaluate_fidelity\n",
")\n",
"\n",
"print(\"Best path: \", path)\n",
"print(\"Best path fidelity\", fidelity)\n",
Expand Down
45 changes: 44 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,50 @@ variable-rgx = "[a-z_][a-z0-9_]{1,30}$"
max-line-length = 105 # default 100

[tool.pylint."messages control"]
disable = []
disable = [
# intentionally disabled:
"spelling", # too noisy
"fixme", # disabled as TODOs would show up as warnings
"protected-access", # disabled as we don't follow the public vs private convention strictly
"duplicate-code", # disabled as it is too verbose
"redundant-returns-doc", # for @abstractmethod, it cannot interpret "pass"
"too-many-lines", "too-many-branches", "too-many-locals", "too-many-nested-blocks", "too-many-statements",
"too-many-instance-attributes", "too-many-arguments", "too-many-public-methods", "too-few-public-methods", "too-many-ancestors",
"unnecessary-pass", # allow for methods with just "pass", for clarity
"no-else-return", # relax "elif" after a clause with a return
"docstring-first-line-empty", # relax docstring style
"import-outside-toplevel", "import-error", # overzealous with our optionals/dynamic packages
# TODO(#9614): these were added in modern Pylint. Decide if we want to enable them. If so,
# remove from here and fix the issues. Else, move it above this section and add a comment
# with the rationale
"arguments-renamed",
"broad-exception-raised",
"consider-iterating-dictionary",
"consider-using-dict-items",
"consider-using-enumerate",
"consider-using-f-string",
"modified-iterating-list",
"nested-min-max",
"no-member",
"no-value-for-parameter",
"non-ascii-name",
"not-context-manager",
"superfluous-parens",
"unknown-option-value",
"unexpected-keyword-arg",
"unnecessary-dict-index-lookup",
"unnecessary-direct-lambda-call",
"unnecessary-dunder-call",
"unnecessary-ellipsis",
"unnecessary-lambda-assignment",
"unnecessary-list-index-lookup",
"unspecified-encoding",
"unsupported-assignment-operation",
"use-dict-literal",
"use-list-literal",
"use-implicit-booleaness-not-comparison",
"use-maxsplit-arg",
]

enable = [
"use-symbolic-message-instead"
Expand Down
4 changes: 2 additions & 2 deletions qopt_best_practices/swap_strategies/build_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def apply_swap_strategy(
return pm_pre.run(circuit)


def apply_qaoa_layers( # pylint: disable=too-many-arguments,too-many-locals
def apply_qaoa_layers( # pylint: disable=too-many-arguments,too-many-locals
cost_layer: QuantumCircuit,
meas_map: dict,
num_layers: int,
Expand Down Expand Up @@ -116,7 +116,7 @@ def apply_qaoa_layers( # pylint: disable=too-many-arguments,too-many-locals
return new_circuit


def create_qaoa_swap_circuit( # pylint: disable=too-many-arguments
def create_qaoa_swap_circuit( # pylint: disable=too-many-arguments
cost_operator: SparsePauliOp,
swap_strategy: SwapStrategy,
edge_coloring: dict = None,
Expand Down
8 changes: 2 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
with open("requirements.txt") as f:
REQUIREMENTS = f.read().splitlines()

VERSION_PATH = os.path.join(
os.path.dirname(__file__), "qopt_best_practices", "VERSION.txt"
)
VERSION_PATH = os.path.join(os.path.dirname(__file__), "qopt_best_practices", "VERSION.txt")
with open(VERSION_PATH, "r") as version_file:
VERSION = version_file.read().strip()

Expand Down Expand Up @@ -37,9 +35,7 @@
"Topic :: Scientific/Engineering",
],
keywords="qiskit quantum optimization",
packages=setuptools.find_packages(
include=["qopt_best_practices", "qopt_best_practices.*"]
),
packages=setuptools.find_packages(include=["qopt_best_practices", "qopt_best_practices.*"]),
install_requires=REQUIREMENTS,
include_package_data=True,
python_requires=">=3.7",
Expand Down
25 changes: 10 additions & 15 deletions test/test_qubit_selection.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,29 @@
"""Tests for Qubit Selection Utils"""

from unittest import TestCase
import json
from qiskit.providers.fake_provider import FakeWashington
import os
from unittest import TestCase

from qopt_best_practices.utils import build_graph, build_paulis
from qopt_best_practices.swap_strategies import *
from qiskit.providers.fake_provider import FakeWashington

from qopt_best_practices.qubit_selection import (
BackendEvaluator,
find_lines,
evaluate_fidelity,
)
from qopt_best_practices.utils import build_max_cut_graph
from qopt_best_practices.qubit_selection import BackendEvaluator, find_lines


class TestQubitSelection(TestCase):

"""Unit test for QAOA workflow."""

def setUp(self):
super().setUp()

# load data
graph_file = "data/graph_2layers_0seed.json"
graph_file = os.path.join(os.path.dirname(__file__), "data/graph_2layers_0seed.json")

with open(graph_file, "r") as f:
data = json.load(f)
with open(graph_file, "r") as file:
data = json.load(file)

self.mapped_paulis = [tuple(pauli) for pauli in data["paulis"]]
self.mapped_graph = build_graph(self.mapped_paulis)
self.mapped_graph = build_max_cut_graph(self.mapped_paulis)
self.backend = FakeWashington()

def test_find_lines(self):
Expand All @@ -45,7 +40,7 @@ def test_qubit_selection(self):

path_finder = BackendEvaluator(self.backend)

path, fidelity, num_subsets = path_finder.evaluate(len(self.mapped_graph))
path, _, _ = path_finder.evaluate(len(self.mapped_graph))

expected_path = [30, 31, 32, 36, 51, 50, 49, 48, 47, 35]

Expand Down
26 changes: 13 additions & 13 deletions test/test_sat_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

from unittest import TestCase
import json

import os
import networkx as nx

from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import SwapStrategy

from qopt_best_practices.utils import build_graph, build_paulis
from qopt_best_practices.sat_mapping import *
from qopt_best_practices.utils import build_max_cut_graph, build_max_cut_paulis
from qopt_best_practices.sat_mapping import SATMapper


class TestSwapStrategies(TestCase):
Expand All @@ -18,31 +18,30 @@ def setUp(self):
super().setUp()

# load data
graph_file = "data/graph_2layers_0seed.json"
graph_file = os.path.join(os.path.dirname(__file__), "data/graph_2layers_0seed.json")

with open(graph_file, "r") as f:
data = json.load(f)
with open(graph_file, "r") as file:
data = json.load(file)

self.original_graph = nx.from_edgelist(data["Original graph"])
self.original_paulis = build_paulis(self.original_graph)
self.original_paulis = build_max_cut_paulis(self.original_graph)

self.mapped_paulis = [tuple(pauli) for pauli in data["paulis"]]
self.mapped_graph = build_graph(self.mapped_paulis)
self.mapped_graph = build_max_cut_graph(self.mapped_paulis)

self.sat_mapping = {int(key): value for key, value in data["SAT mapping"].items()}
self.min_k = data["min swap layers"]
self.swap_strategy = SwapStrategy.from_line(
[i for i in range(len(self.original_graph.nodes))]
)
self.swap_strategy = SwapStrategy.from_line(list(range(len(self.original_graph.nodes))))
self.basic_graphs = [nx.path_graph(5), nx.cycle_graph(7)]

def test_find_initial_mappings(self):
"""Test find_initial_mappings"""

mapper = SATMapper()

results = mapper.find_initial_mappings(self.original_graph, self.swap_strategy)
min_k = min((k for k, v in results.items() if v.satisfiable))
edge_map = dict(results[min_k].mapping)
# edge_map = dict(results[min_k].mapping)

# edge maps are not equal, but same min_k
self.assertEqual(min_k, self.min_k)
Expand All @@ -51,10 +50,11 @@ def test_find_initial_mappings(self):
# self.assertEqual(edge_map, self.sat_mapping)

def test_remap_graph_with_sat(self):
"""Test remap_graph_with_sat"""

mapper = SATMapper()

remapped_g, sat_map, min_sat_layers = mapper.remap_graph_with_sat(
remapped_g, _, _ = mapper.remap_graph_with_sat(
graph=self.original_graph, swap_strategy=self.swap_strategy
)

Expand Down
Loading

0 comments on commit 0a6c8cd

Please sign in to comment.