From fb14e64405e5f2b2bfe2c912dac3d7dfc55599b2 Mon Sep 17 00:00:00 2001 From: Frank Harkins Date: Tue, 29 Oct 2024 11:22:01 +0000 Subject: [PATCH 1/3] Add ruff formatting --- docs/ruff.toml | 1 + tox.ini | 2 ++ 2 files changed, 3 insertions(+) create mode 100644 docs/ruff.toml diff --git a/docs/ruff.toml b/docs/ruff.toml new file mode 100644 index 00000000000..50ec7749e1f --- /dev/null +++ b/docs/ruff.toml @@ -0,0 +1 @@ +line-length=78 diff --git a/tox.ini b/tox.ini index 7a1bb294010..2adfbf60dc5 100644 --- a/tox.ini +++ b/tox.ini @@ -17,8 +17,10 @@ deps = commands = lint: ruff check {posargs:docs} + lint: ruff format --check {posargs:docs} lint: squeaky --check --no-advice {posargs:docs} fix: squeaky {posargs:docs} + fix: ruff format {posargs:docs} fix: ruff check --fix {posargs:docs} [testenv:nb-tester] From 31c365243882186ad002d256a6659f4e79931f20 Mon Sep 17 00:00:00 2001 From: Frank Harkins Date: Tue, 29 Oct 2024 11:28:32 +0000 Subject: [PATCH 2/3] Format with ruff --- docs/guides/algorithmiq-tem.ipynb | 4 +- docs/guides/build-noise-models.ipynb | 74 ++++++----- docs/guides/circuit-library.ipynb | 41 +++--- docs/guides/common-parameters.ipynb | 4 +- docs/guides/construct-circuits.ipynb | 14 +-- docs/guides/create-transpiler-plugin.ipynb | 23 +++- docs/guides/custom-backend.ipynb | 117 +++++++++++------- docs/guides/custom-transpiler-pass.ipynb | 27 ++-- .../defaults-and-configuration-options.ipynb | 10 +- .../dynamical-decoupling-pass-manager.ipynb | 8 +- docs/guides/functions.ipynb | 10 +- docs/guides/get-qpu-information.ipynb | 3 +- docs/guides/hello-world.ipynb | 38 +++--- docs/guides/ibm-circuit-function.ipynb | 41 +++--- docs/guides/noise-learning.ipynb | 34 +++-- docs/guides/plot-quantum-states.ipynb | 9 +- docs/guides/primitive-input-output.ipynb | 64 +++++++--- docs/guides/pulse.ipynb | 65 ++++++---- .../q-ctrl-performance-management.ipynb | 23 ++-- docs/guides/qedma-qesem.ipynb | 62 ++++------ docs/guides/qunasys-quri-chemistry.ipynb | 116 ++++++++--------- docs/guides/represent-quantum-computers.ipynb | 6 +- docs/guides/save-circuits.ipynb | 11 +- docs/guides/save-jobs.ipynb | 11 +- docs/guides/serverless-first-program.ipynb | 4 +- .../serverless-run-first-workload.ipynb | 6 +- docs/guides/set-optimization.ipynb | 4 +- .../guides/simulate-stabilizer-circuits.ipynb | 12 +- docs/guides/simulate-with-qiskit-aer.ipynb | 8 +- docs/guides/specify-observables-pauli.ipynb | 16 ++- .../guides/transpile-with-pass-managers.ipynb | 8 +- docs/guides/transpiler-plugins.ipynb | 12 +- docs/guides/transpiler-stages.ipynb | 8 +- docs/guides/visualize-results.ipynb | 8 +- 34 files changed, 538 insertions(+), 363 deletions(-) diff --git a/docs/guides/algorithmiq-tem.ipynb b/docs/guides/algorithmiq-tem.ipynb index 05ec8cadb4e..11f7773fe61 100644 --- a/docs/guides/algorithmiq-tem.ipynb +++ b/docs/guides/algorithmiq-tem.ipynb @@ -177,7 +177,9 @@ "pub = (qc, [observable])\n", "options = {\"default_precision\": 0.02}\n", "\n", - "job = tem.run(pubs=[pub], instance=instance, backend_name=backend_name, options=options)" + "job = tem.run(\n", + " pubs=[pub], instance=instance, backend_name=backend_name, options=options\n", + ")" ] }, { diff --git a/docs/guides/build-noise-models.ipynb b/docs/guides/build-noise-models.ipynb index 3b22676257a..5389c8dc247 100644 --- a/docs/guides/build-noise-models.ipynb +++ b/docs/guides/build-noise-models.ipynb @@ -176,8 +176,8 @@ "source": [ "# Construct a 1-qubit bit-flip and phase-flip errors\n", "p_error = 0.05\n", - "bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)])\n", - "phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)])\n", + "bit_flip = pauli_error([(\"X\", p_error), (\"I\", 1 - p_error)])\n", + "phase_flip = pauli_error([(\"Z\", p_error), (\"I\", 1 - p_error)])\n", "print(bit_flip)\n", "print(phase_flip)" ] @@ -492,7 +492,7 @@ "\n", "# Add depolarizing error to all single qubit u1, u2, u3 gates\n", "error = depolarizing_error(0.05, 1)\n", - "noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])\n", + "noise_model.add_all_qubit_quantum_error(error, [\"u1\", \"u2\", \"u3\"])\n", "\n", "# Print noise model info\n", "print(noise_model)" @@ -540,7 +540,7 @@ "\n", "# Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only\n", "error = depolarizing_error(0.05, 1)\n", - "noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0])\n", + "noise_model.add_quantum_error(error, [\"u1\", \"u2\", \"u3\"], [0])\n", "\n", "# Print noise model info\n", "print(noise_model)" @@ -718,9 +718,9 @@ "p_gate1 = 0.05\n", "\n", "# QuantumError objects\n", - "error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)])\n", - "error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])\n", - "error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)])\n", + "error_reset = pauli_error([(\"X\", p_reset), (\"I\", 1 - p_reset)])\n", + "error_meas = pauli_error([(\"X\", p_meas), (\"I\", 1 - p_meas)])\n", + "error_gate1 = pauli_error([(\"X\", p_gate1), (\"I\", 1 - p_gate1)])\n", "error_gate2 = error_gate1.tensor(error_gate1)\n", "\n", "# Add errors to noise model\n", @@ -775,7 +775,9 @@ "sim_noise = AerSimulator(noise_model=noise_bit_flip)\n", "\n", "# Transpile circuit for noisy basis gates\n", - "passmanager = generate_preset_pass_manager(optimization_level=3, backend=sim_noise)\n", + "passmanager = generate_preset_pass_manager(\n", + " optimization_level=3, backend=sim_noise\n", + ")\n", "circ_tnoise = passmanager.run(circ)\n", "\n", "# Run and get counts\n", @@ -825,35 +827,49 @@ ], "source": [ "# T1 and T2 values for qubits 0-3\n", - "T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec\n", - "T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec\n", + "T1s = np.random.normal(\n", + " 50e3, 10e3, 4\n", + ") # Sampled from normal distribution mean 50 microsec\n", + "T2s = np.random.normal(\n", + " 70e3, 10e3, 4\n", + ") # Sampled from normal distribution mean 50 microsec\n", "\n", "# Truncate random T2s <= T1s\n", "T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])\n", "\n", "# Instruction times (in nanoseconds)\n", - "time_u1 = 0 # virtual gate\n", + "time_u1 = 0 # virtual gate\n", "time_u2 = 50 # (single X90 pulse)\n", - "time_u3 = 100 # (two X90 pulses)\n", + "time_u3 = 100 # (two X90 pulses)\n", "time_cx = 300\n", "time_reset = 1000 # 1 microsecond\n", - "time_measure = 1000 # 1 microsecond\n", + "time_measure = 1000 # 1 microsecond\n", "\n", "# QuantumError objects\n", - "errors_reset = [thermal_relaxation_error(t1, t2, time_reset)\n", - " for t1, t2 in zip(T1s, T2s)]\n", - "errors_measure = [thermal_relaxation_error(t1, t2, time_measure)\n", - " for t1, t2 in zip(T1s, T2s)]\n", - "errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)\n", - " for t1, t2 in zip(T1s, T2s)]\n", - "errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)\n", - " for t1, t2 in zip(T1s, T2s)]\n", - "errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)\n", - " for t1, t2 in zip(T1s, T2s)]\n", - "errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(\n", - " thermal_relaxation_error(t1b, t2b, time_cx))\n", - " for t1a, t2a in zip(T1s, T2s)]\n", - " for t1b, t2b in zip(T1s, T2s)]\n", + "errors_reset = [\n", + " thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)\n", + "]\n", + "errors_measure = [\n", + " thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)\n", + "]\n", + "errors_u1 = [\n", + " thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)\n", + "]\n", + "errors_u2 = [\n", + " thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)\n", + "]\n", + "errors_u3 = [\n", + " thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)\n", + "]\n", + "errors_cx = [\n", + " [\n", + " thermal_relaxation_error(t1a, t2a, time_cx).expand(\n", + " thermal_relaxation_error(t1b, t2b, time_cx)\n", + " )\n", + " for t1a, t2a in zip(T1s, T2s)\n", + " ]\n", + " for t1b, t2b in zip(T1s, T2s)\n", + "]\n", "\n", "# Add errors to noise model\n", "noise_thermal = NoiseModel()\n", @@ -908,7 +924,9 @@ "sim_thermal = AerSimulator(noise_model=noise_thermal)\n", "\n", "# Transpile circuit for noisy basis gates\n", - "passmanager = generate_preset_pass_manager(optimization_level=3, backend=sim_thermal)\n", + "passmanager = generate_preset_pass_manager(\n", + " optimization_level=3, backend=sim_thermal\n", + ")\n", "circ_tthermal = passmanager.run(circ)\n", "\n", "# Run and get counts\n", diff --git a/docs/guides/circuit-library.ipynb b/docs/guides/circuit-library.ipynb index 4e184134ece..3c2078f6dc3 100644 --- a/docs/guides/circuit-library.ipynb +++ b/docs/guides/circuit-library.ipynb @@ -52,13 +52,14 @@ "source": [ "from qiskit import QuantumCircuit\n", "from qiskit.circuit.library import HGate, MCXGate\n", + "\n", "mcx_gate = MCXGate(3)\n", "hadamard_gate = HGate()\n", "\n", "qc = QuantumCircuit(4)\n", "qc.append(hadamard_gate, [0])\n", - "qc.append(mcx_gate, [0,1,2,3])\n", - "qc.draw('mpl')" + "qc.append(mcx_gate, [0, 1, 2, 3])\n", + "qc.draw(\"mpl\")" ] }, { @@ -112,8 +113,9 @@ ], "source": [ "from qiskit.circuit.library import TwoLocal\n", - "two_local = TwoLocal(3, 'rx', 'cz')\n", - "two_local.decompose().draw('mpl')" + "\n", + "two_local = TwoLocal(3, \"rx\", \"cz\")\n", + "two_local.decompose().draw(\"mpl\")" ] }, { @@ -172,8 +174,10 @@ } ], "source": [ - "bound_circuit = two_local.assign_parameters({ p: 0 for p in two_local.parameters})\n", - "bound_circuit.decompose().draw('mpl')" + "bound_circuit = two_local.assign_parameters(\n", + " {p: 0 for p in two_local.parameters}\n", + ")\n", + "bound_circuit.decompose().draw(\"mpl\")" ] }, { @@ -224,7 +228,7 @@ "feature_map = ZZFeatureMap(feature_dimension=len(features))\n", "\n", "encoded = feature_map.assign_parameters(features)\n", - "encoded.draw('mpl')" + "encoded.draw(\"mpl\")" ] }, { @@ -279,7 +283,7 @@ "# Evolve state by appending the evolution gate\n", "state.compose(evolution, inplace=True)\n", "\n", - "state.draw('mpl')" + "state.draw(\"mpl\")" ] }, { @@ -324,7 +328,8 @@ ], "source": [ "from qiskit.circuit.library import QuantumVolume\n", - "QuantumVolume(4).decompose().draw('mpl')" + "\n", + "QuantumVolume(4).decompose().draw(\"mpl\")" ] }, { @@ -375,25 +380,29 @@ "adder = CDKMRippleCarryAdder(3) # Adder of 3-bit numbers\n", "\n", "# Create the number A=2\n", - "reg_a = QuantumRegister(3, 'a')\n", + "reg_a = QuantumRegister(3, \"a\")\n", "number_a = QuantumCircuit(reg_a)\n", - "number_a.initialize(2) # Number 2; |010>\n", + "number_a.initialize(2) # Number 2; |010>\n", "\n", "# Create the number B=3\n", - "reg_b = QuantumRegister(3, 'b')\n", + "reg_b = QuantumRegister(3, \"b\")\n", "number_b = QuantumCircuit(reg_b)\n", "number_b.initialize(3) # Number 3; |011>\n", "\n", "# Create a circuit to hold everything, including a classical register for\n", - "# the result\n", + "# the result\n", "reg_result = ClassicalRegister(3)\n", "circuit = QuantumCircuit(*adder.qregs, reg_result)\n", "\n", "# Compose number initializers with the adder. Adder stores the result to\n", "# register B, so we'll measure those qubits.\n", - "circuit = circuit.compose(number_a, qubits=reg_a).compose(number_b, qubits=reg_b).compose(adder)\n", + "circuit = (\n", + " circuit.compose(number_a, qubits=reg_a)\n", + " .compose(number_b, qubits=reg_b)\n", + " .compose(adder)\n", + ")\n", "circuit.measure(reg_b, reg_result)\n", - "circuit.draw('mpl')" + "circuit.draw(\"mpl\")" ] }, { @@ -424,7 +433,7 @@ "\n", "result = StatevectorSampler().run([circuit]).result()\n", "\n", - "print(f'Count data:\\n {result[0].data.c0.get_int_counts()}')" + "print(f\"Count data:\\n {result[0].data.c0.get_int_counts()}\")" ] }, { diff --git a/docs/guides/common-parameters.ipynb b/docs/guides/common-parameters.ipynb index 3d54c057604..4e934df7791 100644 --- a/docs/guides/common-parameters.ipynb +++ b/docs/guides/common-parameters.ipynb @@ -48,7 +48,9 @@ "qc = QuantumCircuit(qubits)\n", "qc.append(rand_U, qubits)\n", "pass_manager = generate_preset_pass_manager(\n", - " optimization_level=1, approximation_degree=0.85, basis_gates=[\"sx\", \"rz\", \"cx\"]\n", + " optimization_level=1,\n", + " approximation_degree=0.85,\n", + " basis_gates=[\"sx\", \"rz\", \"cx\"],\n", ")\n", "approx_qc = pass_manager.run(qc)\n", "print(approx_qc.count_ops()[\"cx\"])" diff --git a/docs/guides/construct-circuits.ipynb b/docs/guides/construct-circuits.ipynb index 2cc8339e5f6..4fef40ca2e3 100644 --- a/docs/guides/construct-circuits.ipynb +++ b/docs/guides/construct-circuits.ipynb @@ -195,7 +195,7 @@ "qc = QuantumCircuit(1)\n", "qc.append(\n", " HGate(), # New HGate instruction\n", - " [0] # Apply to qubit 0\n", + " [0], # Apply to qubit 0\n", ")\n", "qc.draw(\"mpl\")" ] @@ -240,7 +240,7 @@ "qc_b.y(0)\n", "qc_b.z(1)\n", "\n", - "# compose qubits (0, 1) of qc_a to qubits (1, 3) of qc_b respectively\n", + "# compose qubits (0, 1) of qc_a to qubits (1, 3) of qc_b respectively\n", "combined = qc_a.compose(qc_b, qubits=[1, 3])\n", "combined.draw(\"mpl\")" ] @@ -385,10 +385,12 @@ "\n", "angle = Parameter(\"angle\") # undefined number\n", "\n", - "# Create and optimize circuit once\n", + "# Create and optimize circuit once\n", "qc = QuantumCircuit(1)\n", "qc.rx(angle, 0)\n", - "qc = generate_preset_pass_manager(optimization_level=3, basis_gates=['u', 'cx']).run(qc)\n", + "qc = generate_preset_pass_manager(\n", + " optimization_level=3, basis_gates=[\"u\", \"cx\"]\n", + ").run(qc)\n", "\n", "qc.draw(\"mpl\")" ] @@ -424,9 +426,7 @@ "source": [ "circuits = []\n", "for value in range(100):\n", - " circuits.append(\n", - " qc.assign_parameters({ angle: value })\n", - " )\n", + " circuits.append(qc.assign_parameters({angle: value}))\n", "\n", "circuits[0].draw(\"mpl\")" ] diff --git a/docs/guides/create-transpiler-plugin.ipynb b/docs/guides/create-transpiler-plugin.ipynb index 99dedaece06..8d2fc8bbc17 100644 --- a/docs/guides/create-transpiler-plugin.ipynb +++ b/docs/guides/create-transpiler-plugin.ipynb @@ -65,7 +65,9 @@ "from qiskit.transpiler.passes import VF2Layout\n", "from qiskit.transpiler.passmanager_config import PassManagerConfig\n", "from qiskit.transpiler.preset_passmanagers import common\n", - "from qiskit.transpiler.preset_passmanagers.plugin import PassManagerStagePlugin\n", + "from qiskit.transpiler.preset_passmanagers.plugin import (\n", + " PassManagerStagePlugin,\n", + ")\n", "\n", "\n", "class MyLayoutPlugin(PassManagerStagePlugin):\n", @@ -84,7 +86,9 @@ " )\n", " ]\n", " )\n", - " layout_pm += common.generate_embed_passmanager(pass_manager_config.coupling_map)\n", + " layout_pm += common.generate_embed_passmanager(\n", + " pass_manager_config.coupling_map\n", + " )\n", " return layout_pm" ] }, @@ -178,7 +182,9 @@ "metadata": {}, "outputs": [], "source": [ - "from qiskit.transpiler.preset_passmanagers.plugin import PassManagerStagePluginManager\n", + "from qiskit.transpiler.preset_passmanagers.plugin import (\n", + " PassManagerStagePluginManager,\n", + ")\n", "\n", "# Initialize the plugin manager\n", "plugin_manager = PassManagerStagePluginManager()\n", @@ -436,7 +442,12 @@ "\n", "class MyCliffordSynthesisPlugin(HighLevelSynthesisPlugin):\n", " def run(\n", - " self, high_level_object, coupling_map=None, target=None, qubits=None, **options\n", + " self,\n", + " high_level_object,\n", + " coupling_map=None,\n", + " target=None,\n", + " qubits=None,\n", + " **options,\n", " ) -> QuantumCircuit:\n", " if high_level_object.num_qubits <= 3:\n", " return synth_clifford_bm(high_level_object)\n", @@ -513,7 +524,9 @@ } ], "source": [ - "from qiskit.transpiler.passes.synthesis import high_level_synthesis_plugin_names\n", + "from qiskit.transpiler.passes.synthesis import (\n", + " high_level_synthesis_plugin_names,\n", + ")\n", "\n", "high_level_synthesis_plugin_names(\"clifford\")" ] diff --git a/docs/guides/custom-backend.ipynb b/docs/guides/custom-backend.ipynb index 58e4f05271f..9e9751865db 100644 --- a/docs/guides/custom-backend.ipynb +++ b/docs/guides/custom-backend.ipynb @@ -82,7 +82,6 @@ "from qiskit.visualization import plot_gate_map\n", "\n", "\n", - "\n", "class FakeLOCCBackend(BackendV2):\n", " \"\"\"Fake multi chip backend.\"\"\"\n", "\n", @@ -98,11 +97,15 @@ " number_of_chips (int): The number of chips to have in the multichip backend\n", " each chip will be a heavy hex graph of ``distance`` code distance.\n", " \"\"\"\n", - " super().__init__(name='Fake LOCC backend')\n", + " super().__init__(name=\"Fake LOCC backend\")\n", " # Create a heavy-hex graph using the rustworkx library, then instantiate a new target\n", - " self._graph = rx.generators.directed_heavy_hex_graph(distance, bidirectional=False)\n", + " self._graph = rx.generators.directed_heavy_hex_graph(\n", + " distance, bidirectional=False\n", + " )\n", " num_qubits = len(self._graph) * number_of_chips\n", - " self._target = Target(\"Fake multi-chip backend\", num_qubits=num_qubits)\n", + " self._target = Target(\n", + " \"Fake multi-chip backend\", num_qubits=num_qubits\n", + " )\n", "\n", " # Generate instruction properties for single qubit gates and a measurement, delay,\n", " # and reset operation to every qubit in the backend.\n", @@ -118,13 +121,16 @@ " qarg = (i,)\n", " rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0)\n", " x_props[qarg] = InstructionProperties(\n", - " error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)\n", + " error=rng.uniform(1e-6, 1e-4),\n", + " duration=rng.uniform(1e-8, 9e-7),\n", " )\n", " sx_props[qarg] = InstructionProperties(\n", - " error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)\n", + " error=rng.uniform(1e-6, 1e-4),\n", + " duration=rng.uniform(1e-8, 9e-7),\n", " )\n", " measure_props[qarg] = InstructionProperties(\n", - " error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7)\n", + " error=rng.uniform(1e-3, 1e-1),\n", + " duration=rng.uniform(1e-8, 9e-7),\n", " )\n", " delay_props[qarg] = None\n", " self._target.add_instruction(XGate(), x_props)\n", @@ -141,7 +147,8 @@ " offset = i * len(self._graph)\n", " edge = (root_edge[0] + offset, root_edge[1] + offset)\n", " cz_props[edge] = InstructionProperties(\n", - " error=rng.uniform(7e-4, 5e-3), duration=rng.uniform(1e-8, 9e-7)\n", + " error=rng.uniform(7e-4, 5e-3),\n", + " duration=rng.uniform(1e-8, 9e-7),\n", " )\n", " self._target.add_instruction(CZGate(), cz_props)\n", "\n", @@ -155,7 +162,7 @@ " count = 0\n", " for edge in edge_list:\n", " if node == edge[0]:\n", - " count+=1\n", + " count += 1\n", " if count == 1:\n", " inter_chip_nodes[node] = count\n", " # Create inter-chip ecr props\n", @@ -163,9 +170,13 @@ " inter_chip_edges = list(inter_chip_nodes.keys())\n", " for i in range(1, number_of_chips):\n", " offset = i * len(self._graph)\n", - " edge = (inter_chip_edges[1] + (len(self._graph) * (i-1)) , inter_chip_edges[0] + offset)\n", + " edge = (\n", + " inter_chip_edges[1] + (len(self._graph) * (i - 1)),\n", + " inter_chip_edges[0] + offset,\n", + " )\n", " cx_props[edge] = InstructionProperties(\n", - " error=rng.uniform(7e-4, 5e-3), duration=rng.uniform(1e-8, 9e-7)\n", + " error=rng.uniform(7e-4, 5e-3),\n", + " duration=rng.uniform(1e-8, 9e-7),\n", " )\n", "\n", " self._target.add_instruction(ECRGate(), cx_props)\n", @@ -182,13 +193,14 @@ " def graph(self):\n", " return self._graph\n", "\n", - "\n", " @classmethod\n", " def _default_options(cls):\n", " return Options(shots=1024)\n", "\n", " def run(self, circuit, **kwargs):\n", - " raise NotImplementedError(\"This backend does not contain a run method\")" + " raise NotImplementedError(\n", + " \"This backend does not contain a run method\"\n", + " )" ] }, { @@ -215,25 +227,27 @@ "coupling_map_backend = target.build_coupling_map()\n", "\n", "\n", - "coordinates = [(3, 1),\n", - " (3, -1),\n", - " (2, -2),\n", - " (1,1),\n", - " (0,0),\n", - " (-1, -1),\n", - " (-2, 2),\n", - " (-3, 1),\n", - " (-3, -1),\n", - " (2, 1),\n", - " (1, -1),\n", - " (-1, 1),\n", - " (-2, -1),\n", - " (3, 0),\n", - " (2, -1),\n", - " (0, 1),\n", - " (0, -1),\n", - " (-2, 1),\n", - " (-3, 0)]\n", + "coordinates = [\n", + " (3, 1),\n", + " (3, -1),\n", + " (2, -2),\n", + " (1, 1),\n", + " (0, 0),\n", + " (-1, -1),\n", + " (-2, 2),\n", + " (-3, 1),\n", + " (-3, -1),\n", + " (2, 1),\n", + " (1, -1),\n", + " (-1, 1),\n", + " (-2, -1),\n", + " (3, 0),\n", + " (2, -1),\n", + " (0, 1),\n", + " (0, -1),\n", + " (-2, 1),\n", + " (-3, 0),\n", + "]\n", "\n", "single_qubit_coordinates = []\n", "total_qubit_coordinates = []\n", @@ -243,12 +257,12 @@ " total_qubit_coordinates.append(coordinate)\n", "\n", "for coordinate in coordinates:\n", - " total_qubit_coordinates.append((-1*coordinate[0]+1, coordinate[1]+4))\n", + " total_qubit_coordinates.append(\n", + " (-1 * coordinate[0] + 1, coordinate[1] + 4)\n", + " )\n", "\n", "for coordinate in coordinates:\n", - " total_qubit_coordinates.append((coordinate[0], coordinate[1]+8))\n", - "\n", - "\n", + " total_qubit_coordinates.append((coordinate[0], coordinate[1] + 8))\n", "\n", "\n", "line_colors = [\"#adaaab\" for edge in coupling_map_backend.get_edges()]\n", @@ -256,7 +270,7 @@ "\n", "# Get tuples for the edges which have an ecr instruction attached\n", "for instruction in target.instructions:\n", - " if instruction[0].name == 'ecr':\n", + " if instruction[0].name == \"ecr\":\n", " ecr_edges.append(instruction[1])\n", "\n", "for i, edge in enumerate(coupling_map_backend.get_edges()):\n", @@ -291,7 +305,12 @@ ], "source": [ "print(backend.name)\n", - "plot_gate_map(backend, plot_directed=True, qubit_coordinates=total_qubit_coordinates, line_color=line_colors)" + "plot_gate_map(\n", + " backend,\n", + " plot_directed=True,\n", + " qubit_coordinates=total_qubit_coordinates,\n", + " line_color=line_colors,\n", + ")" ] }, { @@ -354,7 +373,7 @@ "print(\"Pre-Transpilation: \")\n", "print(f\"CX gates: {op_counts['cx']}\")\n", "print(f\"H gates: {op_counts['h']}\")\n", - "print('\\n', 30*'#', '\\n')\n", + "print(\"\\n\", 30 * \"#\", \"\\n\")\n", "\n", "pm = generate_preset_pass_manager(optimization_level=3, backend=backend)\n", "transpiled_ghz = pm.run(ghz)\n", @@ -396,7 +415,9 @@ "source": [ "from qiskit.visualization import plot_circuit_layout\n", "\n", - "plot_circuit_layout(transpiled_ghz, backend, qubit_coordinates=total_qubit_coordinates)" + "plot_circuit_layout(\n", + " transpiled_ghz, backend, qubit_coordinates=total_qubit_coordinates\n", + ")" ] }, { @@ -421,10 +442,10 @@ "\n", " def __init__(self):\n", " \"\"\"Instantiate a new backend that is inspired by a toric code\"\"\"\n", - " super().__init__(name='Fake LOCC backend')\n", + " super().__init__(name=\"Fake LOCC backend\")\n", " graph = rx.generators.directed_grid_graph(20, 20)\n", " for column in range(20):\n", - " graph.add_edge(column, 19*20 + column, None)\n", + " graph.add_edge(column, 19 * 20 + column, None)\n", " for row in range(20):\n", " graph.add_edge(row * 20, row * 20 + 19, None)\n", " num_qubits = len(graph)\n", @@ -440,13 +461,16 @@ " qarg = (i,)\n", " rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0)\n", " x_props[qarg] = InstructionProperties(\n", - " error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)\n", + " error=rng.uniform(1e-6, 1e-4),\n", + " duration=rng.uniform(1e-8, 9e-7),\n", " )\n", " sx_props[qarg] = InstructionProperties(\n", - " error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)\n", + " error=rng.uniform(1e-6, 1e-4),\n", + " duration=rng.uniform(1e-8, 9e-7),\n", " )\n", " measure_props[qarg] = InstructionProperties(\n", - " error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7)\n", + " error=rng.uniform(1e-3, 1e-1),\n", + " duration=rng.uniform(1e-8, 9e-7),\n", " )\n", " delay_props[qarg] = None\n", " self._target.add_instruction(XGate(), x_props)\n", @@ -458,7 +482,8 @@ " cz_props = {}\n", " for edge in graph.edge_list():\n", " cz_props[edge] = InstructionProperties(\n", - " error=rng.uniform(7e-4, 5e-3), duration=rng.uniform(1e-8, 9e-7)\n", + " error=rng.uniform(7e-4, 5e-3),\n", + " duration=rng.uniform(1e-8, 9e-7),\n", " )\n", " self._target.add_instruction(CZGate(), cz_props)\n", "\n", diff --git a/docs/guides/custom-transpiler-pass.ipynb b/docs/guides/custom-transpiler-pass.ipynb index bebbae319d4..9a44a75b4f1 100644 --- a/docs/guides/custom-transpiler-pass.ipynb +++ b/docs/guides/custom-transpiler-pass.ipynb @@ -138,12 +138,12 @@ "\n", " # iterate through Paulis on left of gate to twirl\n", " for pauli_left in pauli_basis(2):\n", - "\n", " # iterate through Paulis on right of gate to twirl\n", " for pauli_right in pauli_basis(2):\n", - "\n", " # save pairs that produce identical operation as gate to twirl\n", - " if (Operator(pauli_left) @ Operator(twirl_gate)).equiv(Operator(twirl_gate) @ pauli_right):\n", + " if (Operator(pauli_left) @ Operator(twirl_gate)).equiv(\n", + " Operator(twirl_gate) @ pauli_right\n", + " ):\n", " twirl_list.append((pauli_left, pauli_right))\n", "\n", " self.twirl_set[twirl_gate.name] = twirl_list\n", @@ -152,15 +152,18 @@ " self,\n", " dag: DAGCircuit,\n", " ) -> DAGCircuit:\n", - "\n", " # collect all nodes in DAG and proceed if it is to be twirled\n", - " twirling_gate_classes = tuple(gate.base_class for gate in self.gates_to_twirl)\n", + " twirling_gate_classes = tuple(\n", + " gate.base_class for gate in self.gates_to_twirl\n", + " )\n", " for node in dag.op_nodes():\n", " if not isinstance(node.op, twirling_gate_classes):\n", " continue\n", "\n", " # random integer to select Pauli twirl pair\n", - " pauli_index = np.random.randint(0, len(self.twirl_set[node.op.name]))\n", + " pauli_index = np.random.randint(\n", + " 0, len(self.twirl_set[node.op.name])\n", + " )\n", " twirl_pair = self.twirl_set[node.op.name][pauli_index]\n", "\n", " # instantiate mini_dag and attach quantum register\n", @@ -169,9 +172,13 @@ " mini_dag.add_qreg(register)\n", "\n", " # apply left Pauli, gate to twirl, and right Pauli to empty mini-DAG\n", - " mini_dag.apply_operation_back(twirl_pair[0].to_instruction(), [register[0], register[1]])\n", + " mini_dag.apply_operation_back(\n", + " twirl_pair[0].to_instruction(), [register[0], register[1]]\n", + " )\n", " mini_dag.apply_operation_back(node.op, [register[0], register[1]])\n", - " mini_dag.apply_operation_back(twirl_pair[1].to_instruction(), [register[0], register[1]])\n", + " mini_dag.apply_operation_back(\n", + " twirl_pair[1].to_instruction(), [register[0], register[1]]\n", + " )\n", "\n", " # substitute gate to twirl node with twirling mini-DAG\n", " dag.substitute_node_with_dag(node, mini_dag)\n", @@ -215,7 +222,7 @@ "qc.ecr(1, 2)\n", "qc.ecr(1, 0)\n", "qc.cx(2, 1)\n", - "qc.draw('mpl')" + "qc.draw(\"mpl\")" ] }, { @@ -266,7 +273,7 @@ } ], "source": [ - "twirled_qcs[-1].draw('mpl')" + "twirled_qcs[-1].draw(\"mpl\")" ] }, { diff --git a/docs/guides/defaults-and-configuration-options.ipynb b/docs/guides/defaults-and-configuration-options.ipynb index 1b39d492b44..18758eb0544 100644 --- a/docs/guides/defaults-and-configuration-options.ipynb +++ b/docs/guides/defaults-and-configuration-options.ipynb @@ -51,7 +51,7 @@ "qc.measure_all()\n", "\n", "# View the circuit\n", - "qc.draw(output='mpl')" + "qc.draw(output=\"mpl\")" ] }, { @@ -87,11 +87,13 @@ "backend = FakeSherbrooke()\n", "\n", "# Transpile the circuit\n", - "pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)\n", + "pass_manager = generate_preset_pass_manager(\n", + " optimization_level=1, backend=backend\n", + ")\n", "transpiled_circ = pass_manager.run(qc)\n", "\n", "# View the transpiled circuit\n", - "transpiled_circ.draw(output='mpl', idle_wires=False)" + "transpiled_circ.draw(output=\"mpl\", idle_wires=False)" ] }, { @@ -238,7 +240,7 @@ " scheduling_method=None,\n", " approximation_degree=1.0,\n", " seed_transpiler=None,\n", - " unitary_synthesis_method='default',\n", + " unitary_synthesis_method=\"default\",\n", " unitary_synthesis_plugin_config=None,\n", " hls_config=None,\n", " init_method=None,\n", diff --git a/docs/guides/dynamical-decoupling-pass-manager.ipynb b/docs/guides/dynamical-decoupling-pass-manager.ipynb index 61e4d2c6589..a78a0339261 100644 --- a/docs/guides/dynamical-decoupling-pass-manager.ipynb +++ b/docs/guides/dynamical-decoupling-pass-manager.ipynb @@ -142,7 +142,9 @@ "import numpy as np\n", "\n", "rng = np.random.default_rng(1234)\n", - "qc_t.assign_parameters(rng.uniform(-np.pi, np.pi, qc_t.num_parameters), inplace=True)" + "qc_t.assign_parameters(\n", + " rng.uniform(-np.pi, np.pi, qc_t.num_parameters), inplace=True\n", + ")" ] }, { @@ -238,7 +240,9 @@ } ], "source": [ - "from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel\n", + "from qiskit.circuit.equivalence_library import (\n", + " SessionEquivalenceLibrary as sel,\n", + ")\n", "from qiskit.transpiler.passes import BasisTranslator\n", "\n", "qc_dd = BasisTranslator(sel, basis_gates)(qc_dd)\n", diff --git a/docs/guides/functions.ipynb b/docs/guides/functions.ipynb index 5fe0710da62..dedf0fe83b7 100644 --- a/docs/guides/functions.ipynb +++ b/docs/guides/functions.ipynb @@ -49,7 +49,7 @@ "source": [ "from qiskit_ibm_catalog import QiskitFunctionsCatalog\n", "\n", - "catalog = QiskitFunctionsCatalog(token='')" + "catalog = QiskitFunctionsCatalog(token=\"\")" ] }, { @@ -116,7 +116,7 @@ "metadata": {}, "outputs": [], "source": [ - "ibm_cf = catalog.load('ibm/circuit-function')" + "ibm_cf = catalog.load(\"ibm/circuit-function\")" ] }, { @@ -142,11 +142,7 @@ } ], "source": [ - "job = ibm_cf.run(\n", - " instance=...,\n", - " pubs=[],\n", - " backend=\"backend_name\"\n", - ")\n", + "job = ibm_cf.run(instance=..., pubs=[], backend=\"backend_name\")\n", "\n", "job.job_id" ] diff --git a/docs/guides/get-qpu-information.ipynb b/docs/guides/get-qpu-information.ipynb index d4e2748a76b..53d271bb89e 100644 --- a/docs/guides/get-qpu-information.ipynb +++ b/docs/guides/get-qpu-information.ipynb @@ -42,6 +42,7 @@ "source": [ "# Initialize your account\n", "from qiskit_ibm_runtime import QiskitRuntimeService\n", + "\n", "service = QiskitRuntimeService(instance=\"ibm-q/open/main\")\n", "\n", "service.backends()" @@ -255,7 +256,7 @@ } ], "source": [ - "backend.target[\"ecr\"][(1,0)]" + "backend.target[\"ecr\"][(1, 0)]" ] }, { diff --git a/docs/guides/hello-world.ipynb b/docs/guides/hello-world.ipynb index 0ab8156077f..5603b8c68b6 100644 --- a/docs/guides/hello-world.ipynb +++ b/docs/guides/hello-world.ipynb @@ -215,7 +215,7 @@ "pm = generate_preset_pass_manager(backend=backend, optimization_level=1)\n", "isa_circuit = pm.run(qc)\n", "\n", - "isa_circuit.draw('mpl', idle_wires=False)" + "isa_circuit.draw(\"mpl\", idle_wires=False)" ] }, { @@ -387,9 +387,9 @@ "errors = pub_result.data.stds\n", "\n", "# plotting graph\n", - "plt.plot(observables_labels, values, '-o')\n", - "plt.xlabel('Observables')\n", - "plt.ylabel('Values')\n", + "plt.plot(observables_labels, values, \"-o\")\n", + "plt.xlabel(\"Observables\")\n", + "plt.ylabel(\"Values\")\n", "plt.show()" ] }, @@ -416,7 +416,7 @@ "# This can happen when the device occasionally behaves strangely. If this cell\n", "# fails, you may just need to run the notebook again.\n", "\n", - "_results = { obs: val for obs, val in zip(observables_labels, values) }\n", + "_results = {obs: val for obs, val in zip(observables_labels, values)}\n", "for _label in [\"IZ\", \"IX\", \"ZI\", \"XI\"]:\n", " assert abs(_results[_label]) < 0.2\n", "for _label in [\"XX\", \"ZZ\"]:\n", @@ -446,6 +446,7 @@ "source": [ "from qiskit import QuantumCircuit\n", "\n", + "\n", "def get_qc_for_n_qubit_GHZ_state(n: int) -> QuantumCircuit:\n", " \"\"\"This function will create a qiskit.QuantumCircuit (qc) for an n-qubit GHZ state.\n", "\n", @@ -458,12 +459,13 @@ " if isinstance(n, int) and n >= 2:\n", " qc = QuantumCircuit(n)\n", " qc.h(0)\n", - " for i in range(n-1):\n", - " qc.cx(i, i+1)\n", + " for i in range(n - 1):\n", + " qc.cx(i, i + 1)\n", " else:\n", " raise Exception(\"n is not a valid input\")\n", " return qc\n", "\n", + "\n", "# Create a new circuit with two qubits (first argument) and two classical\n", "# bits (second argument)\n", "n = 100\n", @@ -497,7 +499,9 @@ "from qiskit.quantum_info import SparsePauliOp\n", "\n", "# ZZII...II, ZIZI...II, ... , ZIII...IZ\n", - "operator_strings = ['Z' + 'I'*i + 'Z' + 'I'*(n-2-i) for i in range(n-1)]\n", + "operator_strings = [\n", + " \"Z\" + \"I\" * i + \"Z\" + \"I\" * (n - 2 - i) for i in range(n - 1)\n", + "]\n", "print(operator_strings)\n", "print(len(operator_strings))\n", "\n", @@ -528,7 +532,9 @@ "# service = QiskitRuntimeService(channel=\"ibm_quantum\", token=\"\")\n", "service = QiskitRuntimeService()\n", "\n", - "backend = service.least_busy(simulator=False, operational=True, min_num_qubits=100)\n", + "backend = service.least_busy(\n", + " simulator=False, operational=True, min_num_qubits=100\n", + ")\n", "pm = generate_preset_pass_manager(optimization_level=1, backend=backend)\n", "\n", "isa_circuit = pm.run(qc)\n", @@ -619,15 +625,17 @@ "from qiskit_ibm_runtime import QiskitRuntimeService\n", "\n", "# data\n", - "data = list(range(1, len(operators)+1)) # Distance between the Z operators\n", + "data = list(range(1, len(operators) + 1)) # Distance between the Z operators\n", "result = job.result()[0]\n", - "values = result.data.evs # Expectation value at each Z operator.\n", - "values = [v / values[0] for v in values] # Normalize the expectation values to evaluate how they decay with distance.\n", + "values = result.data.evs # Expectation value at each Z operator.\n", + "values = [\n", + " v / values[0] for v in values\n", + "] # Normalize the expectation values to evaluate how they decay with distance.\n", "\n", "# plotting graph\n", - "plt.plot(data, values, marker='o', label='100-qubit GHZ state')\n", - "plt.xlabel('Distance between qubits $i$')\n", - "plt.ylabel(r'$\\langle Z_i Z_0 \\rangle / \\langle Z_1 Z_0 \\rangle $')\n", + "plt.plot(data, values, marker=\"o\", label=\"100-qubit GHZ state\")\n", + "plt.xlabel(\"Distance between qubits $i$\")\n", + "plt.ylabel(r\"$\\langle Z_i Z_0 \\rangle / \\langle Z_1 Z_0 \\rangle $\")\n", "plt.legend()\n", "plt.show()" ] diff --git a/docs/guides/ibm-circuit-function.ipynb b/docs/guides/ibm-circuit-function.ipynb index cb39ac6d600..40f9b2e7548 100644 --- a/docs/guides/ibm-circuit-function.ipynb +++ b/docs/guides/ibm-circuit-function.ipynb @@ -92,9 +92,9 @@ "pubs = [(circuit, observable)]\n", "\n", "job = function.run(\n", - " # Use `backend_name=backend_name` if you didn't initialize a backend object\n", - " backend_name=backend.name,\n", - " pubs=pubs\n", + " # Use `backend_name=backend_name` if you didn't initialize a backend object\n", + " backend_name=backend.name,\n", + " pubs=pubs,\n", ")" ] }, @@ -155,10 +155,14 @@ } ], "source": [ - "print(f'The result of the submitted job had {len(result)} PUB\\n')\n", - "print(f'The associated PubResult of this job has the following DataBins:\\n {result[0].data}\\n')\n", - "print(f'And this DataBin has attributes: {result[0].data.keys()}')\n", - "print(f'The expectation values measured from this PUB are: \\n{result[0].data.evs}')" + "print(f\"The result of the submitted job had {len(result)} PUB\\n\")\n", + "print(\n", + " f\"The associated PubResult of this job has the following DataBins:\\n {result[0].data}\\n\"\n", + ")\n", + "print(f\"And this DataBin has attributes: {result[0].data.keys()}\")\n", + "print(\n", + " f\"The expectation values measured from this PUB are: \\n{result[0].data.evs}\"\n", + ")" ] }, { @@ -227,11 +231,7 @@ "source": [ "options = {\"mitigation_level\": 2}\n", "\n", - "job = function.run(\n", - " backend_name=backend.name,\n", - " pubs=pubs,\n", - " options=options\n", - ")" + "job = function.run(backend_name=backend.name, pubs=pubs, options=options)" ] }, { @@ -271,10 +271,7 @@ "metadata": {}, "outputs": [], "source": [ - "options = {\n", - " \"mitigation_level\": 1,\n", - " \"resilience\": {\"zne_mitigation\": True}\n", - "}" + "options = {\"mitigation_level\": 1, \"resilience\": {\"zne_mitigation\": True}}" ] }, { @@ -324,9 +321,11 @@ } ], "source": [ - "print(f'The result of the submitted job had {len(result)} PUB')\n", - "print(f'The expectation values measured from this PUB are: \\n{result[0].data.evs}')\n", - "print(f'And the associated metadata is: \\n{result[0].metadata}')" + "print(f\"The result of the submitted job had {len(result)} PUB\")\n", + "print(\n", + " f\"The expectation values measured from this PUB are: \\n{result[0].data.evs}\"\n", + ")\n", + "print(f\"And the associated metadata is: \\n{result[0].metadata}\")" ] }, { @@ -368,9 +367,7 @@ ], "source": [ "job = function.run(\n", - " backend_name=\"bad_backend_name\",\n", - " pubs=pubs,\n", - " options=options\n", + " backend_name=\"bad_backend_name\", pubs=pubs, options=options\n", ")\n", "\n", "print(job.result())" diff --git a/docs/guides/noise-learning.ipynb b/docs/guides/noise-learning.ipynb index fe046835aac..0d98e87581e 100644 --- a/docs/guides/noise-learning.ipynb +++ b/docs/guides/noise-learning.ipynb @@ -28,7 +28,11 @@ "\n", "from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2\n", "from qiskit_ibm_runtime.noise_learner import NoiseLearner\n", - "from qiskit_ibm_runtime.options import NoiseLearnerOptions, ResilienceOptionsV2, EstimatorOptions\n", + "from qiskit_ibm_runtime.options import (\n", + " NoiseLearnerOptions,\n", + " ResilienceOptionsV2,\n", + " EstimatorOptions,\n", + ")\n", "\n", "# Build a circuit with two entangling layers\n", "num_qubits = 27\n", @@ -123,12 +127,18 @@ } ], "source": [ - "print(f'Noise learner result contains {len(noise_model.data)} entries'\\\n", - " f' and has the following type:\\n {type(noise_model)}\\n')\n", - "print(f'Each element of `NoiseLearnerResult` then contains'\\\n", - " f' an object of type:\\n {type(noise_model.data[0])}\\n')\n", - "print(f'And each of these `LayerError` objects possess the'\\\n", - " f' following data: \\n{noise_model.data[0].error}\\n')" + "print(\n", + " f\"Noise learner result contains {len(noise_model.data)} entries\"\n", + " f\" and has the following type:\\n {type(noise_model)}\\n\"\n", + ")\n", + "print(\n", + " f\"Each element of `NoiseLearnerResult` then contains\"\n", + " f\" an object of type:\\n {type(noise_model.data[0])}\\n\"\n", + ")\n", + "print(\n", + " f\"And each of these `LayerError` objects possess the\"\n", + " f\" following data: \\n{noise_model.data[0].error}\\n\"\n", + ")" ] }, { @@ -176,9 +186,7 @@ "\n", "# Instantiate a noise learner options object\n", "learner_options = NoiseLearnerOptions(\n", - " max_layers_to_learn = 3,\n", - " num_randomizations = 32,\n", - " twirling_strategy = \"all\"\n", + " max_layers_to_learn=3, num_randomizations=32, twirling_strategy=\"all\"\n", ")\n", "\n", "# Instantiate a NoiseLearner object and execute the noise learning program\n", @@ -230,8 +238,10 @@ "outputs": [], "source": [ "# Specify options via a dictionary\n", - "options_dict = {'resilience_level':2,\n", - " 'resilience':{'layer_noise_model': noise_model}}\n", + "options_dict = {\n", + " \"resilience_level\": 2,\n", + " \"resilience\": {\"layer_noise_model\": noise_model},\n", + "}\n", "\n", "estimator = EstimatorV2(mode=backend, options=options_dict)" ] diff --git a/docs/guides/plot-quantum-states.ipynb b/docs/guides/plot-quantum-states.ipynb index edfd75fc09b..0f09cd1f274 100644 --- a/docs/guides/plot-quantum-states.ipynb +++ b/docs/guides/plot-quantum-states.ipynb @@ -50,7 +50,7 @@ "# Create a Bell state for demonstration\n", "qc = QuantumCircuit(2)\n", "qc.h(0)\n", - "qc.crx(pi/2, 0, 1)\n", + "qc.crx(pi / 2, 0, 1)\n", "psi = Statevector(qc)" ] }, @@ -253,6 +253,7 @@ ], "source": [ "from qiskit.quantum_info import DensityMatrix\n", + "\n", "DensityMatrix(psi).draw(\"latex\") # convert to a DensityMatrix and draw" ] }, @@ -282,6 +283,7 @@ ], "source": [ "from qiskit.visualization import plot_state_city\n", + "\n", "plot_state_city(psi)\n", "# Alternative: psi.draw(\"city\")" ] @@ -312,6 +314,7 @@ ], "source": [ "from qiskit.visualization import plot_state_hinton\n", + "\n", "plot_state_hinton(psi)\n", "# Alternative: psi.draw(\"hinton\")" ] @@ -342,6 +345,7 @@ ], "source": [ "from qiskit.visualization import plot_state_paulivec\n", + "\n", "plot_state_paulivec(psi)\n", "# Alternative: psi.draw(\"paulivec\")" ] @@ -372,6 +376,7 @@ ], "source": [ "from qiskit.quantum_info import SparsePauliOp\n", + "\n", "SparsePauliOp.from_operator(psi)" ] }, @@ -401,6 +406,7 @@ ], "source": [ "from qiskit.visualization import plot_state_qsphere\n", + "\n", "plot_state_qsphere(psi)\n", "# Alternative: psi.draw(\"qsphere\")" ] @@ -431,6 +437,7 @@ ], "source": [ "from qiskit.visualization import plot_bloch_multivector\n", + "\n", "plot_bloch_multivector(psi)\n", "# Alternative: psi.draw(\"bloch\")" ] diff --git a/docs/guides/primitive-input-output.ipynb b/docs/guides/primitive-input-output.ipynb index 52f36dc653b..7b10591afa4 100644 --- a/docs/guides/primitive-input-output.ipynb +++ b/docs/guides/primitive-input-output.ipynb @@ -182,23 +182,35 @@ "\n", "parameter_values = np.random.uniform(size=(5,)) # shape (5,)\n", "observables = SparsePauliOp(\"ZZZ\") # shape ()\n", - "#>> pub result has shape (5,)\n", + "# >> pub result has shape (5,)\n", "\n", "# Zip\n", "parameter_values = np.random.uniform(size=(5,)) # shape (5,)\n", - "observables = [SparsePauliOp(pauli) for pauli in [\"III\", \"XXX\", \"YYY\", \"ZZZ\", \"XYZ\"]] # shape (5,)\n", - "#>> pub result has shape (5,)\n", + "observables = [\n", + " SparsePauliOp(pauli) for pauli in [\"III\", \"XXX\", \"YYY\", \"ZZZ\", \"XYZ\"]\n", + "] # shape (5,)\n", + "# >> pub result has shape (5,)\n", "\n", "# Outer/Product\n", "parameter_values = np.random.uniform(size=(1, 6)) # shape (1, 6)\n", - "observables = [[SparsePauliOp(pauli)] for pauli in [\"III\", \"XXX\", \"YYY\", \"ZZZ\"]] # shape (4, 1)\n", - "#>> pub result has shape (4, 6)\n", + "observables = [\n", + " [SparsePauliOp(pauli)] for pauli in [\"III\", \"XXX\", \"YYY\", \"ZZZ\"]\n", + "] # shape (4, 1)\n", + "# >> pub result has shape (4, 6)\n", "\n", "# Standard nd generalization\n", "parameter_values = np.random.uniform(size=(3, 6)) # shape (3, 6)\n", "observables = [\n", - " [[SparsePauliOp(['XII'])], [SparsePauliOp(['IXI'])], [SparsePauliOp(['IIX'])]],\n", - " [[SparsePauliOp(['ZII'])], [SparsePauliOp(['IZI'])], [SparsePauliOp(['IIZ'])]]\n", + " [\n", + " [SparsePauliOp([\"XII\"])],\n", + " [SparsePauliOp([\"IXI\"])],\n", + " [SparsePauliOp([\"IIX\"])],\n", + " ],\n", + " [\n", + " [SparsePauliOp([\"ZII\"])],\n", + " [SparsePauliOp([\"IZI\"])],\n", + " [SparsePauliOp([\"IIZ\"])],\n", + " ],\n", "] # shape (2, 3, 1)" ] }, @@ -347,12 +359,20 @@ } ], "source": [ - "print(f'The result of the submitted job had {len(result)} PUB and has a value:\\n {result}\\n')\n", - "print(f'The associated PubResult of this job has the following DataBins:\\n {result[0].data}\\n')\n", - "print(f'And this DataBin has attributes: {result[0].data.keys()}')\n", - "print('Recall that this shape is due to our array of parameter binding sets having shape (100,), combined with \\n\\\n", - " our array of observables having shape (3, 1), where 2 is the number of parameters in the circuit.\\n')\n", - "print(f'The expectation values measured from this PUB are: \\n{result[0].data.evs}')" + "print(\n", + " f\"The result of the submitted job had {len(result)} PUB and has a value:\\n {result}\\n\"\n", + ")\n", + "print(\n", + " f\"The associated PubResult of this job has the following DataBins:\\n {result[0].data}\\n\"\n", + ")\n", + "print(f\"And this DataBin has attributes: {result[0].data.keys()}\")\n", + "print(\n", + " \"Recall that this shape is due to our array of parameter binding sets having shape (100,), combined with \\n\\\n", + " our array of observables having shape (3, 1), where 2 is the number of parameters in the circuit.\\n\"\n", + ")\n", + "print(\n", + " f\"The expectation values measured from this PUB are: \\n{result[0].data.evs}\"\n", + ")" ] }, { @@ -444,10 +464,16 @@ } ], "source": [ - "print(f'The result of the submitted job had {len(result)} PUB and has a value:\\n {result}\\n')\n", - "print(f'The associated PubResult of this Sampler job has the following DataBins:\\n {result[0].data}\\n')\n", - "print(f'It has a key-value pair dict: \\n{result[0].data.items()}\\n')\n", - "print(f'And the raw data can be converted to a bitstring-count format: \\n{result[0].data.meas.get_counts()}')" + "print(\n", + " f\"The result of the submitted job had {len(result)} PUB and has a value:\\n {result}\\n\"\n", + ")\n", + "print(\n", + " f\"The associated PubResult of this Sampler job has the following DataBins:\\n {result[0].data}\\n\"\n", + ")\n", + "print(f\"It has a key-value pair dict: \\n{result[0].data.items()}\\n\")\n", + "print(\n", + " f\"And the raw data can be converted to a bitstring-count format: \\n{result[0].data.meas.get_counts()}\"\n", + ")" ] }, { @@ -481,11 +507,11 @@ ], "source": [ "# Print out the results metadata\n", - "print('The metadata of the PrimitiveResult is:')\n", + "print(\"The metadata of the PrimitiveResult is:\")\n", "for key, val in result.metadata.items():\n", " print(f\"'{key}' : {val},\")\n", "\n", - "print('\\nThe metadata of the PubResult result is:')\n", + "print(\"\\nThe metadata of the PubResult result is:\")\n", "for key, val in result[0].metadata.items():\n", " print(f\"'{key}' : {val},\")" ] diff --git a/docs/guides/pulse.ipynb b/docs/guides/pulse.ipynb index e9ee5067718..df0424a26ba 100644 --- a/docs/guides/pulse.ipynb +++ b/docs/guides/pulse.ipynb @@ -61,7 +61,7 @@ "circ.measure(0, 0)\n", "circ.measure(1, 1)\n", "\n", - "circ.draw('mpl')" + "circ.draw(\"mpl\")" ] }, { @@ -91,8 +91,10 @@ "\n", "backend = FakeValenciaV2()\n", "\n", - "with pulse.build(backend, name='hadamard') as h_q0:\n", - " pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))" + "with pulse.build(backend, name=\"hadamard\") as h_q0:\n", + " pulse.play(\n", + " Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)\n", + " )" ] }, { @@ -148,7 +150,7 @@ "metadata": {}, "outputs": [], "source": [ - "circ.add_calibration('h', [0], h_q0)" + "circ.add_calibration(\"h\", [0], h_q0)" ] }, { @@ -206,14 +208,16 @@ "from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager\n", "\n", "backend = FakeHanoiV2()\n", - "passmanager = generate_preset_pass_manager(optimization_level=1, backend=backend)\n", + "passmanager = generate_preset_pass_manager(\n", + " optimization_level=1, backend=backend\n", + ")\n", "circ = passmanager.run(circ)\n", "\n", "# Print instructions that only affect qubits 0 and 1\n", "for instruction, qubits in FakeHanoiV2().instructions:\n", " if qubits and set(qubits).issubset({0, 1}):\n", " print(instruction, qubits)\n", - "circ.draw('mpl', idle_wires=False)" + "circ.draw(\"mpl\", idle_wires=False)" ] }, { @@ -253,12 +257,12 @@ "from qiskit.circuit import Gate\n", "\n", "circ = QuantumCircuit(1, 1)\n", - "custom_gate = Gate('my_custom_gate', 1, [3.14, 1])\n", + "custom_gate = Gate(\"my_custom_gate\", 1, [3.14, 1])\n", "# 3.14 is an arbitrary parameter for demonstration\n", "circ.append(custom_gate, [0])\n", "circ.measure(0, 0)\n", "\n", - "circ.draw('mpl')" + "circ.draw(\"mpl\")" ] }, { @@ -268,10 +272,12 @@ "metadata": {}, "outputs": [], "source": [ - "with pulse.build(backend, name='custom') as my_schedule:\n", - " pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0))\n", + "with pulse.build(backend, name=\"custom\") as my_schedule:\n", + " pulse.play(\n", + " Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0)\n", + " )\n", "\n", - "circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1])\n", + "circ.add_calibration(\"my_custom_gate\", [0], my_schedule, [3.14, 1])\n", "# Alternatively: circ.add_calibration(custom_gate, [0], my_schedule)" ] }, @@ -305,7 +311,7 @@ ], "source": [ "circ = passmanager.run(circ)\n", - "circ.draw('mpl', idle_wires=False)" + "circ.draw(\"mpl\", idle_wires=False)" ] }, { @@ -378,7 +384,9 @@ ")\n", "\n", "# Re-generate the passmanager with the new backend target\n", - "passmanager = generate_preset_pass_manager(optimization_level=1, backend=backend)\n", + "passmanager = generate_preset_pass_manager(\n", + " optimization_level=1, backend=backend\n", + ")\n", "qc = passmanager.run(qc)" ] }, @@ -429,7 +437,7 @@ "source": [ "from qiskit import pulse\n", "\n", - "with pulse.build(name='my_example') as my_program:\n", + "with pulse.build(name=\"my_example\") as my_program:\n", " # Add instructions here\n", " pass\n", "\n", @@ -515,11 +523,13 @@ "\n", "backend = FakeValenciaV2()\n", "\n", - "with pulse.build(backend=backend, name='backend_aware') as backend_aware_program:\n", + "with pulse.build(\n", + " backend=backend, name=\"backend_aware\"\n", + ") as backend_aware_program:\n", " channel = pulse.drive_channel(0)\n", " print(pulse.num_qubits())\n", " # Raises an error as backend only has 5 qubits\n", - " #pulse.drive_channel(100)" + " # pulse.drive_channel(100)" ] }, { @@ -626,8 +636,9 @@ } ], "source": [ - "gaussian = pulse.library.Gaussian(num_samples, amp, sigma,\n", - " name=\"Parametric Gaussian\")\n", + "gaussian = pulse.library.Gaussian(\n", + " num_samples, amp, sigma, name=\"Parametric Gaussian\"\n", + ")\n", "gaussian.draw()" ] }, @@ -666,7 +677,9 @@ "import numpy as np\n", "\n", "times = np.arange(num_samples)\n", - "gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2))\n", + "gaussian_samples = np.exp(\n", + " -1 / 2 * ((times - num_samples / 2) ** 2 / sigma**2)\n", + ")\n", "\n", "gaussian = library.Waveform(gaussian_samples, name=\"WF Gaussian\")\n", "gaussian.draw()" @@ -738,7 +751,7 @@ ], "source": [ "with pulse.build() as schedule:\n", - " pulse.play([0.001*i for i in range(160)], channel)\n", + " pulse.play([0.001 * i for i in range(160)], channel)\n", "schedule.draw()" ] }, @@ -921,7 +934,7 @@ } ], "source": [ - "with pulse.build(backend, name='Left align example') as program:\n", + "with pulse.build(backend, name=\"Left align example\") as program:\n", " with pulse.align_left():\n", " gaussian_pulse = library.Gaussian(100, 0.5, 20)\n", " pulse.play(gaussian_pulse, pulse.drive_channel(0))\n", @@ -965,7 +978,7 @@ } ], "source": [ - "with pulse.build(backend, name='Right align example') as program:\n", + "with pulse.build(backend, name=\"Right align example\") as program:\n", " with pulse.align_right():\n", " gaussian_pulse = library.Gaussian(100, 0.5, 20)\n", " pulse.play(gaussian_pulse, pulse.drive_channel(0))\n", @@ -1007,9 +1020,9 @@ } ], "source": [ - "with pulse.build(backend, name='example') as program:\n", + "with pulse.build(backend, name=\"example\") as program:\n", " gaussian_pulse = library.Gaussian(100, 0.5, 20)\n", - " with pulse.align_equispaced(2*gaussian_pulse.duration):\n", + " with pulse.align_equispaced(2 * gaussian_pulse.duration):\n", " pulse.play(gaussian_pulse, pulse.drive_channel(0))\n", " pulse.play(gaussian_pulse, pulse.drive_channel(1))\n", " pulse.play(gaussian_pulse, pulse.drive_channel(1))\n", @@ -1049,7 +1062,7 @@ } ], "source": [ - "with pulse.build(backend, name='example') as program:\n", + "with pulse.build(backend, name=\"example\") as program:\n", " with pulse.align_sequential():\n", " gaussian_pulse = library.Gaussian(100, 0.5, 20)\n", " pulse.play(gaussian_pulse, pulse.drive_channel(0))\n", @@ -1091,7 +1104,7 @@ } ], "source": [ - "with pulse.build(backend, name='Offset example') as program:\n", + "with pulse.build(backend, name=\"Offset example\") as program:\n", " with pulse.phase_offset(3.14, pulse.drive_channel(0)):\n", " pulse.play(gaussian_pulse, pulse.drive_channel(0))\n", " with pulse.frequency_offset(10e6, pulse.drive_channel(0)):\n", diff --git a/docs/guides/q-ctrl-performance-management.ipynb b/docs/guides/q-ctrl-performance-management.ipynb index 26ad67c7061..08851a2f690 100644 --- a/docs/guides/q-ctrl-performance-management.ipynb +++ b/docs/guides/q-ctrl-performance-management.ipynb @@ -307,7 +307,9 @@ " f\"The associated PubResult of this job has the following DataBins:\\n {result[0].data}\\n\"\n", ")\n", "print(f\"And this DataBin has attributes: {result[0].data.keys()}\")\n", - "print(f\"The expectation values measured from this PUB are: \\n{result[0].data.evs}\")" + "print(\n", + " f\"The expectation values measured from this PUB are: \\n{result[0].data.evs}\"\n", + ")" ] }, { @@ -541,9 +543,12 @@ "source": [ "import matplotlib.pyplot as plt\n", "\n", + "\n", "def plot_top_bitstrings(counts_dict, hidden_bitstring=None):\n", " # Sort and take the top 100 bitstrings\n", - " top_100 = sorted(counts_dict.items(), key=lambda x: x[1], reverse=True)[:100]\n", + " top_100 = sorted(counts_dict.items(), key=lambda x: x[1], reverse=True)[\n", + " :100\n", + " ]\n", " if not top_100:\n", " print(\"No bitstrings found in the input dictionary.\")\n", " return\n", @@ -552,17 +557,21 @@ " bitstrings, counts = zip(*top_100)\n", "\n", " # Assign colors: purple if the bitstring matches hidden_bitstring, otherwise gray\n", - " colors = ['#680CE9' if bit == hidden_bitstring else 'gray' for bit in bitstrings]\n", + " colors = [\n", + " \"#680CE9\" if bit == hidden_bitstring else \"gray\" for bit in bitstrings\n", + " ]\n", "\n", " # Create the bar plot\n", " plt.figure(figsize=(15, 8))\n", - " plt.bar(range(len(bitstrings)), counts, tick_label=bitstrings, color=colors)\n", + " plt.bar(\n", + " range(len(bitstrings)), counts, tick_label=bitstrings, color=colors\n", + " )\n", "\n", " # Rotate the bitstrings for better readability\n", " plt.xticks(rotation=90, fontsize=8)\n", - " plt.xlabel('Bitstrings')\n", - " plt.ylabel('Counts')\n", - " plt.title('Top 100 Bitstrings by Counts')\n", + " plt.xlabel(\"Bitstrings\")\n", + " plt.ylabel(\"Counts\")\n", + " plt.title(\"Top 100 Bitstrings by Counts\")\n", "\n", " # Show the plot\n", " plt.tight_layout()\n", diff --git a/docs/guides/qedma-qesem.ipynb b/docs/guides/qedma-qesem.ipynb index 7a33b04e84a..d1448ca4f02 100644 --- a/docs/guides/qedma-qesem.ipynb +++ b/docs/guides/qedma-qesem.ipynb @@ -78,9 +78,9 @@ "execution_count": null, "id": "613c4d93", "metadata": { - "tags": [ - "remove-cell" - ] + "tags": [ + "remove-cell" + ] }, "outputs": [], "source": [ @@ -100,7 +100,7 @@ "\n", "catalog = QiskitFunctionsCatalog(token=\"\")\n", "\n", - "qesem_function = catalog.load('qedma/qesem')" + "qesem_function = catalog.load(\"qedma/qesem\")" ] }, { @@ -128,18 +128,13 @@ "outputs": [], "source": [ "job = qesem_function.run(\n", - " action = \"estimate_qpu_time\",\n", - " instance = \"hub/group/project\",\n", - " pubs = [\n", - " (\n", - " circ,\n", - " [obs1,obs2,obs3]\n", - " )\n", - " ],\n", - " precision = 0.03,\n", - " run_options = {\n", + " action=\"estimate_qpu_time\",\n", + " instance=\"hub/group/project\",\n", + " pubs=[(circ, [obs1, obs2, obs3])],\n", + " precision=0.03,\n", + " run_options={\n", " \"backend_name\": \"ibm_brisbane\",\n", - " }\n", + " },\n", ")" ] }, @@ -159,18 +154,13 @@ "outputs": [], "source": [ "job = qesem_function.run(\n", - " action = \"execute\",\n", - " instance = \"hub/group/project\",\n", - " pubs = [\n", - " (\n", - " circ,\n", - " [obs1,obs2,obs3]\n", - " )\n", - " ],\n", - " precision = 0.03,\n", - " run_options = {\n", + " action=\"execute\",\n", + " instance=\"hub/group/project\",\n", + " pubs=[(circ, [obs1, obs2, obs3])],\n", + " precision=0.03,\n", + " run_options={\n", " \"backend_name\": \"ibm_brisbane\",\n", - " }\n", + " },\n", ")" ] }, @@ -224,22 +214,14 @@ "source": [ "# example execute QESEM job\n", "job = qesem_function.run(\n", - " action = \"execute\",\n", - " instance = \"hub/group/project\",\n", - " pubs = [\n", - " (\n", - " bell,\n", - " [obs1,obs2,obs3]\n", - " )\n", - " ],\n", - " precision = 0.03,\n", - " run_options = {\n", + " action=\"execute\",\n", + " instance=\"hub/group/project\",\n", + " pubs=[(bell, [obs1, obs2, obs3])],\n", + " precision=0.03,\n", + " run_options={\n", " \"backend_name\": \"ibm_brisbane\",\n", " },\n", - " custom_options = {\n", - " \"max_qpu_time\": 14400,\n", - " \"transpilation_level\": 0\n", - " }\n", + " custom_options={\"max_qpu_time\": 14400, \"transpilation_level\": 0},\n", ")" ] }, diff --git a/docs/guides/qunasys-quri-chemistry.ipynb b/docs/guides/qunasys-quri-chemistry.ipynb index 98e9bb387cd..34c75354eb1 100644 --- a/docs/guides/qunasys-quri-chemistry.ipynb +++ b/docs/guides/qunasys-quri-chemistry.ipynb @@ -136,14 +136,14 @@ "source": [ "mole = {\n", " \"atom\": \"O 0 0 0; H 0.2774 0.8929 0.2544; H 0.6068 -0.2383 -0.7169\",\n", - " \"basis\": \"6-31g\", # default to \"sto-3g\"\n", - " \"spin\": 0.0, # default to 0.0. Current code forces spin = 0.0\n", - " \"charge\": 0, # default to 0\n", - " \"active_space\": { # default to None. Equivalent to no active space chosen.\n", + " \"basis\": \"6-31g\", # default to \"sto-3g\"\n", + " \"spin\": 0.0, # default to 0.0. Current code forces spin = 0.0\n", + " \"charge\": 0, # default to 0\n", + " \"active_space\": { # default to None. Equivalent to no active space chosen.\n", " \"n_active_ele\": 10,\n", " \"n_active_orb\": 10,\n", - " \"active_orbs_indices\": [i for i in range(10)]\n", - " }\n", + " \"active_orbs_indices\": [i for i in range(10)],\n", + " },\n", "}" ] }, @@ -243,8 +243,10 @@ "qsci_uccsd_json = {\n", " \"mole\": mole,\n", " \"ansatz\": \"UCCSD\",\n", - " \"state_prep_method\": \"CCSD\", # this is optional and defaulted to \"CCSD\".\n", - " \"ansatz_setting\": {\"use_singles\": False}, # this is optional and defaulted to the list above.\n", + " \"state_prep_method\": \"CCSD\", # this is optional and defaulted to \"CCSD\".\n", + " \"ansatz_setting\": {\n", + " \"use_singles\": False\n", + " }, # this is optional and defaulted to the list above.\n", " \"qsci_setting\": {\"n_shots\": 1e5, \"number_of_states_pick_out\": 1e4},\n", "}" ] @@ -269,14 +271,14 @@ "qsci_double_exc_json = {\n", " \"mole\": mole,\n", " \"ansatz\": \"DoubleExcitation\",\n", - " \"state_prep_method\": \"CCSD\", # this is optional and defaulted to \"CCSD\".\n", - " \"ansatz_setting\": {\"n_amplitudes\": 20}, # this is optional and defaulted to {\"n_amplitudes\": 10}.\n", + " \"state_prep_method\": \"CCSD\", # this is optional and defaulted to \"CCSD\".\n", + " \"ansatz_setting\": {\n", + " \"n_amplitudes\": 20\n", + " }, # this is optional and defaulted to {\"n_amplitudes\": 10}.\n", " \"qsci_setting\": {\"n_shots\": 1e5, \"number_of_states_pick_out\": 5e4},\n", - " \"mitigation_setting\": { # please refer to the \"error mitigation\" section of this tutorial.\n", - " \"configuration_recovery\": {\n", - " \"number_of_states_pick_out\": 10000\n", - " }\n", - " }\n", + " \"mitigation_setting\": { # please refer to the \"error mitigation\" section of this tutorial.\n", + " \"configuration_recovery\": {\"number_of_states_pick_out\": 10000}\n", + " },\n", "}" ] }, @@ -349,6 +351,7 @@ "source": [ "import datetime\n", "import time\n", + "\n", "job = function.run(\n", " method=\"QSCI\",\n", " parameters=qsci_double_exc_json,\n", @@ -357,10 +360,10 @@ ")\n", "\n", "while True:\n", - " print(datetime.datetime.now(), job.status())\n", - " if job.status() in [\"ERROR\", \"DONE\"]:\n", - " break\n", - " time.sleep(10)\n", + " print(datetime.datetime.now(), job.status())\n", + " if job.status() in [\"ERROR\", \"DONE\"]:\n", + " break\n", + " time.sleep(10)\n", "\n", "result = job.result()" ] @@ -416,7 +419,7 @@ } ], "source": [ - "CASCI_ENERGY = -76.0508056368444 # Exact result\n", + "CASCI_ENERGY = -76.0508056368444 # Exact result\n", "qsci_energy = result[\"qsci_energy\"]\n", "print(f\"CASCI energy: {CASCI_ENERGY} Ha\")\n", "print(f\"QSCI energy: {qsci_energy} Ha\")\n", @@ -470,14 +473,18 @@ "source": [ "import numpy as np\n", "\n", - "amps = np.array(result[\"state_vector\"][\"reals\"]) + 1j * np.array(result[\"state_vector\"][\"imags\"])\n", + "amps = np.array(result[\"state_vector\"][\"reals\"]) + 1j * np.array(\n", + " result[\"state_vector\"][\"imags\"]\n", + ")\n", "sort_idx = np.argsort(np.abs(amps))\n", "\n", - "for i, (bit, real, imag) in enumerate(zip(\n", - " np.array(result[\"state_vector\"][\"bits\"])[sort_idx][::-1],\n", - " np.array(result[\"state_vector\"][\"reals\"])[sort_idx][::-1],\n", - " np.array(result[\"state_vector\"][\"imags\"])[sort_idx][::-1],\n", - ")):\n", + "for i, (bit, real, imag) in enumerate(\n", + " zip(\n", + " np.array(result[\"state_vector\"][\"bits\"])[sort_idx][::-1],\n", + " np.array(result[\"state_vector\"][\"reals\"])[sort_idx][::-1],\n", + " np.array(result[\"state_vector\"][\"imags\"])[sort_idx][::-1],\n", + " )\n", + "):\n", " if i > 20:\n", " break\n", " print(\n", @@ -523,16 +530,14 @@ " \"mole\": mole,\n", " \"ansatz\": \"KuCJ\",\n", " \"state_prep_method\": \"RANDOM\", # this is optional and defaulted to \"RANDOM\" for \"KuCJ\".\n", - " \"ansatz_setting\": {\"k\": 1}, # this is optional and defaulted to the table above.\n", - " \"qsci_setting\": {\n", - " \"n_shots\": 1e5, \"number_of_states_pick_out\": 5e4\n", + " \"ansatz_setting\": {\n", + " \"k\": 1\n", + " }, # this is optional and defaulted to the table above.\n", + " \"qsci_setting\": {\"n_shots\": 1e5, \"number_of_states_pick_out\": 5e4},\n", + " \"max_iter\": 5, # Default to 2000. Choose 5 iteration for demonstration.\n", + " \"mitigation_setting\": { # Refer to the \"error mitigation\" section.\n", + " \"configuration_recovery\": {\"number_of_states_pick_out\": 10000}\n", " },\n", - " \"max_iter\": 5, # Default to 2000. Choose 5 iteration for demonstration.\n", - " \"mitigation_setting\": { # Refer to the \"error mitigation\" section.\n", - " \"configuration_recovery\": {\n", - " \"number_of_states_pick_out\": 10000\n", - " }\n", - " }\n", "}" ] }, @@ -544,6 +549,7 @@ "outputs": [], "source": [ "import time\n", + "\n", "opt_job = function.run(\n", " method=\"OPT_QSCI\",\n", " parameters=\"opt_qsci_1ucj_json\",\n", @@ -634,21 +640,25 @@ } ], "source": [ - "CASCI_ENERGY = -76.0508056368444 # Exact result\n", + "CASCI_ENERGY = -76.0508056368444 # Exact result\n", "opt_qsci_energy = opt_result[\"qsci_energy\"]\n", "print(f\"CASCI energy: {CASCI_ENERGY} Ha\")\n", "print(f\"QSCI energy: {opt_qsci_energy} Ha\")\n", "print(f\"Energy error: {(opt_qsci_energy - CASCI_ENERGY) * 1000: .2e} mHa\")\n", "print()\n", "print(\"Top 20 important configurations:\")\n", - "amps = np.array(opt_result[\"state_vector\"][\"reals\"]) + 1j * np.array(opt_result[\"state_vector\"][\"imags\"])\n", + "amps = np.array(opt_result[\"state_vector\"][\"reals\"]) + 1j * np.array(\n", + " opt_result[\"state_vector\"][\"imags\"]\n", + ")\n", "sort_idx = np.argsort(np.abs(amps))\n", "\n", - "for i, (bit, real, imag) in enumerate(zip(\n", - " np.array(opt_result[\"state_vector\"][\"bits\"])[sort_idx][::-1],\n", - " np.array(opt_result[\"state_vector\"][\"reals\"])[sort_idx][::-1],\n", - " np.array(opt_result[\"state_vector\"][\"imags\"])[sort_idx][::-1],\n", - ")):\n", + "for i, (bit, real, imag) in enumerate(\n", + " zip(\n", + " np.array(opt_result[\"state_vector\"][\"bits\"])[sort_idx][::-1],\n", + " np.array(opt_result[\"state_vector\"][\"reals\"])[sort_idx][::-1],\n", + " np.array(opt_result[\"state_vector\"][\"imags\"])[sort_idx][::-1],\n", + " )\n", + "):\n", " if i > 20:\n", " break\n", " print(\n", @@ -736,9 +746,7 @@ "source": [ "# Use default configuration recovery setting\n", "default_mitigation_setting = {\n", - " \"mitigation_setting\": {\n", - " \"configuration_recovery\": True\n", - " }\n", + " \"mitigation_setting\": {\"configuration_recovery\": True}\n", "}\n", "\n", "# Customized configuration recovery setting\n", @@ -747,7 +755,7 @@ " \"configuration_recovery\": {\n", " \"n_recover_iteration\": 20,\n", " \"n_batch\": 10,\n", - " \"number_of_states_pick_out\": 5000\n", + " \"number_of_states_pick_out\": 5000,\n", " }\n", " }\n", "}" @@ -786,20 +794,16 @@ "source": [ "d = 1.0\n", "n2_dissociation_qsci = {\n", - " \"mole\": {\"atom\": f\"N 0 0 0; N 0 0 {d}\",},\n", + " \"mole\": {\n", + " \"atom\": f\"N 0 0 0; N 0 0 {d}\",\n", + " },\n", " \"ansatz\": \"DoubleExcitation\",\n", " \"state_prep_method\": \"CCSD\",\n", - " \"qsci_setting\": {\n", - " \"n_shots\": 100000, \"number_of_states_pick_out\": 50000\n", - " },\n", - " \"mitigation_setting\": {\n", - " \"configuration_recovery\": True\n", - " },\n", + " \"qsci_setting\": {\"n_shots\": 100000, \"number_of_states_pick_out\": 50000},\n", + " \"mitigation_setting\": {\"configuration_recovery\": True},\n", "}\n", "job = function.run(\n", - " method=\"QSCI\",\n", - " parameters=n2_dissociation_qsci,\n", - " backend=\"ibm_strasbourg\"\n", + " method=\"QSCI\", parameters=n2_dissociation_qsci, backend=\"ibm_strasbourg\"\n", ")" ] }, diff --git a/docs/guides/represent-quantum-computers.ipynb b/docs/guides/represent-quantum-computers.ipynb index 1695030061c..b601777d3f0 100644 --- a/docs/guides/represent-quantum-computers.ipynb +++ b/docs/guides/represent-quantum-computers.ipynb @@ -425,7 +425,11 @@ " basis_gates=basis_gates,\n", " coupling_map=coupling_map,\n", " num_qubits=target.num_qubits,\n", - " custom_name_mapping={ \"if_else\": IfElseOp, \"switch_case\": SwitchCaseOp, \"for_loop\": ForLoopOp },\n", + " custom_name_mapping={\n", + " \"if_else\": IfElseOp,\n", + " \"switch_case\": SwitchCaseOp,\n", + " \"for_loop\": ForLoopOp,\n", + " },\n", ")\n", "\n", "for i, (op, qargs) in enumerate(target.instructions):\n", diff --git a/docs/guides/save-circuits.ipynb b/docs/guides/save-circuits.ipynb index 5d6373bb6d0..3bea7995b44 100644 --- a/docs/guides/save-circuits.ipynb +++ b/docs/guides/save-circuits.ipynb @@ -23,7 +23,7 @@ "\n", "qc = QuantumCircuit(2)\n", "qc.h(0)\n", - "qc.cx(0,1)\n", + "qc.cx(0, 1)\n", "qc.measure_all()" ] }, @@ -44,7 +44,7 @@ "source": [ "from qiskit import qpy\n", "\n", - "with open('test.qpy', 'wb') as file:\n", + "with open(\"test.qpy\", \"wb\") as file:\n", " qpy.dump(qc, file)" ] }, @@ -77,10 +77,10 @@ } ], "source": [ - "with open('test.qpy', 'rb') as handle:\n", + "with open(\"test.qpy\", \"rb\") as handle:\n", " qc = qpy.load(handle)\n", "\n", - "qc[0].draw('mpl')" + "qc[0].draw(\"mpl\")" ] }, { @@ -96,7 +96,8 @@ "source": [ "# Cleanup the file we created (this cell should be hidden from the user)\n", "import pathlib\n", - "pathlib.Path('test.qpy').unlink()" + "\n", + "pathlib.Path(\"test.qpy\").unlink()" ] } ], diff --git a/docs/guides/save-jobs.ipynb b/docs/guides/save-jobs.ipynb index 71e8cef4983..d9f6f2ae849 100644 --- a/docs/guides/save-jobs.ipynb +++ b/docs/guides/save-jobs.ipynb @@ -67,9 +67,9 @@ "execution_count": 2, "id": "43d0f06e-f97f-4c19-b242-02cb0bd420a9", "metadata": { - "tags": [ - "ignore-warnings" - ] + "tags": [ + "ignore-warnings" + ] }, "outputs": [ { @@ -142,6 +142,7 @@ "source": [ "import json\n", "from qiskit_ibm_runtime import RuntimeEncoder\n", + "\n", "with open(\"result.json\", \"w\") as file:\n", " json.dump(retrieved_job.result(), file, cls=RuntimeEncoder)" ] @@ -173,6 +174,7 @@ ], "source": [ "from qiskit_ibm_runtime import RuntimeDecoder\n", + "\n", "with open(\"result.json\", \"r\") as file:\n", " result = json.load(file, cls=RuntimeDecoder)\n", "\n", @@ -192,7 +194,8 @@ "source": [ "# Cleanup the file we created (this cell should be hidden from the user)\n", "import pathlib\n", - "pathlib.Path('result.json').unlink()" + "\n", + "pathlib.Path(\"result.json\").unlink()" ] } ], diff --git a/docs/guides/serverless-first-program.ipynb b/docs/guides/serverless-first-program.ipynb index d2b7ed4dcf8..bcefd40b11f 100644 --- a/docs/guides/serverless-first-program.ipynb +++ b/docs/guides/serverless-first-program.ipynb @@ -39,7 +39,8 @@ "source": [ "# This cell is hidden from users, it just creates a new folder\n", "from pathlib import Path\n", - "Path('./source_files').mkdir(exist_ok=True)" + "\n", + "Path(\"./source_files\").mkdir(exist_ok=True)" ] }, { @@ -323,6 +324,7 @@ "source": [ "# This cell is hidden from users, it just deletes the working folder we created\n", "import shutil\n", + "\n", "shutil.rmtree(\"./source_files/\")" ] } diff --git a/docs/guides/serverless-run-first-workload.ipynb b/docs/guides/serverless-run-first-workload.ipynb index 10af7fecbbe..4766277770a 100644 --- a/docs/guides/serverless-run-first-workload.ipynb +++ b/docs/guides/serverless-run-first-workload.ipynb @@ -80,7 +80,7 @@ "from qiskit.circuit.random import random_circuit\n", "\n", "qc_random = [(random_circuit(4, 4, measure=True)) for _ in range(30)]\n", - "qc_random[0].draw(output='mpl', idle_wires=False)" + "qc_random[0].draw(output=\"mpl\", idle_wires=False)" ] }, { @@ -146,7 +146,7 @@ "metadata": {}, "outputs": [], "source": [ - "transpile_remote_serverless = serverless.load('transpile_remote_serverless')" + "transpile_remote_serverless = serverless.load(\"transpile_remote_serverless\")" ] }, { @@ -167,7 +167,7 @@ "job = transpile_remote_serverless.run(\n", " circuits=qc_random,\n", " backend=backend.name,\n", - " optimization_level=optimization_level\n", + " optimization_level=optimization_level,\n", ")" ] }, diff --git a/docs/guides/set-optimization.ipynb b/docs/guides/set-optimization.ipynb index 552f3c69edf..2068b4939cd 100644 --- a/docs/guides/set-optimization.ipynb +++ b/docs/guides/set-optimization.ipynb @@ -338,7 +338,9 @@ "approx_fid = trace_to_fid(\n", " np.trace(np.dot(Operator(qc_t3_approx_small).adjoint().data, UU))\n", ")\n", - "print(f\"Synthesis fidelity\\nExact: {exact_fid:.3f}\\nApproximate: {approx_fid:.3f}\")" + "print(\n", + " f\"Synthesis fidelity\\nExact: {exact_fid:.3f}\\nApproximate: {approx_fid:.3f}\"\n", + ")" ] }, { diff --git a/docs/guides/simulate-stabilizer-circuits.ipynb b/docs/guides/simulate-stabilizer-circuits.ipynb index 91cd23f27bf..3e76ebb696b 100644 --- a/docs/guides/simulate-stabilizer-circuits.ipynb +++ b/docs/guides/simulate-stabilizer-circuits.ipynb @@ -104,9 +104,13 @@ ")\n", "\n", "# Initialize a Sampler backed by the stabilizer circuit simulator\n", - "exact_sampler = Sampler(options=dict(backend_options=dict(method=\"stabilizer\")))\n", + "exact_sampler = Sampler(\n", + " options=dict(backend_options=dict(method=\"stabilizer\"))\n", + ")\n", "# The circuit needs to be transpiled to the AerSimulator target\n", - "pass_manager = generate_preset_pass_manager(1, AerSimulator(method=\"stabilizer\"))\n", + "pass_manager = generate_preset_pass_manager(\n", + " 1, AerSimulator(method=\"stabilizer\")\n", + ")\n", "isa_circuit = pass_manager.run(measured_circuit)\n", "pub = (isa_circuit, params)\n", "job = exact_sampler.run([pub])\n", @@ -150,7 +154,9 @@ ")\n", "\n", "noisy_sampler = Sampler(\n", - " options=dict(backend_options=dict(method=\"stabilizer\", noise_model=noise_model))\n", + " options=dict(\n", + " backend_options=dict(method=\"stabilizer\", noise_model=noise_model)\n", + " )\n", ")\n", "job = noisy_sampler.run([pub])\n", "result = job.result()\n", diff --git a/docs/guides/simulate-with-qiskit-aer.ipynb b/docs/guides/simulate-with-qiskit-aer.ipynb index bd3560a5ee6..46406070a72 100644 --- a/docs/guides/simulate-with-qiskit-aer.ipynb +++ b/docs/guides/simulate-with-qiskit-aer.ipynb @@ -127,7 +127,9 @@ " depolarizing_error(cx_depolarizing_prob, 2), [\"cx\"]\n", ")\n", "\n", - "noisy_estimator = Estimator(options=dict(backend_options=dict(noise_model=noise_model)))\n", + "noisy_estimator = Estimator(\n", + " options=dict(backend_options=dict(noise_model=noise_model))\n", + ")\n", "job = noisy_estimator.run([pub])\n", "result = job.result()\n", "pub_result = result[0]\n", @@ -226,7 +228,9 @@ "measured_circuit = circuit.copy()\n", "measured_circuit.measure_all()\n", "\n", - "noisy_sampler = Sampler(options=dict(backend_options=dict(noise_model=noise_model)))\n", + "noisy_sampler = Sampler(\n", + " options=dict(backend_options=dict(noise_model=noise_model))\n", + ")\n", "# The circuit needs to be transpiled to the AerSimulator target\n", "pass_manager = generate_preset_pass_manager(3, AerSimulator())\n", "isa_circuit = pass_manager.run(measured_circuit)\n", diff --git a/docs/guides/specify-observables-pauli.ipynb b/docs/guides/specify-observables-pauli.ipynb index b5dae5f369d..14acaa3984a 100644 --- a/docs/guides/specify-observables-pauli.ipynb +++ b/docs/guides/specify-observables-pauli.ipynb @@ -70,15 +70,20 @@ ], "source": [ "from qiskit.quantum_info import SparsePauliOp\n", + "\n", "# define the number of qubits\n", "n = 12\n", "\n", "# define the single Pauli terms as (\"Paulis\", [indices], coefficient)\n", - "interactions = [(\"ZZ\", [i, i + 1], 1) for i in range(n - 1)] # we assume spins on a 1D line\n", + "interactions = [\n", + " (\"ZZ\", [i, i + 1], 1) for i in range(n - 1)\n", + "] # we assume spins on a 1D line\n", "field = [(\"X\", [i], -1) for i in range(n)]\n", "\n", "# build the operator\n", - "hamiltonian = SparsePauliOp.from_sparse_list(interactions + field, num_qubits=n)\n", + "hamiltonian = SparsePauliOp.from_sparse_list(\n", + " interactions + field, num_qubits=n\n", + ")\n", "print(hamiltonian)" ] }, @@ -127,10 +132,9 @@ "import numpy as np\n", "from qiskit.quantum_info import SparsePauliOp\n", "\n", - "matrix = np.array([[-1, 0, 0.5, -1],\n", - "\t\t [0, 1, 1, 0.5],\n", - "\t\t [0.5, 1, -1, 0],\n", - "\t\t [-1, 0.5, 0, 1]])\n", + "matrix = np.array(\n", + " [[-1, 0, 0.5, -1], [0, 1, 1, 0.5], [0.5, 1, -1, 0], [-1, 0.5, 0, 1]]\n", + ")\n", "\n", "observable = SparsePauliOp.from_operator(matrix)\n", "print(observable)" diff --git a/docs/guides/transpile-with-pass-managers.ipynb b/docs/guides/transpile-with-pass-managers.ipynb index 51cb649e426..139c88a0271 100644 --- a/docs/guides/transpile-with-pass-managers.ipynb +++ b/docs/guides/transpile-with-pass-managers.ipynb @@ -46,7 +46,9 @@ "\n", "service = QiskitRuntimeService()\n", "backend = service.backend(\"ibm_brisbane\")\n", - "pass_manager = generate_preset_pass_manager(optimization_level=3, backend=backend)" + "pass_manager = generate_preset_pass_manager(\n", + " optimization_level=3, backend=backend\n", + ")" ] }, { @@ -252,7 +254,9 @@ "from qiskit.transpiler.passes import UnitarySynthesis, Unroll3qOrMore\n", "\n", "basis_gates = [\"rx\", \"ry\", \"rxx\"]\n", - "init = PassManager([UnitarySynthesis(basis_gates, min_qubits=3), Unroll3qOrMore()])\n", + "init = PassManager(\n", + " [UnitarySynthesis(basis_gates, min_qubits=3), Unroll3qOrMore()]\n", + ")\n", "staged_pm = StagedPassManager(\n", " stages=[\"init\", \"translation\"], init=init, translation=translate\n", ")" diff --git a/docs/guides/transpiler-plugins.ipynb b/docs/guides/transpiler-plugins.ipynb index 4a6294f7189..70380e6654a 100644 --- a/docs/guides/transpiler-plugins.ipynb +++ b/docs/guides/transpiler-plugins.ipynb @@ -145,7 +145,9 @@ } ], "source": [ - "from qiskit.transpiler.passes.synthesis import high_level_synthesis_plugin_names\n", + "from qiskit.transpiler.passes.synthesis import (\n", + " high_level_synthesis_plugin_names,\n", + ")\n", "\n", "high_level_synthesis_plugin_names(\"clifford\")" ] @@ -189,7 +191,9 @@ } ], "source": [ - "from qiskit.transpiler.passes.synthesis.plugin import HighLevelSynthesisPluginManager\n", + "from qiskit.transpiler.passes.synthesis.plugin import (\n", + " HighLevelSynthesisPluginManager,\n", + ")\n", "\n", "HighLevelSynthesisPluginManager().plugins.names()" ] @@ -248,7 +252,9 @@ " optimization_level=3,\n", " backend=backend,\n", " unitary_synthesis_method=\"sk\",\n", - " unitary_synthesis_plugin_config=dict(basis_gates=[\"cz\", \"id\", \"rz\", \"sx\", \"x\"]),\n", + " unitary_synthesis_plugin_config=dict(\n", + " basis_gates=[\"cz\", \"id\", \"rz\", \"sx\", \"x\"]\n", + " ),\n", ")" ] }, diff --git a/docs/guides/transpiler-stages.ipynb b/docs/guides/transpiler-stages.ipynb index 9adf0d00470..ba726e39fd7 100644 --- a/docs/guides/transpiler-stages.ipynb +++ b/docs/guides/transpiler-stages.ipynb @@ -156,7 +156,7 @@ } ], "source": [ - "ghz.draw('mpl', idle_wires=False)" + "ghz.draw(\"mpl\", idle_wires=False)" ] }, { @@ -244,7 +244,7 @@ "print(\"native gates:\" + str(backend.operation_names))\n", "qc = QuantumCircuit(2)\n", "qc.swap(0, 1)\n", - "qc.decompose().draw('mpl')" + "qc.decompose().draw(\"mpl\")" ] }, { @@ -280,7 +280,7 @@ "source": [ "qc = QuantumCircuit(3)\n", "qc.ccx(0, 1, 2)\n", - "qc.decompose().draw('mpl')" + "qc.decompose().draw(\"mpl\")" ] }, { @@ -424,7 +424,7 @@ " optimization_level=3,\n", " backend=backend,\n", " timing_constraints=backend.target.timing_constraints(),\n", - " scheduling_method=\"asap\"\n", + " scheduling_method=\"asap\",\n", ")\n", "\n", "\n", diff --git a/docs/guides/visualize-results.ipynb b/docs/guides/visualize-results.ipynb index 99f92c14127..afb4ecf45ff 100644 --- a/docs/guides/visualize-results.ipynb +++ b/docs/guides/visualize-results.ipynb @@ -206,7 +206,7 @@ "observables_labels = [\"ZZ\", \"XX\", \"YZ\", \"ZY\", \"XY\", \"XZ\", \"ZX\"]\n", "observables = [SparsePauliOp(label) for label in observables_labels]\n", "\n", - "result = Estimator().run([qc]*7, observables).result()\n", + "result = Estimator().run([qc] * 7, observables).result()\n", "print(result)\n", "\n", "# Plot using Matplotlib\n", @@ -252,7 +252,11 @@ ], "source": [ "from math import sqrt\n", - "standard_error = [sqrt(exp_data[\"variance\"])/sqrt(exp_data[\"shots\"]) for exp_data in result.metadata]\n", + "\n", + "standard_error = [\n", + " sqrt(exp_data[\"variance\"]) / sqrt(exp_data[\"shots\"])\n", + " for exp_data in result.metadata\n", + "]\n", "\n", "_, ax = plt.subplots()\n", "ax.bar(observables_labels, result.values, yerr=standard_error, capsize=2)\n", From 96de9dbc648f01f6e6f595ced49eeeaf68cdc1df Mon Sep 17 00:00:00 2001 From: Frank Harkins Date: Tue, 29 Oct 2024 15:23:38 +0000 Subject: [PATCH 3/3] Update README --- README.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index cb36a17fd40..8feee5f40a9 100644 --- a/README.md +++ b/README.md @@ -189,8 +189,9 @@ change, CI will alert us. ### Lint notebooks -We use [`squeaky`](https://github.com/frankharkins/squeaky) to lint our -notebooks. First install `tox` using [pipx](https://pipx.pypa.io/stable/). +We use [`squeaky`](https://github.com/frankharkins/squeaky) and +[`ruff`](https://docs.astral.sh/ruff/) to lint our notebooks. First install +`tox` using [pipx](https://pipx.pypa.io/stable/). ```sh pipx install tox @@ -200,19 +201,19 @@ To check if a notebook needs linting: ```sh # Check all notebooks in ./docs -tox -e lint -- docs/**/*.ipynb +tox -e lint ``` -To fix problems in a notebooks, run: +Some problems can be fixed automatically. To fix these problems, run: ```sh +# Fix problems in all notebooks +tox -e fix + +# Fix problems in a specific notebook tox -e fix -- path/to/notebook ``` -Or, you can retrieve an executed and linted version of your notebook from CI -following the steps at the end of the [Execute notebooks](#execute-notebooks) -section. - If you use the Jupyter notebook editor, consider adding squeaky as a [pre-save hook](https://github.com/frankharkins/squeaky?tab=readme-ov-file#jupyter-pre-save-hook). This will lint your notebooks as you save them, so you never need to worry