From a706c4cf245281636543aebbd667728b619ec919 Mon Sep 17 00:00:00 2001 From: Saurav Maheshkar Date: Wed, 9 Apr 2025 04:38:52 +0100 Subject: [PATCH 1/3] feat: add black[jupyter] as a formatting tool --- check/format-incremental | 2 +- .../quimb/Cirq-to-Tensor-Networks.ipynb | 36 +-- .../quimb/Contract-a-Grid-Circuit.ipynb | 48 +-- cirq-core/cirq/contrib/svg/example.ipynb | 40 +-- cirq-web/bloch_sphere_example.ipynb | 20 +- cirq-web/circuit_example.ipynb | 16 +- dev_tools/requirements/deps/format.txt | 2 +- docs/_template.ipynb | 2 +- docs/build/custom_gates.ipynb | 80 ++--- docs/build/gates.ipynb | 4 +- docs/build/interop.ipynb | 26 +- docs/build/operators.ipynb | 10 +- docs/build/protocols.ipynb | 17 +- docs/build/qubits.ipynb | 2 +- docs/build/qudits.ipynb | 34 +- docs/experiments/fourier_checking.ipynb | 80 +++-- docs/experiments/hidden_linear_function.ipynb | 112 ++++--- docs/experiments/quantum_walks.ipynb | 81 ++--- docs/experiments/shor.ipynb | 115 +++---- docs/experiments/textbook_algorithms.ipynb | 62 ++-- docs/experiments/variational_algorithm.ipynb | 41 ++- docs/gatezoo.ipynb | 7 +- docs/google/best_practices.ipynb | 24 +- docs/google/concepts.ipynb | 9 +- docs/google/internal_gates.ipynb | 7 +- docs/google/qubit-placement.ipynb | 44 ++- docs/hardware/aqt/getting_started.ipynb | 5 +- .../getting_started_honeywell.ipynb | 16 +- .../azure-quantum/getting_started_ionq.ipynb | 21 +- docs/hardware/ionq/getting_started.ipynb | 12 +- docs/hardware/pasqal/getting_started.ipynb | 81 ++--- docs/hardware/rigetti/getting_started.ipynb | 28 +- docs/named_topologies.ipynb | 112 +++++-- docs/noise/heatmaps.ipynb | 87 ++--- .../qcvv/coherent_vs_incoherent_xeb.ipynb | 1 + docs/noise/qcvv/isolated_xeb.ipynb | 46 +-- docs/noise/qcvv/parallel_xeb.ipynb | 94 +++--- docs/noise/qcvv/xeb_calibration_example.ipynb | 71 ++--- docs/noise/qcvv/xeb_theory.ipynb | 84 ++--- docs/noise/representing_noise.ipynb | 65 +--- docs/simulate/noisy_simulation.ipynb | 17 + docs/simulate/params.ipynb | 16 +- docs/simulate/qvm_stabilizer_example.ipynb | 2 +- docs/simulate/state_histograms.ipynb | 25 +- docs/start/intro.ipynb | 44 ++- docs/transform/routing_transformer.ipynb | 38 ++- docs/tutorials/google/colab.ipynb | 27 +- docs/tutorials/google/echoes.ipynb | 54 ++-- .../google/identifying_hardware_changes.ipynb | 98 +++--- docs/tutorials/google/spin_echoes.ipynb | 75 +++-- docs/tutorials/google/start.ipynb | 33 +- .../visualizing_calibration_metrics.ipynb | 53 +++- .../advanced/quantum_utility_sim_4a.ipynb | 17 +- .../advanced/quantum_utility_sim_4b.ipynb | 13 +- examples/advanced/quantum_volume.ipynb | 127 ++++---- examples/advanced/quantum_volume_errors.ipynb | 298 +++++++++--------- .../advanced/quantum_volume_routing.ipynb | 45 +-- examples/direct_fidelity_estimation.ipynb | 26 +- examples/stabilizer_code.ipynb | 12 +- 59 files changed, 1478 insertions(+), 1186 deletions(-) diff --git a/check/format-incremental b/check/format-incremental index 72c0e79cd60..3c73dbc8136 100755 --- a/check/format-incremental +++ b/check/format-incremental @@ -130,7 +130,7 @@ echo "Running the black formatter... (version: $BLACKVERSION)" args=("${arg_color[@]}") if (( only_print == 1 )); then - args+=("--check" "--diff") + args+=("--check" "--diff", "--ipynb") fi black "${args[@]}" "${format_files[@]}" diff --git a/cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb b/cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb index 1928c32b8c9..105f8f22d52 100644 --- a/cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb +++ b/cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb @@ -20,8 +20,7 @@ "except ImportError:\n", " print(\"installing cirq-core[contrib]...\")\n", " !pip install --quiet 'cirq-core[contrib]'\n", - " print(\"installed cirq-core[contrib].\")\n", - " " + " print(\"installed cirq-core[contrib].\")" ] }, { @@ -100,7 +99,8 @@ "tn = qtn.TensorNetwork(tensors)\n", "print(qubit_frontier)\n", "from matplotlib import pyplot as plt\n", - "tn.graph(fix=fix, color=['Q0', 'Q1', 'Q2'], figsize=(8,8))" + "\n", + "tn.graph(fix=fix, color=['Q0', 'Q1', 'Q2'], figsize=(8, 8))" ] }, { @@ -207,7 +207,7 @@ "source": [ "tensors, qubit_frontier, fix = ccq.circuit_to_density_matrix_tensors(circuit=circuit, qubits=qubits)\n", "tn = qtn.TensorNetwork(tensors)\n", - "tn.graph(fix=fix, color=['Q0', 'Q1', 'Q2', 'kQ1'], figsize=(8,8))" + "tn.graph(fix=fix, color=['Q0', 'Q1', 'Q2', 'kQ1'], figsize=(8, 8))" ] }, { @@ -226,7 +226,7 @@ "source": [ "partial = 12\n", "tags_seq = [(f'i{i}b', f'i{i}f') for i in range(partial)]\n", - "tn.graph(fix=fix, color = [x for x, _ in tags_seq] + [y for _, y in tags_seq], figsize=(8, 8))" + "tn.graph(fix=fix, color=[x for x, _ in tags_seq] + [y for _, y in tags_seq], figsize=(8, 8))" ] }, { @@ -280,6 +280,7 @@ "source": [ "import timeit\n", "\n", + "\n", "def profile(n_qubits: int, n_moments: int):\n", " qubits = cirq.LineQubit.range(n_qubits)\n", " circuit = cirq.testing.random_circuit(qubits, n_moments=n_moments, op_density=0.8)\n", @@ -289,23 +290,15 @@ " n_moments = len(circuit)\n", " variables = {'circuit': circuit, 'qubits': qubits}\n", "\n", - " setup1 = [\n", - " 'import cirq',\n", - " 'import numpy as np',\n", - " ]\n", + " setup1 = ['import cirq', 'import numpy as np']\n", " n_call_cs, duration_cs = timeit.Timer(\n", - " stmt='cirq.final_density_matrix(circuit)',\n", - " setup='; '.join(setup1),\n", - " globals=variables).autorange()\n", + " stmt='cirq.final_density_matrix(circuit)', setup='; '.join(setup1), globals=variables\n", + " ).autorange()\n", "\n", - " setup2 = [\n", - " 'from cirq.contrib.quimb import tensor_density_matrix',\n", - " 'import numpy as np',\n", - " ]\n", + " setup2 = ['from cirq.contrib.quimb import tensor_density_matrix', 'import numpy as np']\n", " n_call_t, duration_t = timeit.Timer(\n", - " stmt='tensor_density_matrix(circuit, qubits)',\n", - " setup='; '.join(setup2),\n", - " globals=variables).autorange()\n", + " stmt='tensor_density_matrix(circuit, qubits)', setup='; '.join(setup2), globals=variables\n", + " ).autorange()\n", "\n", " return {\n", " 'n_qubits': n_qubits,\n", @@ -345,8 +338,10 @@ "def select(df, k, v):\n", " return df[df[k] == v].drop(k, axis=1)\n", "\n", + "\n", "pd.DataFrame.select = select\n", "\n", + "\n", "def plot1(df, labelfmt):\n", " for k in ['duration_cirq', 'duration_quimb']:\n", " plt.plot(df['n_moments'], df[k], '.-', label=labelfmt.format(k))\n", @@ -360,7 +355,8 @@ " plot1(df.select('n_qubits', 6), 'n = 6, {}')\n", " plt.xlabel('N Moments')\n", " plt.ylabel('Time / s')\n", - " \n", + "\n", + "\n", "plot(df)\n", "plt.tight_layout()" ] diff --git a/cirq-core/cirq/contrib/quimb/Contract-a-Grid-Circuit.ipynb b/cirq-core/cirq/contrib/quimb/Contract-a-Grid-Circuit.ipynb index 8cd078b8eee..0b8dd46132d 100644 --- a/cirq-core/cirq/contrib/quimb/Contract-a-Grid-Circuit.ipynb +++ b/cirq-core/cirq/contrib/quimb/Contract-a-Grid-Circuit.ipynb @@ -72,6 +72,7 @@ "from matplotlib import pyplot as plt\n", "\n", "import seaborn as sns\n", + "\n", "sns.set_style('ticks')\n", "\n", "plt.rc('axes', labelsize=16, titlesize=16)\n", @@ -114,13 +115,16 @@ "height = 4\n", "graph = nx.grid_2d_graph(width, height)\n", "rs = np.random.RandomState(52)\n", - "nx.set_edge_attributes(graph, name='weight',\n", - " values={e: np.round(rs.uniform(), 2) for e in graph.edges})\n", + "nx.set_edge_attributes(\n", + " graph, name='weight', values={e: np.round(rs.uniform(), 2) for e in graph.edges}\n", + ")\n", "\n", - "zz_inds = ((width//2, (height//2-1)), (width//2, (height//2)))\n", - "nx.draw_networkx(graph, \n", - " pos={n:n for n in graph.nodes},\n", - " node_color=[QRED if node in zz_inds else QBLUE for node in graph.nodes])" + "zz_inds = ((width // 2, (height // 2 - 1)), (width // 2, (height // 2)))\n", + "nx.draw_networkx(\n", + " graph,\n", + " pos={n: n for n in graph.nodes},\n", + " node_color=[QRED if node in zz_inds else QBLUE for node in graph.nodes],\n", + ")" ] }, { @@ -211,7 +215,7 @@ "metadata": {}, "outputs": [], "source": [ - "compressed_c= cirq.merge_k_qubit_unitaries(compressed_c, k=2)\n", + "compressed_c = cirq.merge_k_qubit_unitaries(compressed_c, k=2)\n", "compressed_c = cirq.merge_k_qubit_unitaries(compressed_c, k=1)\n", "\n", "compressed_c = cirq.drop_negligible_operations(compressed_c, atol=1e-6)\n", @@ -245,7 +249,7 @@ "metadata": {}, "outputs": [], "source": [ - "# simplification might eliminate qubits entirely for large graphs and \n", + "# simplification might eliminate qubits entirely for large graphs and\n", "# shallow `p`, so re-get the current qubits.\n", "qubits = sorted(tot_c.all_qubits())\n", "print(len(qubits))" @@ -266,13 +270,10 @@ "metadata": {}, "outputs": [], "source": [ - "tensors, qubit_frontier, fix = ccq.circuit_to_tensors(\n", - " circuit=tot_c, qubits=qubits)\n", + "tensors, qubit_frontier, fix = ccq.circuit_to_tensors(circuit=tot_c, qubits=qubits)\n", "end_bras = [\n", - " qtn.Tensor(\n", - " data=quimb.up().squeeze(),\n", - " inds=(f'i{qubit_frontier[q]}_q{q}',),\n", - " tags={'Q0', 'bra0'}) for q in qubits\n", + " qtn.Tensor(data=quimb.up().squeeze(), inds=(f'i{qubit_frontier[q]}_q{q}',), tags={'Q0', 'bra0'})\n", + " for q in qubits\n", "]\n", "\n", "tn = qtn.TensorNetwork(tensors + end_bras)\n", @@ -321,7 +322,7 @@ "metadata": {}, "outputs": [], "source": [ - "path_info.opt_cost / int(3e9) # assuming 3gflop, in seconds" + "path_info.opt_cost / int(3e9) # assuming 3gflop, in seconds" ] }, { @@ -330,7 +331,7 @@ "metadata": {}, "outputs": [], "source": [ - "path_info.largest_intermediate * 128 / 8 / 1024 / 1024 / 1024 # gb" + "path_info.largest_intermediate * 128 / 8 / 1024 / 1024 / 1024 # gb" ] }, { @@ -368,13 +369,16 @@ "height = 8\n", "graph = nx.grid_2d_graph(width, height)\n", "rs = np.random.RandomState(52)\n", - "nx.set_edge_attributes(graph, name='weight',\n", - " values={e: np.round(rs.uniform(), 2) for e in graph.edges})\n", + "nx.set_edge_attributes(\n", + " graph, name='weight', values={e: np.round(rs.uniform(), 2) for e in graph.edges}\n", + ")\n", "\n", - "zz_inds = ((width//2, (height//2-1)), (width//2, (height//2)))\n", - "nx.draw_networkx(graph, \n", - " pos={n:n for n in graph.nodes},\n", - " node_color=[QRED if node in zz_inds else QBLUE for node in graph.nodes])" + "zz_inds = ((width // 2, (height // 2 - 1)), (width // 2, (height // 2)))\n", + "nx.draw_networkx(\n", + " graph,\n", + " pos={n: n for n in graph.nodes},\n", + " node_color=[QRED if node in zz_inds else QBLUE for node in graph.nodes],\n", + ")" ] }, { diff --git a/cirq-core/cirq/contrib/svg/example.ipynb b/cirq-core/cirq/contrib/svg/example.ipynb index 86989a8cdce..05059709c37 100644 --- a/cirq-core/cirq/contrib/svg/example.ipynb +++ b/cirq-core/cirq/contrib/svg/example.ipynb @@ -33,14 +33,16 @@ "outputs": [], "source": [ "a, b, c = cirq.LineQubit.range(3)\n", - "SVGCircuit(cirq.Circuit(\n", - " cirq.CNOT(a, b),\n", - " cirq.CZ(b, c),\n", - " cirq.SWAP(a, c),\n", - " cirq.PhasedXPowGate(exponent=0.123, phase_exponent=0.456).on(c),\n", - " cirq.Z(a),\n", - " cirq.measure(a, b, c, key='z')\n", - "))" + "SVGCircuit(\n", + " cirq.Circuit(\n", + " cirq.CNOT(a, b),\n", + " cirq.CZ(b, c),\n", + " cirq.SWAP(a, c),\n", + " cirq.PhasedXPowGate(exponent=0.123, phase_exponent=0.456).on(c),\n", + " cirq.Z(a),\n", + " cirq.measure(a, b, c, key='z'),\n", + " )\n", + ")" ] }, { @@ -49,16 +51,18 @@ "metadata": {}, "outputs": [], "source": [ - "SVGCircuit(cirq.Circuit(\n", - " cirq.CNOT(cirq.GridQubit(0,0), cirq.GridQubit(0,1)),\n", - " cirq.CNOT(cirq.GridQubit(1,0), cirq.GridQubit(1,1)),\n", - " cirq.CNOT(cirq.GridQubit(0,0), cirq.GridQubit(1,0)),\n", - " cirq.CNOT(cirq.GridQubit(0,1), cirq.GridQubit(1,1)),\n", - " cirq.CNOT(cirq.GridQubit(0,0), cirq.GridQubit(0,1)),\n", - " cirq.CNOT(cirq.GridQubit(1,0), cirq.GridQubit(1,1)),\n", - " cirq.CNOT(cirq.GridQubit(0,0), cirq.GridQubit(1,0)),\n", - " cirq.CNOT(cirq.GridQubit(0,1), cirq.GridQubit(1,1)),\n", - "))" + "SVGCircuit(\n", + " cirq.Circuit(\n", + " cirq.CNOT(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)),\n", + " cirq.CNOT(cirq.GridQubit(1, 0), cirq.GridQubit(1, 1)),\n", + " cirq.CNOT(cirq.GridQubit(0, 0), cirq.GridQubit(1, 0)),\n", + " cirq.CNOT(cirq.GridQubit(0, 1), cirq.GridQubit(1, 1)),\n", + " cirq.CNOT(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)),\n", + " cirq.CNOT(cirq.GridQubit(1, 0), cirq.GridQubit(1, 1)),\n", + " cirq.CNOT(cirq.GridQubit(0, 0), cirq.GridQubit(1, 0)),\n", + " cirq.CNOT(cirq.GridQubit(0, 1), cirq.GridQubit(1, 1)),\n", + " )\n", + ")" ] } ], diff --git a/cirq-web/bloch_sphere_example.ipynb b/cirq-web/bloch_sphere_example.ipynb index 3f3105a2f2d..3838523cd88 100644 --- a/cirq-web/bloch_sphere_example.ipynb +++ b/cirq-web/bloch_sphere_example.ipynb @@ -15,7 +15,7 @@ "metadata": {}, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -84,20 +84,20 @@ "\n", "random_vector = cirq.testing.random_superposition(2)\n", "\n", - "r2o2 = math.sqrt(2)/2\n", - "i = (0 + 1j)\n", + "r2o2 = math.sqrt(2) / 2\n", + "i = 0 + 1j\n", "\n", - "zero_state = [1+0j, 0+0j]\n", - "one_state = [0+0j, 1+0j]\n", + "zero_state = [1 + 0j, 0 + 0j]\n", + "one_state = [0 + 0j, 1 + 0j]\n", "\n", - "plus_state = [r2o2+0j, r2o2+0j]\n", - "minus_state = [r2o2+0j, -r2o2+0j]\n", + "plus_state = [r2o2 + 0j, r2o2 + 0j]\n", + "minus_state = [r2o2 + 0j, -r2o2 + 0j]\n", "\n", - "i_plus_state = [(r2o2+0j), i*(r2o2+0j)]\n", - "i_minus_state = [(r2o2+0j), i*(-r2o2+0j)]\n", + "i_plus_state = [(r2o2 + 0j), i * (r2o2 + 0j)]\n", + "i_minus_state = [(r2o2 + 0j), i * (-r2o2 + 0j)]\n", "\n", "state_vector = cirq.to_valid_state_vector(plus_state)\n", - "sphere=BlochSphere(state_vector=state_vector)\n", + "sphere = BlochSphere(state_vector=state_vector)\n", "display(sphere)" ] }, diff --git a/cirq-web/circuit_example.ipynb b/cirq-web/circuit_example.ipynb index 22e66e01253..cfc4cc4c377 100644 --- a/cirq-web/circuit_example.ipynb +++ b/cirq-web/circuit_example.ipynb @@ -15,7 +15,7 @@ "metadata": {}, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -70,11 +70,13 @@ "outputs": [], "source": [ "import cirq\n", + "\n", "qubits = [cirq.GridQubit(x, y) for x in range(10) for y in range(10)]\n", "\n", "import cirq.testing\n", "from cirq.protocols import circuit_diagram_info\n", - "circuit = cirq.testing.random_circuit(cirq.GridQubit.square(10), n_moments=5, op_density=.7)" + "\n", + "circuit = cirq.testing.random_circuit(cirq.GridQubit.square(10), n_moments=5, op_density=0.7)" ] }, { @@ -89,22 +91,24 @@ "\"\"\"\n", "This cell builds a 3D circuit diagram using a big list of operations provided TS Circuit class.\n", "\"\"\"\n", + "\n", "import cirq_web\n", "from typing import Optional\n", "from cirq_web.circuits.symbols import SymbolInfo\n", "\n", + "\n", "class FunkyHadamard(cirq_web.circuits.symbols.SymbolResolver):\n", " def resolve(self, operation: cirq.Operation) -> Optional[SymbolInfo]:\n", " if isinstance(operation.gate, cirq.HPowGate):\n", " return SymbolInfo(['Hello!'], ['yellow'])\n", " else:\n", " return None\n", - " \n", - "resolvers = list(cirq_web.circuits.symbols.DEFAULT_SYMBOL_RESOLVERS) + [\n", - " FunkyHadamard()\n", - "]\n", + "\n", + "\n", + "resolvers = list(cirq_web.circuits.symbols.DEFAULT_SYMBOL_RESOLVERS) + [FunkyHadamard()]\n", "\n", "from cirq_web import Circuit3D\n", + "\n", "c3d = Circuit3D(circuit, resolvers, 2.5)\n", "display(c3d)" ] diff --git a/dev_tools/requirements/deps/format.txt b/dev_tools/requirements/deps/format.txt index dcbf51867fe..b0915259df5 100644 --- a/dev_tools/requirements/deps/format.txt +++ b/dev_tools/requirements/deps/format.txt @@ -1,2 +1,2 @@ -black==25.1.0 +black[jupyter]==25.1.0 isort[colors]~=6.0.1 diff --git a/docs/_template.ipynb b/docs/_template.ipynb index e09e779f666..1ceb5be288e 100644 --- a/docs/_template.ipynb +++ b/docs/_template.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", diff --git a/docs/build/custom_gates.ipynb b/docs/build/custom_gates.ipynb index 9ac1be522b0..350437b938a 100644 --- a/docs/build/custom_gates.ipynb +++ b/docs/build/custom_gates.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -77,7 +77,7 @@ " !pip install --quiet cirq\n", " print(\"installed cirq.\")\n", " import cirq\n", - " \n", + "\n", "import numpy as np" ] }, @@ -149,22 +149,22 @@ "outputs": [], "source": [ "\"\"\"Define a custom single-qubit gate.\"\"\"\n", + "\n", + "\n", "class MyGate(cirq.Gate):\n", " def __init__(self):\n", " super(MyGate, self)\n", - " \n", + "\n", " def _num_qubits_(self):\n", " return 1\n", - " \n", + "\n", " def _unitary_(self):\n", - " return np.array([\n", - " [1.0, 1.0],\n", - " [-1.0, 1.0]\n", - " ]) / np.sqrt(2)\n", - " \n", + " return np.array([[1.0, 1.0], [-1.0, 1.0]]) / np.sqrt(2)\n", + "\n", " def _circuit_diagram_info_(self, args):\n", " return \"G\"\n", "\n", + "\n", "my_gate = MyGate()" ] }, @@ -188,9 +188,8 @@ "outputs": [], "source": [ "\"\"\"Use the custom gate in a circuit.\"\"\"\n", - "circ = cirq.Circuit(\n", - " my_gate.on(cirq.LineQubit(0))\n", - ")\n", + "\n", + "circ = cirq.Circuit(my_gate.on(cirq.LineQubit(0)))\n", "\n", "print(\"Circuit with custom gates:\")\n", "print(circ)" @@ -216,6 +215,7 @@ "outputs": [], "source": [ "\"\"\"Simulate a circuit with a custom gate.\"\"\"\n", + "\n", "sim = cirq.Simulator()\n", "\n", "res = sim.simulate(circ)\n", @@ -231,24 +231,29 @@ "outputs": [], "source": [ "\"\"\"Define a custom two-qubit gate.\"\"\"\n", + "\n", + "\n", "class AnotherGate(cirq.Gate):\n", " def __init__(self):\n", " super(AnotherGate, self)\n", "\n", " def _num_qubits_(self):\n", " return 2\n", - " \n", + "\n", " def _unitary_(self):\n", - " return np.array([\n", - " [1.0, -1.0, 0.0, 0.0],\n", - " [0.0, 0.0, 1.0, 1.0],\n", - " [1.0, 1.0, 0.0, 0.0],\n", - " [0.0, 0.0, 1.0, -1.0]\n", - " ]) / np.sqrt(2)\n", - " \n", + " return np.array(\n", + " [\n", + " [1.0, -1.0, 0.0, 0.0],\n", + " [0.0, 0.0, 1.0, 1.0],\n", + " [1.0, 1.0, 0.0, 0.0],\n", + " [0.0, 0.0, 1.0, -1.0],\n", + " ]\n", + " ) / np.sqrt(2)\n", + "\n", " def _circuit_diagram_info_(self, args):\n", " return \"Top wire symbol\", \"Bottom wire symbol\"\n", "\n", + "\n", "this_gate = AnotherGate()" ] }, @@ -270,9 +275,8 @@ "outputs": [], "source": [ "\"\"\"Use the custom two-qubit gate in a circuit.\"\"\"\n", - "circ = cirq.Circuit(\n", - " this_gate.on(*cirq.LineQubit.range(2))\n", - ")\n", + "\n", + "circ = cirq.Circuit(this_gate.on(*cirq.LineQubit.range(2)))\n", "\n", "print(\"Circuit with custom two-qubit gate:\")\n", "print(circ)" @@ -318,20 +322,21 @@ "outputs": [], "source": [ "\"\"\"Define a custom gate with a parameter.\"\"\"\n", + "\n", + "\n", "class RotationGate(cirq.Gate):\n", " def __init__(self, theta):\n", " super(RotationGate, self)\n", " self.theta = theta\n", - " \n", + "\n", " def _num_qubits_(self):\n", " return 1\n", - " \n", + "\n", " def _unitary_(self):\n", - " return np.array([\n", - " [np.cos(self.theta), np.sin(self.theta)],\n", - " [np.sin(self.theta), -np.cos(self.theta)]\n", - " ]) / np.sqrt(2)\n", - " \n", + " return np.array(\n", + " [[np.cos(self.theta), np.sin(self.theta)], [np.sin(self.theta), -np.cos(self.theta)]]\n", + " ) / np.sqrt(2)\n", + "\n", " def _circuit_diagram_info_(self, args):\n", " return f\"R({self.theta})\"" ] @@ -354,9 +359,8 @@ "outputs": [], "source": [ "\"\"\"Use the custom gate in a circuit.\"\"\"\n", - "circ = cirq.Circuit(\n", - " RotationGate(theta=0.1).on(cirq.LineQubit(0))\n", - ")\n", + "\n", + "circ = cirq.Circuit(RotationGate(theta=0.1).on(cirq.LineQubit(0)))\n", "\n", "print(\"Circuit with a custom rotation gate:\")\n", "print(circ)" @@ -402,10 +406,11 @@ " yield cirq.CNOT(a, b)\n", " yield cirq.CNOT(b, a)\n", " yield cirq.CNOT(a, b)\n", - " \n", + "\n", " def _circuit_diagram_info_(self, args):\n", " return [\"CustomSWAP\"] * self.num_qubits()\n", "\n", + "\n", "my_swap = MySwap()" ] }, @@ -429,11 +434,9 @@ "outputs": [], "source": [ "\"\"\"Use the custom gate in a circuit.\"\"\"\n", + "\n", "qreg = cirq.LineQubit.range(2)\n", - "circ = cirq.Circuit(\n", - " cirq.X(qreg[0]),\n", - " my_swap.on(*qreg)\n", - ")\n", + "circ = cirq.Circuit(cirq.X(qreg[0]), my_swap.on(*qreg))\n", "\n", "print(\"Circuit:\")\n", "print(circ)" @@ -457,6 +460,7 @@ "outputs": [], "source": [ "\"\"\"Simulate the circuit.\"\"\"\n", + "\n", "sim.simulate(circ)" ] }, diff --git a/docs/build/gates.ipynb b/docs/build/gates.ipynb index b68924f4724..22309d3ad05 100644 --- a/docs/build/gates.ipynb +++ b/docs/build/gates.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -142,7 +142,7 @@ "print(cirq.CNOT(b, c))\n", "print(cirq.CNOT(a, b))\n", "print(cirq.H(a))\n", - "print(cirq.measure(a,b))" + "print(cirq.measure(a, b))" ] }, { diff --git a/docs/build/interop.ipynb b/docs/build/interop.ipynb index 5ce98de1e74..126480b6225 100644 --- a/docs/build/interop.ipynb +++ b/docs/build/interop.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -154,7 +154,7 @@ "import cirq\n", "\n", "# Example circuit\n", - "circuit = cirq.Circuit(cirq.Z(cirq.GridQubit(1,1)))\n", + "circuit = cirq.Circuit(cirq.Z(cirq.GridQubit(1, 1)))\n", "\n", "# Serialize to a JSON string\n", "json_string = cirq.to_json(circuit)\n", @@ -241,14 +241,17 @@ ], "source": [ "from cirq.contrib.qasm_import import circuit_from_qasm\n", - "circuit = circuit_from_qasm(\"\"\"\n", + "\n", + "circuit = circuit_from_qasm(\n", + " \"\"\"\n", " OPENQASM 2.0;\n", " include \"qelib1.inc\";\n", " qreg q[3];\n", " creg meas[3];\n", " h q;\n", " measure q -> meas;\n", - " \"\"\")\n", + " \"\"\"\n", + ")\n", "print(circuit)" ] }, @@ -280,7 +283,9 @@ ], "source": [ "from cirq.contrib.qasm_import import circuit_from_qasm\n", - "circuit = circuit_from_qasm(\"\"\"\n", + "\n", + "circuit = circuit_from_qasm(\n", + " \"\"\"\n", "OPENQASM 3.0;\n", "include \"stdgates.inc\";\n", "\n", @@ -290,7 +295,8 @@ "\n", "x q;\n", "m_mmm = measure q;\n", - "\"\"\")\n", + "\"\"\"\n", + ")\n", "print(circuit)" ] }, @@ -470,7 +476,7 @@ ], "source": [ "quirk_url = \"https://algassert.com/quirk#circuit=%7B%22cols%22:[[%22H%22,%22H%22],[%22%E2%80%A2%22,%22X%22],[%22H%22,%22H%22]]}\"\n", - "c= cirq.quirk_url_to_circuit(quirk_url)\n", + "c = cirq.quirk_url_to_circuit(quirk_url)\n", "\n", "print(c)" ] @@ -504,7 +510,7 @@ "source": [ "import json\n", "\n", - "quirk_str=\"\"\"{\n", + "quirk_str = \"\"\"{\n", " \"cols\": [\n", " [\n", " \"H\",\n", @@ -520,8 +526,8 @@ " ]\n", " ]\n", "}\"\"\"\n", - "quirk_json=json.loads(quirk_str)\n", - "c= cirq.quirk_json_to_circuit(quirk_json)\n", + "quirk_json = json.loads(quirk_str)\n", + "c = cirq.quirk_json_to_circuit(quirk_json)\n", "\n", "print(c)" ] diff --git a/docs/build/operators.ipynb b/docs/build/operators.ipynb index 4fcb77f7f74..84edad2e540 100644 --- a/docs/build/operators.ipynb +++ b/docs/build/operators.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -77,7 +77,7 @@ " !pip install --quiet cirq\n", " print(\"installed cirq.\")\n", " import cirq\n", - " \n", + "\n", "import numpy as np\n", "import sympy.parsing.sympy_parser as sympy_parser" ] @@ -558,11 +558,7 @@ }, "outputs": [], "source": [ - "circuit = cirq.Circuit(\n", - " cirq.H(qubit),\n", - " cirq.depolarize(p=0.01).on(qubit),\n", - " cirq.measure(qubit)\n", - ")\n", + "circuit = cirq.Circuit(cirq.H(qubit), cirq.depolarize(p=0.01).on(qubit), cirq.measure(qubit))\n", "print(circuit)" ] }, diff --git a/docs/build/protocols.ipynb b/docs/build/protocols.ipynb index 39eb3b32235..3ec743e02d2 100644 --- a/docs/build/protocols.ipynb +++ b/docs/build/protocols.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -76,7 +76,7 @@ " print(\"installing cirq...\")\n", " !pip install --quiet cirq\n", " print(\"installed cirq.\")\n", - " import cirq " + " import cirq" ] }, { @@ -110,7 +110,7 @@ "a, b = cirq.LineQubit.range(2)\n", "circuit = cirq.Circuit(cirq.X(a), cirq.Y(b))\n", "print(circuit)\n", - "print(\"circuit unitary:\\n\", cirq.unitary(circuit))\n" + "print(\"circuit unitary:\\n\", cirq.unitary(circuit))" ] }, { @@ -130,12 +130,11 @@ }, "outputs": [], "source": [ - "try: \n", - " print(cirq.unitary(a)) ## error!\n", - "except Exception as e: \n", + "try:\n", + " print(cirq.unitary(a)) ## error!\n", + "except Exception as e:\n", " print(\"As expected, a qubit does not have a unitary. The error: \")\n", - " print(e)\n", - " " + " print(e)" ] }, { @@ -254,7 +253,7 @@ }, "outputs": [], "source": [ - "probabilistic_x = cirq.X.with_probability(.3)\n", + "probabilistic_x = cirq.X.with_probability(0.3)\n", "\n", "for p, op in cirq.mixture(probabilistic_x):\n", " print(f\"probability: {p}\")\n", diff --git a/docs/build/qubits.ipynb b/docs/build/qubits.ipynb index 2ae100ff543..b46249cf138 100644 --- a/docs/build/qubits.ipynb +++ b/docs/build/qubits.ipynb @@ -9,7 +9,7 @@ }, "outputs": [], "source": [ - "#@title Copyright 2020 The Cirq Developers\n", + "# @title Copyright 2020 The Cirq Developers\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", diff --git a/docs/build/qudits.ipynb b/docs/build/qudits.ipynb index ea7c5e07b82..6aaec310550 100644 --- a/docs/build/qudits.ipynb +++ b/docs/build/qudits.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -105,14 +105,15 @@ "import cirq\n", "import numpy as np\n", "\n", + "\n", "class QutritPlusGate(cirq.Gate):\n", " \"\"\"A gate that adds one in the computational basis of a qutrit.\n", - " \n", + "\n", " This gate acts on three-level systems. In the computational basis of\n", " this system it enacts the transformation U|x〉 = |x + 1 mod 3〉, or\n", " in other words U|0〉 = |1〉, U|1〉 = |2〉, and U|2> = |0〉.\n", " \"\"\"\n", - " \n", + "\n", " def _qid_shape_(self):\n", " # By implementing this method this gate implements the\n", " # cirq.qid_shape protocol and will return the tuple (3,)\n", @@ -121,22 +122,19 @@ " return (3,)\n", "\n", " def _unitary_(self):\n", - " # Since the gate acts on three level systems it has a unitary \n", + " # Since the gate acts on three level systems it has a unitary\n", " # effect which is a three by three unitary matrix.\n", - " return np.array([[0, 0, 1],\n", - " [1, 0, 0],\n", - " [0, 1, 0]])\n", + " return np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]])\n", "\n", " def _circuit_diagram_info_(self, args):\n", " return '[+1]'\n", "\n", - "# Here we create a qutrit for the gate to act on. \n", + "\n", + "# Here we create a qutrit for the gate to act on.\n", "q0 = cirq.LineQid(0, dimension=3)\n", "\n", "# We can now enact the gate on this qutrit.\n", - "circuit = cirq.Circuit(\n", - " QutritPlusGate().on(q0)\n", - ")\n", + "circuit = cirq.Circuit(QutritPlusGate().on(q0))\n", "\n", "# When we print this out we see that the qutrit is labeled by its dimension.\n", "print(circuit)" @@ -285,12 +283,14 @@ "source": [ "# Create a circuit with three qutrit gates.\n", "q0, q1 = cirq.LineQid.range(2, dimension=3)\n", - "circuit = cirq.Circuit([\n", - " QutritPlusGate()(q0), \n", - " QutritPlusGate()(q1),\n", - " QutritPlusGate()(q1),\n", - " cirq.measure(q0, q1, key=\"x\")\n", - "])\n", + "circuit = cirq.Circuit(\n", + " [\n", + " QutritPlusGate()(q0),\n", + " QutritPlusGate()(q1),\n", + " QutritPlusGate()(q1),\n", + " cirq.measure(q0, q1, key=\"x\"),\n", + " ]\n", + ")\n", "\n", "# Sample from this circuit.\n", "result = cirq.sample(circuit, repetitions=3)\n", diff --git a/docs/experiments/fourier_checking.ipynb b/docs/experiments/fourier_checking.ipynb index a4d5ddf8494..442af57112f 100644 --- a/docs/experiments/fourier_checking.ipynb +++ b/docs/experiments/fourier_checking.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -213,7 +213,7 @@ "\n", " Creates a function 𝑓:{0,1}^𝑛 → {−1,1}\n", " where f(x)=c for all inputs.\n", - " \n", + "\n", " c is randomly chosen as either -1 or 1, but, once chosen,\n", " is constant for all values of x.\n", "\n", @@ -225,6 +225,7 @@ " f = np.ones(N) if flip else -1 * np.ones(N)\n", " return f\n", "\n", + "\n", "def choose_random_function() -> Tuple[str, np.ndarray]:\n", " \"\"\"Randomly choose a function from constant or balanced distributions.\n", "\n", @@ -239,7 +240,8 @@ " dist = \"C\"\n", " return dist, f\n", "\n", - "def randomized_alg(f:np.ndarray, sample_size:int) -> str:\n", + "\n", + "def randomized_alg(f: np.ndarray, sample_size: int) -> str:\n", " \"\"\"Samples the function f from `sample_size` different inputs.\n", "\n", " Queries the function f a number of times equal to sample_size.\n", @@ -270,7 +272,7 @@ }, "outputs": [], "source": [ - "N = 128 # size of the problem, n=7, N=2^7=128\n", + "N = 128 # size of the problem, n=7, N=2^7=128\n", "samples_size_per_function = 3\n", "number_of_functions_to_try = 1000\n", "\n", @@ -279,15 +281,11 @@ "for _ in range(number_of_functions_to_try):\n", " dist, f = choose_random_function()\n", " decision = randomized_alg(f, samples_size_per_function)\n", - " res=pd.concat([res, pd.DataFrame({\n", - " \"Distribution\": [dist],\n", - " \"Decision\":[decision],\n", - " \"Count\": [1]\n", - " })], ignore_index=True)\n", - "confusion = res.pivot_table(index=\"Distribution\",\n", - " columns=\"Decision\",\n", - " values=\"Count\",\n", - " aggfunc=\"sum\")\n", + " res = pd.concat(\n", + " [res, pd.DataFrame({\"Distribution\": [dist], \"Decision\": [decision], \"Count\": [1]})],\n", + " ignore_index=True,\n", + " )\n", + "confusion = res.pivot_table(index=\"Distribution\", columns=\"Decision\", values=\"Count\", aggfunc=\"sum\")\n", "# Translate the counts into percentage\n", "confusion.div(confusion.sum(axis=1), axis=0).apply(lambda x: round(x, 4) * 100)" ] @@ -322,15 +320,11 @@ " decision = randomized_alg(f, samples_size_per_function)\n", " constant_minus_blanaced_count += 1 if decision == \"constant\" else -1\n", " final_decision = \"constant\" if constant_minus_blanaced_count > 0 else \"balanced\"\n", - " res=pd.concat([res, pd.DataFrame({\n", - " \"Distribution\": [dist],\n", - " \"Decision\":[final_decision],\n", - " \"Count\": [1]\n", - " })], ignore_index=True)\n", - "confusion = res.pivot_table(index=\"Distribution\",\n", - " columns=\"Decision\",\n", - " values=\"Count\",\n", - " aggfunc=\"sum\")\n", + " res = pd.concat(\n", + " [res, pd.DataFrame({\"Distribution\": [dist], \"Decision\": [final_decision], \"Count\": [1]})],\n", + " ignore_index=True,\n", + " )\n", + "confusion = res.pivot_table(index=\"Distribution\", columns=\"Decision\", values=\"Count\", aggfunc=\"sum\")\n", "# Translate the counts into percentage\n", "confusion.div(confusion.sum(axis=1), axis=0).apply(lambda x: round(x, 4) * 100)" ] @@ -395,7 +389,7 @@ " v_hat = np.array([0.0] * N)\n", " for y in range(N):\n", " for x in range(N):\n", - " v_hat[y] += ((-1)**bitwise_dot(x, y)) * v[x]\n", + " v_hat[y] += ((-1) ** bitwise_dot(x, y)) * v[x]\n", " return v_hat / np.sqrt(N)" ] }, @@ -488,7 +482,7 @@ "outputs": [], "source": [ "# let's see some examples to gain some insights of forrelation\n", - "f = np.array([1, -1, 1, -1]) \n", + "f = np.array([1, -1, 1, -1])\n", "g = np.array([1, -1, 1, -1])\n", "print(f\"Correlation: {get_correlation(f,g)} Forrelation: {get_forrelation(f,g)}\")\n", "\n", @@ -558,7 +552,7 @@ }, "outputs": [], "source": [ - "def draw_two_distribution_from_f_set(N:int)-> Tuple[np.ndarray, np.ndarray, float, float]:\n", + "def draw_two_distribution_from_f_set(N: int) -> Tuple[np.ndarray, np.ndarray, float, float]:\n", " \"\"\"Samples two distributions from the 'F' set above.\n", "\n", " Uses a while loop to guarantee a forrelated pair \"as promised\".\n", @@ -568,7 +562,7 @@ " \"\"\"\n", " sgn = lambda x: 1 if x >= 0 else -1\n", " forrelation = 0.2\n", - " while (abs(forrelation)**2 < 0.05) and (abs(forrelation)**2 > 0.01):\n", + " while (abs(forrelation) ** 2 < 0.05) and (abs(forrelation) ** 2 > 0.01):\n", " vs = np.array([np.random.normal() for _ in range(N)])\n", " vs_hat = fourier_transform_over_z2(vs)\n", " fs = np.array([sgn(v) for v in vs])\n", @@ -578,17 +572,17 @@ " return fs, gs, forrelation, correlation\n", "\n", "\n", - "def draw_two_distribution_from_u_set(N:int)-> Tuple[np.ndarray, np.ndarray, float, float]:\n", + "def draw_two_distribution_from_u_set(N: int) -> Tuple[np.ndarray, np.ndarray, float, float]:\n", " \"\"\"Samples two distributions from the 'U' set above.\n", "\n", " Uses a while loop to guarantee a forrelated pair \"as promised\".\n", - " \n", + "\n", " Returns:\n", " A tuple that contains the two distributions, and the correlation/forrelation.\n", " \"\"\"\n", " sgn = lambda x: 1 if x >= 0 else -1\n", " forrelation = 0.2\n", - " while (abs(forrelation)**2 < 0.05) and (abs(forrelation)**2 > 0.01):\n", + " while (abs(forrelation) ** 2 < 0.05) and (abs(forrelation) ** 2 > 0.01):\n", " vs = np.array([np.random.normal() for _ in range(N)])\n", " fs = np.array([sgn(v) for v in vs])\n", " us = np.array([np.random.normal() for _ in range(N)])\n", @@ -607,7 +601,7 @@ "outputs": [], "source": [ "n = 6\n", - "N = 2 ** n\n", + "N = 2**n\n", "\n", "fs, gs, forrelation, correlation = draw_two_distribution_from_f_set(N)\n", "print('Correlation and forrelation from F set')\n", @@ -629,7 +623,7 @@ "plt.figure(figsize=(15, 5))\n", "plt.stem(fs)\n", "plt.stem(gs, linefmt='--r', markerfmt='ro')\n", - "_ = plt.title(f\"Two distributions from U set\")\n" + "_ = plt.title(f\"Two distributions from U set\")" ] }, { @@ -781,13 +775,15 @@ }, "outputs": [], "source": [ - "assert np.isclose(circuit.final_state_vector(ignore_terminal_measurements=True, dtype=np.complex64)[0], forrelation)\n", + "assert np.isclose(\n", + " circuit.final_state_vector(ignore_terminal_measurements=True, dtype=np.complex64)[0],\n", + " forrelation,\n", + ")\n", "\n", "s = cirq.Simulator()\n", "for step in s.simulate_moment_steps(circuit):\n", " print(step.dirac_notation())\n", - " print(\"|0> state probability to observe: \",\n", - " np.abs(step.state_vector(copy=True)[0])**2)" + " print(\"|0> state probability to observe: \", np.abs(step.state_vector(copy=True)[0]) ** 2)" ] }, { @@ -799,8 +795,7 @@ "outputs": [], "source": [ "final_state = circuit.final_state_vector(ignore_terminal_measurements=True, dtype=np.complex64)\n", - "plt.fill_between(np.arange(len(final_state)),\n", - " np.abs(final_state)**2)\n", + "plt.fill_between(np.arange(len(final_state)), np.abs(final_state) ** 2)\n", "plt.xlabel(\"State of qubits\")\n", "plt.ylabel(\"Probability\")\n", "plt.show()" @@ -828,8 +823,8 @@ "qubits_name = ','.join(str(q) for q in qubits)\n", "times_zero_was_measured = len(obs.data[obs.data[qubits_name] == 0])\n", "print(\n", - " f\"times zero state was measured from {repetitions} measurements:\" +\n", - " f\"{times_zero_was_measured} - {float(times_zero_was_measured/repetitions)*100}%\"\n", + " f\"times zero state was measured from {repetitions} measurements:\"\n", + " + f\"{times_zero_was_measured} - {float(times_zero_was_measured/repetitions)*100}%\"\n", ")\n", "if float(times_zero_was_measured / repetitions) > 0.05:\n", " print(\"fs and gs is forrelated!\")" @@ -867,11 +862,10 @@ " obs = s.run(circuit, repetitions=repetitions)\n", " times_zero_was_measured = len(obs.data[obs.data[qubits_name] == 0])\n", " decision = \"accept\" if times_zero_was_measured / repetitions > 0.05 else \"reject\"\n", - " res=pd.concat([res, pd.DataFrame({\n", - " \"Source\": [source],\n", - " \"Decision\":[decision],\n", - " \"Count\": [1]\n", - " })], ignore_index=True)\n", + " res = pd.concat(\n", + " [res, pd.DataFrame({\"Source\": [source], \"Decision\": [decision], \"Count\": [1]})],\n", + " ignore_index=True,\n", + " )\n", "confusion = res.pivot_table(index=\"Source\", columns=\"Decision\", values=\"Count\", aggfunc=\"sum\")\n", "# Translate the counts into percentage\n", "confusion.div(confusion.sum(axis=1), axis=0).apply(lambda x: round(x, 4) * 100)" diff --git a/docs/experiments/hidden_linear_function.ipynb b/docs/experiments/hidden_linear_function.ipynb index 2893028e352..1715bfd9115 100644 --- a/docs/experiments/hidden_linear_function.ipynb +++ b/docs/experiments/hidden_linear_function.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -198,52 +198,53 @@ "source": [ "class HiddenLinearFunctionProblem:\n", " \"\"\"Instance of Hidden Linear Function problem.\n", - " \n", + "\n", " The problem is defined by matrix A and vector b, which are\n", " the coefficients of quadratic form, in which linear function\n", " is \"hidden\".\n", " \"\"\"\n", + "\n", " def __init__(self, A, b):\n", " self.n = A.shape[0]\n", " assert A.shape == (self.n, self.n)\n", - " assert b.shape == (self.n, )\n", + " assert b.shape == (self.n,)\n", " for i in range(self.n):\n", - " for j in range(i+1):\n", + " for j in range(i + 1):\n", " assert A[i][j] == 0, 'A[i][j] can be 1 only if i>i) % 2 for i in range(self.n)]) for m in range(2**self.n)]\n", + " all_vectors = [np.array([(m >> i) % 2 for i in range(self.n)]) for m in range(2**self.n)]\n", "\n", " def vector_in_L(x):\n", " for y in all_vectors:\n", - " if self.q( (x + y)%2 ) != (self.q(x) + self.q(y))%4:\n", + " if self.q((x + y) % 2) != (self.q(x) + self.q(y)) % 4:\n", " return False\n", " return True\n", "\n", " # L is subspace to which we restrict domain of quadratic form.\n", " # Corresponds to `L_q` in the problem definition.\n", " self.L = [x for x in all_vectors if vector_in_L(x)]\n", - " \n", + "\n", " # All vectors `z` which are solutions to the problem.\n", " self.all_zs = [z for z in all_vectors if self.is_z(z)]\n", - " \n", + "\n", " def is_z(self, z):\n", " \"\"\"Checks by definition, whether given vector `z` is solution to this problem.\"\"\"\n", - " assert z.shape == (self.n, )\n", + " assert z.shape == (self.n,)\n", " assert self.L is not None\n", " for x in self.L:\n", " if self.q(x) != 2 * ((z @ x) % 2):\n", @@ -272,26 +273,27 @@ "source": [ "def random_problem(n, seed=None):\n", " \"\"\"Generates instance of the problem with given `n`.\n", - " \n", + "\n", " Args:\n", " n: dimension of the problem.\n", " \"\"\"\n", " if seed is not None:\n", - " np.random.seed(seed) \n", - " A = np.random.randint(0, 2, size=(n,n))\n", + " np.random.seed(seed)\n", + " A = np.random.randint(0, 2, size=(n, n))\n", " for i in range(n):\n", - " for j in range(i+1):\n", + " for j in range(i + 1):\n", " A[i][j] = 0\n", " b = np.random.randint(0, 2, size=n)\n", " problem = HiddenLinearFunctionProblem(A, b)\n", " return problem\n", - " \n", + "\n", + "\n", "def find_interesting_problem(n, min_L_size):\n", " \"\"\"Generates \"interesting\" instance of the problem.\n", - " \n", - " Returns instance of problem with given `n`, such that size of \n", + "\n", + " Returns instance of problem with given `n`, such that size of\n", " subspace `L_q` is at least `min_L_size`.\n", - " \n", + "\n", " Args:\n", " n: dimension of the problem.\n", " min_L_size: minimal cardinality of subspace L.\n", @@ -303,6 +305,7 @@ " return problem\n", " return None\n", "\n", + "\n", "problem = find_interesting_problem(10, 4)\n", "print(\"Size of subspace L: %d\" % len(problem.L))\n", "print(\"Number of solutions: %d\" % len(problem.all_zs))" @@ -325,16 +328,20 @@ }, "outputs": [], "source": [ - "A = np.array([[0, 1, 1, 0, 0, 1, 0, 0, 1, 1],\n", - " [0, 0, 0, 1, 1, 1, 1, 1, 1, 1],\n", - " [0, 0, 0, 0, 0, 0, 1, 1, 0, 1],\n", - " [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n", - " [0, 0, 0, 0, 0, 1, 0, 0, 0, 1],\n", - " [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],\n", - " [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],\n", - " [0, 0, 0, 0, 0, 0, 0, 0, 1, 1],\n", - " [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n", - " [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])\n", + "A = np.array(\n", + " [\n", + " [0, 1, 1, 0, 0, 1, 0, 0, 1, 1],\n", + " [0, 0, 0, 1, 1, 1, 1, 1, 1, 1],\n", + " [0, 0, 0, 0, 0, 0, 1, 1, 0, 1],\n", + " [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n", + " [0, 0, 0, 0, 0, 1, 0, 0, 0, 1],\n", + " [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],\n", + " [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],\n", + " [0, 0, 0, 0, 0, 0, 0, 0, 1, 1],\n", + " [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n", + " [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n", + " ]\n", + ")\n", "b = np.array([0, 0, 0, 0, 1, 1, 1, 0, 0, 1])\n", "problem_10_64 = HiddenLinearFunctionProblem(A, b)\n", "problem_10_64.bruteforce_solve()\n", @@ -386,12 +393,12 @@ "source": [ "def edge_coloring(A):\n", " \"\"\"Solves edge coloring problem.\n", - " \n", + "\n", " Args:\n", " A: adjacency matrix of a graph.\n", - " \n", - " Returns list of lists of edges, such as edges in each list \n", - " do not have common vertex. \n", + "\n", + " Returns list of lists of edges, such as edges in each list\n", + " do not have common vertex.\n", " Tries to minimize length of this list.\n", " \"\"\"\n", " A = np.copy(A)\n", @@ -420,48 +427,50 @@ "source": [ "def generate_circuit_for_problem(problem):\n", " \"\"\"Generates `cirq.Circuit` which solves instance of Hidden Linear Function problem.\"\"\"\n", - " \n", + "\n", " qubits = cirq.LineQubit.range(problem.n)\n", " circuit = cirq.Circuit()\n", - " \n", + "\n", " # Hadamard gates at the beginning (creating equal superposition of all states).\n", " circuit += cirq.Moment([cirq.H(q) for q in qubits])\n", - " \n", + "\n", " # Controlled-Z gates encoding the matrix A.\n", " for layer in edge_coloring(problem.A):\n", " for i, j in layer:\n", " circuit += cirq.CZ(qubits[i], qubits[j])\n", - " \n", + "\n", " # S gates encoding the vector b.\n", " circuit += cirq.Moment([cirq.S.on(qubits[i]) for i in range(problem.n) if problem.b[i] == 1])\n", - " \n", + "\n", " # Hadamard gates at the end.\n", " circuit += cirq.Moment([cirq.H(q) for q in qubits])\n", - " \n", + "\n", " # Measurements.\n", - " circuit += cirq.Moment([cirq.measure(qubits[i], key=str(i)) for i in range(problem.n)]) \n", - " \n", + " circuit += cirq.Moment([cirq.measure(qubits[i], key=str(i)) for i in range(problem.n)])\n", + "\n", " return circuit\n", "\n", + "\n", "def solve_problem(problem, print_circuit=False):\n", " \"\"\"Solves instance of Hidden Linear Function problem.\n", - " \n", + "\n", " Builds quantum circuit for given problem and simulates\n", - " it with the Clifford simulator. \n", - " \n", + " it with the Clifford simulator.\n", + "\n", " Returns measurement result as binary vector, which is\n", " guaranteed to be a solution to given problem.\n", " \"\"\"\n", " circuit = generate_circuit_for_problem(problem)\n", - " \n", + "\n", " if print_circuit:\n", " print(circuit)\n", - " \n", + "\n", " sim = cirq.CliffordSimulator()\n", " result = sim.simulate(circuit)\n", " z = np.array([result.measurements[str(i)][0] for i in range(problem.n)])\n", " return z\n", "\n", + "\n", "solve_problem(problem_10_64, print_circuit=True)" ] }, @@ -490,7 +499,8 @@ " for _ in range(tries):\n", " z = solve_problem(problem)\n", " assert problem.is_z(z)\n", - " \n", + "\n", + "\n", "test_problem(problem_10_64)\n", "print('OK')" ] diff --git a/docs/experiments/quantum_walks.ipynb b/docs/experiments/quantum_walks.ipynb index 8ed2d0f4b0a..003d939178f 100644 --- a/docs/experiments/quantum_walks.ipynb +++ b/docs/experiments/quantum_walks.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -189,24 +189,26 @@ "source": [ "# Defines all of the necessary parameters\n", "\n", - "N = 50 # Defines the total number of steps our walker will take\n", + "N = 50 # Defines the total number of steps our walker will take\n", "pr = 0.5 # Defines the probability of our walker stepping to the right\n", - "i = 0 # Defines the initial position of our walker\n", + "i = 0 # Defines the initial position of our walker\n", + "\n", "\n", "def random_walk(pr, N, i):\n", - " \n", + "\n", " position = i\n", - " \n", + "\n", " # Repeatedly queries our random variable and moves our walker for the specified number of steps\n", - " \n", + "\n", " for j in range(N):\n", - " \n", - " coin_flip = list(np.random.choice(2, 1, p=[1-pr, pr])) # Flips our weighted coin\n", - " position += 2*coin_flip[0]-1 # Moves our walker according to the coin flip \n", - " \n", + "\n", + " coin_flip = list(np.random.choice(2, 1, p=[1 - pr, pr])) # Flips our weighted coin\n", + " position += 2 * coin_flip[0] - 1 # Moves our walker according to the coin flip\n", + "\n", " return position\n", - " \n", - "print(\"The walker is located at: x = {var}\".format(var = random_walk(pr, N, i)))" + "\n", + "\n", + "print(\"The walker is located at: x = {var}\".format(var=random_walk(pr, N, i)))" ] }, { @@ -227,18 +229,19 @@ "outputs": [], "source": [ "def dist(runs, N):\n", - " \n", - " positions = range(-1*N, N+1)\n", - " instances = [0 for i in range(-1*N, N+1)]\n", - " \n", + "\n", + " positions = range(-1 * N, N + 1)\n", + " instances = [0 for i in range(-1 * N, N + 1)]\n", + "\n", " for k in range(runs):\n", "\n", " result = random_walk(pr, N, i)\n", " instances[positions.index(result)] += 1\n", "\n", - " plt.bar(positions, [n/runs for n in instances])\n", + " plt.bar(positions, [n / runs for n in instances])\n", " plt.show()\n", - " \n", + "\n", + "\n", "dist(10000, N)" ] }, @@ -260,17 +263,18 @@ "outputs": [], "source": [ "def height_calculate(x, N, pr):\n", - " \n", - " a = (N + x)/2\n", - " b = (N - x)/2\n", - " \n", - " if (x%2 == 0):\n", - " var = scipy.special.binom(N, a)*(pr**a)*((1-pr)**b)\n", + "\n", + " a = (N + x) / 2\n", + " b = (N - x) / 2\n", + "\n", + " if x % 2 == 0:\n", + " var = scipy.special.binom(N, a) * (pr**a) * ((1 - pr) ** b)\n", " else:\n", " var = 0\n", " return var\n", "\n", - "positions = range(-1*N, N+1)\n", + "\n", + "positions = range(-1 * N, N + 1)\n", "heights = [height_calculate(x, N, pr) for x in positions]\n", "plt.bar(positions, heights)\n", "plt.show()" @@ -563,21 +567,21 @@ " yield cirq.X.on(cirq.GridQubit(0, number_qubits))\n", "\n", " for i in range(number_qubits, 0, -1):\n", - " \n", - " controls = [cirq.GridQubit(0, v) for v in range(number_qubits, i-1, -1)]\n", - " yield cirq.X.on(cirq.GridQubit(0, i-1)).controlled_by(*controls)\n", - " if (i > 1):\n", - " yield cirq.X.on(cirq.GridQubit(0, i-1))\n", + "\n", + " controls = [cirq.GridQubit(0, v) for v in range(number_qubits, i - 1, -1)]\n", + " yield cirq.X.on(cirq.GridQubit(0, i - 1)).controlled_by(*controls)\n", + " if i > 1:\n", + " yield cirq.X.on(cirq.GridQubit(0, i - 1))\n", "\n", " yield cirq.X.on(cirq.GridQubit(0, number_qubits))\n", "\n", " # Implement the Subtraction Operator\n", "\n", - " for i in range(1, number_qubits+1):\n", + " for i in range(1, number_qubits + 1):\n", "\n", - " controls = [cirq.GridQubit(0, v) for v in range(number_qubits, i-1, -1)]\n", - " yield cirq.X.on(cirq.GridQubit(0, i-1)).controlled_by(*controls)\n", - " if (i < number_qubits):\n", + " controls = [cirq.GridQubit(0, v) for v in range(number_qubits, i - 1, -1)]\n", + " yield cirq.X.on(cirq.GridQubit(0, i - 1)).controlled_by(*controls)\n", + " if i < number_qubits:\n", " yield cirq.X.on(cirq.GridQubit(0, i))" ] }, @@ -606,6 +610,7 @@ "iterator = 30\n", "sample_number = 5000\n", "\n", + "\n", "def generate_walk(number_qubits, iterator, sample_number):\n", "\n", " circuit = cirq.Circuit()\n", @@ -621,6 +626,7 @@ "\n", " return final\n", "\n", + "\n", "final = generate_walk(number_qubits, iterator, sample_number)\n", "print(final)" ] @@ -653,7 +659,7 @@ " x_arr_final = []\n", " y_arr_final = []\n", "\n", - " while (len(x_arr) > 0):\n", + " while len(x_arr) > 0:\n", "\n", " x_arr_final.append(min(x_arr))\n", " y_arr_final.append(y_arr[x_arr.index(min(x_arr))])\n", @@ -665,6 +671,7 @@ " plt.scatter(x_arr_final, y_arr_final)\n", " plt.show()\n", "\n", + "\n", "graph(final)" ] }, @@ -694,6 +701,7 @@ "\n", " yield cirq.X.on(cirq.GridQubit(0, 1))\n", "\n", + "\n", "final = generate_walk(number_qubits, iterator, sample_number)\n", "graph(final)" ] @@ -727,10 +735,11 @@ "def initial_state():\n", "\n", " yield cirq.X.on(cirq.GridQubit(0, 1))\n", - " \n", + "\n", " yield cirq.H.on(cirq.GridQubit(0, number_qubits))\n", " yield cirq.S.on(cirq.GridQubit(0, number_qubits))\n", "\n", + "\n", "final = generate_walk(number_qubits, iterator, sample_number)\n", "graph(final)" ] diff --git a/docs/experiments/shor.ipynb b/docs/experiments/shor.ipynb index 34ade59c7b4..7d425e62238 100644 --- a/docs/experiments/shor.ipynb +++ b/docs/experiments/shor.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -80,6 +80,7 @@ "outputs": [], "source": [ "\"\"\"Install Cirq.\"\"\"\n", + "\n", "try:\n", " import cirq\n", "except ImportError:\n", @@ -97,6 +98,7 @@ "outputs": [], "source": [ "\"\"\"Imports for the notebook.\"\"\"\n", + "\n", "import fractions\n", "import math\n", "import random\n", @@ -165,9 +167,11 @@ "outputs": [], "source": [ "\"\"\"Function to compute the elements of Z_n.\"\"\"\n", + "\n", + "\n", "def multiplicative_group(n: int) -> List[int]:\n", " \"\"\"Returns the multiplicative group modulo n.\n", - " \n", + "\n", " Args:\n", " n: Modulus of the multiplicative group.\n", " \"\"\"\n", @@ -197,6 +201,7 @@ "outputs": [], "source": [ "\"\"\"Example of a multiplicative group.\"\"\"\n", + "\n", "n = 15\n", "print(f\"The multiplicative group modulo n = {n} is:\")\n", "print(multiplicative_group(n))" @@ -245,6 +250,8 @@ "outputs": [], "source": [ "\"\"\"Function for classically computing the order of an element of Z_n.\"\"\"\n", + "\n", + "\n", "def classical_order_finder(x: int, n: int) -> Optional[int]:\n", " \"\"\"Computes smallest positive r such that x**r mod n == 1.\n", "\n", @@ -265,7 +272,7 @@ " # Make sure x is both valid and in Z_n.\n", " if x < 2 or x >= n or math.gcd(x, n) > 1:\n", " raise ValueError(f\"Invalid x={x} for modulus n={n}.\")\n", - " \n", + "\n", " # Determine the order.\n", " r, y = 1, x\n", " while y != 1:\n", @@ -292,6 +299,7 @@ "outputs": [], "source": [ "\"\"\"Example of (classically) computing the order of an element.\"\"\"\n", + "\n", "n = 15 # The multiplicative group is [1, 2, 4, 7, 8, 11, 13, 14].\n", "x = 8\n", "r = classical_order_finder(x, n)\n", @@ -364,12 +372,13 @@ "outputs": [], "source": [ "\"\"\"Example of defining an arithmetic (quantum) gate in Cirq.\"\"\"\n", + "\n", + "\n", "class Adder(cirq.ArithmeticGate):\n", " \"\"\"Quantum addition.\"\"\"\n", + "\n", " def __init__(\n", - " self,\n", - " target_register: [int, Sequence[int]],\n", - " input_register: Union[int, Sequence[int]],\n", + " self, target_register: [int, Sequence[int]], input_register: Union[int, Sequence[int]]\n", " ):\n", " self.target_register = target_register\n", " self.input_register = input_register\n", @@ -377,16 +386,14 @@ " def registers(self) -> Sequence[Union[int, Sequence[int]]]:\n", " return self.target_register, self.input_register\n", "\n", - " def with_registers(\n", - " self, *new_registers: Union[int, Sequence[int]]\n", - " ) -> 'Adder':\n", + " def with_registers(self, *new_registers: Union[int, Sequence[int]]) -> 'Adder':\n", " return Adder(*new_registers)\n", "\n", " def apply(self, *register_values: int) -> Union[int, Iterable[int]]:\n", - " return sum(register_values)", + " return sum(register_values)\n", "\n", " def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs):\n", - " wire_symbols = [' + ' for _ in range(len(self.input_register)+len(self.target_register))]\n", + " wire_symbols = [' + ' for _ in range(len(self.input_register) + len(self.target_register))]\n", " return cirq.CircuitDiagramInfo(wire_symbols=tuple(wire_symbols))" ] }, @@ -410,6 +417,7 @@ "outputs": [], "source": [ "\"\"\"Example of using an Adder in a circuit.\"\"\"\n", + "\n", "# Two qubit registers.\n", "qreg1 = cirq.LineQubit.range(2)\n", "qreg2 = cirq.LineQubit.range(2, 4)\n", @@ -423,7 +431,7 @@ " cirq.X.on(qreg2[1]),\n", " adder.on(*qreg1, *qreg2),\n", " cirq.measure_each(*qreg1),\n", - " cirq.measure_each(*qreg2)\n", + " cirq.measure_each(*qreg2),\n", ")\n", "\n", "# Display it.\n", @@ -462,10 +470,8 @@ "outputs": [], "source": [ "\"\"\"Example of the unitary of an Adder gate.\"\"\"\n", - "cirq.unitary(\n", - " Adder(target_register=[2, 2],\n", - " input_register=1)\n", - ").real" + "\n", + "cirq.unitary(Adder(target_register=[2, 2], input_register=1)).real" ] }, { @@ -504,6 +510,8 @@ "outputs": [], "source": [ "\"\"\"Defines the modular exponential gate used in Shor's algorithm.\"\"\"\n", + "\n", + "\n", "class ModularExp(cirq.ArithmeticGate):\n", " \"\"\"Quantum modular exponentiation.\n", "\n", @@ -524,17 +532,13 @@ " U|y⟩ = |y * x mod n⟩ 0 <= y < n\n", " U|y⟩ = |y⟩ n <= y\n", " \"\"\"\n", + "\n", " def __init__(\n", - " self,\n", - " target: Sequence[int],\n", - " exponent: Union[int, Sequence[int]],\n", - " base: int,\n", - " modulus: int\n", + " self, target: Sequence[int], exponent: Union[int, Sequence[int]], base: int, modulus: int\n", " ) -> None:\n", " if len(target) < modulus.bit_length():\n", " raise ValueError(\n", - " f'Register with {len(target)} qubits is too small for modulus'\n", - " f' {modulus}'\n", + " f'Register with {len(target)} qubits is too small for modulus' f' {modulus}'\n", " )\n", " self.target = target\n", " self.exponent = exponent\n", @@ -544,9 +548,7 @@ " def registers(self) -> Sequence[Union[int, Sequence[int]]]:\n", " return self.target, self.exponent, self.base, self.modulus\n", "\n", - " def with_registers(\n", - " self, *new_registers: Union[int, Sequence[int]]\n", - " ) -> 'ModularExp':\n", + " def with_registers(self, *new_registers: Union[int, Sequence[int]]) -> 'ModularExp':\n", " \"\"\"Returns a new ModularExp object with new registers.\"\"\"\n", " if len(new_registers) != 4:\n", " raise ValueError(\n", @@ -555,17 +557,11 @@ " )\n", " target, exponent, base, modulus = new_registers\n", " if not isinstance(target, Sequence):\n", - " raise ValueError(\n", - " f'Target must be a qubit register, got {type(target)}'\n", - " )\n", + " raise ValueError(f'Target must be a qubit register, got {type(target)}')\n", " if not isinstance(base, int):\n", - " raise ValueError(\n", - " f'Base must be a classical constant, got {type(base)}'\n", - " )\n", + " raise ValueError(f'Base must be a classical constant, got {type(base)}')\n", " if not isinstance(modulus, int):\n", - " raise ValueError(\n", - " f'Modulus must be a classical constant, got {type(modulus)}'\n", - " )\n", + " raise ValueError(f'Modulus must be a classical constant, got {type(modulus)}')\n", " return ModularExp(target, exponent, base, modulus)\n", "\n", " def apply(self, *register_values: int) -> int:\n", @@ -587,9 +583,7 @@ " return target\n", " return (target * base**exponent) % modulus\n", "\n", - " def _circuit_diagram_info_(\n", - " self, args: cirq.CircuitDiagramInfoArgs\n", - " ) -> cirq.CircuitDiagramInfo:\n", + " def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq.CircuitDiagramInfo:\n", " \"\"\"Returns a 'CircuitDiagramInfo' object for printing circuits.\n", "\n", " This function just returns information on how to print this operation\n", @@ -635,6 +629,7 @@ "\"\"\"Create the target and exponent registers for phase estimation,\n", "and see the number of qubits needed for Shor's algorithm.\n", "\"\"\"\n", + "\n", "n = 15\n", "L = n.bit_length()\n", "\n", @@ -666,6 +661,7 @@ "outputs": [], "source": [ "\"\"\"See (part of) the unitary for a modular exponential gate.\"\"\"\n", + "\n", "# Pick some element of the multiplicative group modulo n.\n", "x = 5\n", "\n", @@ -700,6 +696,8 @@ "outputs": [], "source": [ "\"\"\"Function to make the quantum circuit for order finding.\"\"\"\n", + "\n", + "\n", "def make_order_finding_circuit(x: int, n: int) -> cirq.Circuit:\n", " \"\"\"Returns quantum circuit which computes the order of x modulo n.\n", "\n", @@ -750,6 +748,7 @@ "outputs": [], "source": [ "\"\"\"Example of the quantum circuit for period finding.\"\"\"\n", + "\n", "n = 15\n", "x = 7\n", "circuit = make_order_finding_circuit(x, n)\n", @@ -783,6 +782,7 @@ "outputs": [], "source": [ "\"\"\"Measuring Shor's period finding circuit.\"\"\"\n", + "\n", "circuit = make_order_finding_circuit(x=5, n=6)\n", "res = cirq.sample(circuit, repetitions=8)\n", "\n", @@ -836,7 +836,7 @@ "\n", " U|y⟩ = |xy mod n⟩ 0 <= y < n\n", " U|y⟩ = |y⟩ n <= y\n", - " \n", + "\n", " then computes r (by continued fractions) if possible, and returns it.\n", "\n", " Args:\n", @@ -853,11 +853,11 @@ "\n", " # Run the continued fractions algorithm to determine f = s / r.\n", " f = fractions.Fraction.from_float(eigenphase).limit_denominator(n)\n", - " \n", + "\n", " # If the numerator is zero, the order finder failed.\n", " if f.numerator == 0:\n", " return None\n", - " \n", + "\n", " # Else, return the denominator if it is valid.\n", " r = f.denominator\n", " if x**r % n != 1:\n", @@ -883,6 +883,7 @@ "outputs": [], "source": [ "\"\"\"Example of the classical post-processing.\"\"\"\n", + "\n", "# Set n and x here\n", "n = 6\n", "x = 5\n", @@ -938,7 +939,7 @@ "source": [ "def quantum_order_finder(x: int, n: int) -> Optional[int]:\n", " \"\"\"Computes smallest positive r such that x**r mod n == 1.\n", - " \n", + "\n", " Args:\n", " x: integer whose order is to be computed, must be greater than one\n", " and belong to the multiplicative group of integers modulo n (which\n", @@ -952,10 +953,10 @@ "\n", " # Create the order finding circuit.\n", " circuit = make_order_finding_circuit(x, n)\n", - " \n", + "\n", " # Sample from the order finding circuit.\n", " measurement = cirq.sample(circuit)\n", - " \n", + "\n", " # Return the processed measurement result.\n", " return process_measurement(measurement, x, n)" ] @@ -1004,6 +1005,8 @@ "outputs": [], "source": [ "\"\"\"Functions for factoring from start to finish.\"\"\"\n", + "\n", + "\n", "def find_factor_of_prime_power(n: int) -> Optional[int]:\n", " \"\"\"Returns non-trivial factor of n if n is a prime power, else None.\"\"\"\n", " for k in range(2, math.floor(math.log2(n)) + 1):\n", @@ -1020,7 +1023,7 @@ "def find_factor(\n", " n: int,\n", " order_finder: Callable[[int, int], Optional[int]] = quantum_order_finder,\n", - " max_attempts: int = 30\n", + " max_attempts: int = 30,\n", ") -> Optional[int]:\n", " \"\"\"Returns a non-trivial factor of composite integer n.\n", "\n", @@ -1039,41 +1042,41 @@ " if sympy.isprime(n):\n", " print(\"n is prime!\")\n", " return None\n", - " \n", + "\n", " # If the number is even, two is a non-trivial factor.\n", " if n % 2 == 0:\n", " return 2\n", - " \n", + "\n", " # If n is a prime power, we can find a non-trivial factor efficiently.\n", " c = find_factor_of_prime_power(n)\n", " if c is not None:\n", " return c\n", - " \n", + "\n", " for _ in range(max_attempts):\n", " # Choose a random number between 2 and n - 1.\n", " x = random.randint(2, n - 1)\n", - " \n", + "\n", " # Most likely x and n will be relatively prime.\n", " c = math.gcd(x, n)\n", - " \n", + "\n", " # If x and n are not relatively prime, we got lucky and found\n", " # a non-trivial factor.\n", " if 1 < c < n:\n", " return c\n", - " \n", + "\n", " # Compute the order r of x modulo n using the order finder.\n", " r = order_finder(x, n)\n", - " \n", + "\n", " # If the order finder failed, try again.\n", " if r is None:\n", " continue\n", - " \n", + "\n", " # If the order r is even, try again.\n", " if r % 2 != 0:\n", " continue\n", - " \n", + "\n", " # Compute the non-trivial factor.\n", - " y = x**(r // 2) % n\n", + " y = x ** (r // 2) % n\n", " assert 1 < y < n\n", " c = math.gcd(y - 1, n)\n", " if 1 < c < n:\n", @@ -1101,6 +1104,7 @@ "outputs": [], "source": [ "\"\"\"Example of factoring via Shor's algorithm (order finding).\"\"\"\n", + "\n", "# Number to factor\n", "n = 184573\n", "\n", @@ -1122,6 +1126,7 @@ "outputs": [], "source": [ "\"\"\"Check the answer is correct.\"\"\"\n", + "\n", "p * q == n" ] } diff --git a/docs/experiments/textbook_algorithms.ipynb b/docs/experiments/textbook_algorithms.ipynb index 00467e09cc7..a5f84abfffa 100644 --- a/docs/experiments/textbook_algorithms.ipynb +++ b/docs/experiments/textbook_algorithms.ipynb @@ -9,7 +9,7 @@ }, "outputs": [], "source": [ - "#@title Copyright 2020 The Cirq Developers\n", + "# @title Copyright 2020 The Cirq Developers\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", @@ -77,6 +77,7 @@ " print(\"installing cirq...\")\n", " !pip install cirq --quiet\n", " import cirq\n", + "\n", " print(\"installed cirq.\")" ] }, @@ -125,23 +126,23 @@ "source": [ "def make_quantum_teleportation_circuit(gate):\n", " \"\"\"Returns a circuit for quantum teleportation.\n", - " \n", + "\n", " This circuit 'teleports' a random qubit state prepared by\n", " the input gate from Alice to Bob.\n", " \"\"\"\n", " circuit = cirq.Circuit()\n", - " \n", + "\n", " # Get the three qubits involved in the teleportation protocol.\n", " msg = cirq.NamedQubit(\"Message\")\n", " alice = cirq.NamedQubit(\"Alice\")\n", " bob = cirq.NamedQubit(\"Bob\")\n", - " \n", + "\n", " # The input gate prepares the message to send.\n", " circuit.append(gate(msg))\n", "\n", " # Create a Bell state shared between Alice and Bob.\n", " circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)])\n", - " \n", + "\n", " # Bell measurement of the Message and Alice's entangled qubit.\n", " circuit.append([cirq.CNOT(msg, alice), cirq.H(msg), cirq.measure(msg, alice)])\n", "\n", @@ -170,8 +171,9 @@ "outputs": [], "source": [ "\"\"\"Visualize the teleportation circuit.\"\"\"\n", + "\n", "# Gate to put the message qubit in some state to send.\n", - "gate = cirq.X ** 0.25\n", + "gate = cirq.X**0.25\n", "\n", "# Create the teleportation circuit.\n", "circuit = make_quantum_teleportation_circuit(gate)\n", @@ -197,6 +199,7 @@ "outputs": [], "source": [ "\"\"\"Display the Bloch vector of the message qubit.\"\"\"\n", + "\n", "message = cirq.Circuit(gate.on(cirq.NamedQubit(\"Message\"))).final_state_vector()\n", "message_bloch_vector = cirq.bloch_vector_from_state_vector(message, index=0)\n", "print(\"Bloch vector of message qubit:\")\n", @@ -221,6 +224,7 @@ "outputs": [], "source": [ "\"\"\"Simulate the teleportation circuit and get the final state of Bob's qubit.\"\"\"\n", + "\n", "# Get a simulator.\n", "sim = cirq.Simulator()\n", "\n", @@ -377,9 +381,9 @@ "source": [ "def make_qft(qubits):\n", " \"\"\"Generator for the QFT on a list of qubits.\n", - " \n", + "\n", " For four qubits, the answer is:\n", - " \n", + "\n", " ┌───────┐ ┌────────────┐ ┌───────┐\n", " 0: ───H───@────────@───────────@───────────────────────────────────────\n", " │ │ │\n", @@ -438,6 +442,7 @@ "outputs": [], "source": [ "\"\"\"Visually check the QFT circuit.\"\"\"\n", + "\n", "qubits = cirq.LineQubit.range(4)\n", "qft = cirq.Circuit(make_qft(qubits))\n", "print(qft)" @@ -470,6 +475,7 @@ "outputs": [], "source": [ "\"\"\"Use the built-in QFT in Cirq.\"\"\"\n", + "\n", "qft_operation = cirq.qft(*qubits, without_reverse=True)\n", "qft_cirq = cirq.Circuit(qft_operation)\n", "print(qft_cirq)" @@ -493,6 +499,7 @@ "outputs": [], "source": [ "\"\"\"Check equality of the 'manual' and 'built-in' QFTs.\"\"\"\n", + "\n", "np.testing.assert_allclose(cirq.unitary(qft), cirq.unitary(qft_cirq))" ] }, @@ -524,9 +531,9 @@ "source": [ "def make_qft_inverse(qubits):\n", " \"\"\"Generator for the inverse QFT on a list of qubits.\n", - " \n", + "\n", " For four qubits, the answer is:\n", - " \n", + "\n", " ┌────────┐ ┌──────────────┐ ┌────────┐\n", " 0: ───H───@─────────@────────────@───────────────────────────────────────────×───\n", " │ │ │ │\n", @@ -585,6 +592,7 @@ "outputs": [], "source": [ "\"\"\"Visually check the inverse QFT circuit.\"\"\"\n", + "\n", "qubits = cirq.LineQubit.range(4)\n", "iqft = cirq.Circuit(make_qft_inverse(qubits))\n", "print(iqft)" @@ -617,6 +625,7 @@ "outputs": [], "source": [ "\"\"\"Use the built-in inverse QFT in Cirq.\"\"\"\n", + "\n", "iqft_operation = cirq.qft(*qubits, inverse=True, without_reverse=True)\n", "iqft_cirq = cirq.Circuit(iqft_operation)\n", "print(iqft_cirq)" @@ -640,6 +649,7 @@ "outputs": [], "source": [ "\"\"\"Check equality of the 'manual' and 'built-in' inverse QFTs.\"\"\"\n", + "\n", "np.testing.assert_allclose(cirq.unitary(iqft), cirq.unitary(iqft_cirq))" ] }, @@ -720,6 +730,7 @@ "outputs": [], "source": [ "\"\"\"Set up the unitary and number of bits to use in phase estimation.\"\"\"\n", + "\n", "# Value of θ which appears in the definition of the unitary U above.\n", "# Try different values.\n", "theta = 0.234\n", @@ -749,6 +760,7 @@ "outputs": [], "source": [ "\"\"\"Build the first part of the circuit for phase estimation.\"\"\"\n", + "\n", "# Get qubits for the phase estimation circuit.\n", "qubits = cirq.LineQubit.range(n_bits)\n", "u_bit = cirq.NamedQubit('u')\n", @@ -780,6 +792,7 @@ "outputs": [], "source": [ "\"\"\"Build the last part of the circuit (inverse QFT) for phase estimation.\"\"\"\n", + "\n", "# Do the inverse QFT.\n", "phase_estimator.append(make_qft_inverse(qubits[::-1]))\n", "\n", @@ -806,6 +819,7 @@ "outputs": [], "source": [ "\"\"\"Set the input state of the eigenvalue register.\"\"\"\n", + "\n", "# Add gate to change initial state to |1>.\n", "phase_estimator.insert(0, cirq.X(u_bit))\n", "\n", @@ -836,6 +850,7 @@ "outputs": [], "source": [ "\"\"\"Simulate the circuit and convert from measured bit values to estimated θ values.\"\"\"\n", + "\n", "# Simulate the circuit.\n", "sim = cirq.Simulator()\n", "result = sim.run(phase_estimator, repetitions=10)\n", @@ -891,13 +906,13 @@ "\n", " # Your code here!\n", " # ...\n", - " \n", + "\n", " # Gate to choose the initial state for the u_bit. Placing X here chooses the |1> state.\n", " phase_estimator.insert(0, prepare_eigenstate_gate.on(u_bit))\n", - " \n", + "\n", " # You code here!\n", " # theta_estimates = ...\n", - " \n", + "\n", " return theta_estimates" ] }, @@ -941,7 +956,7 @@ " # Do the controlled powers of the unitary U.\n", " for i, bit in enumerate(qubits):\n", " phase_estimator.append(cirq.ControlledGate(U).on(bit, u_bit) ** (2 ** (n_bits - 1 - i)))\n", - " \n", + "\n", " # Do the inverse QFT.\n", " phase_estimator.append(make_qft_inverse(qubits[::-1]))\n", "\n", @@ -956,7 +971,7 @@ " result = sim.run(phase_estimator, repetitions=n_reps)\n", "\n", " # Convert measurements into estimates of theta\n", - " theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits\n", + " theta_estimates = np.sum(2 ** np.arange(n_bits) * result.measurements['m'], axis=1) / 2**n_bits\n", "\n", " return theta_estimates" ] @@ -979,6 +994,7 @@ "outputs": [], "source": [ "\"\"\"Analyze convergence vs n_bits.\"\"\"\n", + "\n", "# Set the value of theta. Try different values.\n", "theta = 0.123456\n", "\n", @@ -1010,6 +1026,7 @@ "outputs": [], "source": [ "\"\"\"Plot the results.\"\"\"\n", + "\n", "plt.style.use(\"seaborn-v0_8-whitegrid\")\n", "\n", "plt.plot(nvals, estimates, \"--o\", label=\"Phase estimation\")\n", @@ -1068,6 +1085,7 @@ "outputs": [], "source": [ "\"\"\"Run phase estimation without starting in an eigenstate.\"\"\"\n", + "\n", "# Value of theta.\n", "theta = 0.123456\n", "\n", @@ -1174,6 +1192,7 @@ "outputs": [], "source": [ "\"\"\"Get qubits to use in the circuit for Grover's algorithm.\"\"\"\n", + "\n", "# Number of qubits n.\n", "nqubits = 2\n", "\n", @@ -1203,13 +1222,13 @@ " \"\"\"Implements the function {f(x) = 1 if x == x', f(x) = 0 if x != x'}.\"\"\"\n", " # For x' = (1, 1), the oracle is just a Toffoli gate.\n", " # For a general x', we negate the zero bits and implement a Toffoli.\n", - " \n", + "\n", " # Negate zero bits, if necessary.\n", " yield (cirq.X(q) for (q, bit) in zip(qubits, xprime) if not bit)\n", - " \n", + "\n", " # Do the Toffoli.\n", " yield (cirq.TOFFOLI(qubits[0], qubits[1], ancilla))\n", - " \n", + "\n", " # Negate zero bits, if necessary.\n", " yield (cirq.X(q) for (q, bit) in zip(qubits, xprime) if not bit)" ] @@ -1237,7 +1256,7 @@ "\n", " # Create an equal superposition over input qubits.\n", " circuit.append(cirq.H.on_each(*qubits))\n", - " \n", + "\n", " # Put the output qubit in the |-⟩ state.\n", " circuit.append([cirq.X(ancilla), cirq.H(ancilla)])\n", "\n", @@ -1277,6 +1296,7 @@ "outputs": [], "source": [ "\"\"\"Select a 'marked' bitstring x' at random.\"\"\"\n", + "\n", "xprime = [random.randint(0, 1) for _ in range(nqubits)]\n", "print(f\"Marked bitstring: {xprime}\")" ] @@ -1299,6 +1319,7 @@ "outputs": [], "source": [ "\"\"\"Create the circuit for Grover's algorithm.\"\"\"\n", + "\n", "# Make oracle (black box)\n", "oracle = make_oracle(qubits, ancilla, xprime)\n", "\n", @@ -1326,10 +1347,13 @@ "outputs": [], "source": [ "\"\"\"Simulate the circuit for Grover's algorithm and check the output.\"\"\"\n", + "\n", + "\n", "# Helper function.\n", "def bitstring(bits):\n", " return \"\".join(str(int(b)) for b in bits)\n", "\n", + "\n", "# Sample from the circuit a couple times.\n", "simulator = cirq.Simulator()\n", "result = simulator.run(circuit, repetitions=10)\n", diff --git a/docs/experiments/variational_algorithm.ipynb b/docs/experiments/variational_algorithm.ipynb index a40f4687fa1..c59d8eff3ef 100644 --- a/docs/experiments/variational_algorithm.ipynb +++ b/docs/experiments/variational_algorithm.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -216,6 +216,7 @@ " for j in range(length):\n", " yield rot(cirq.GridQubit(i, j))\n", "\n", + "\n", "# Create the circuit using the rot_x_layer generator\n", "circuit = cirq.Circuit()\n", "circuit.append(rot_x_layer(2, 0.1))\n", @@ -248,9 +249,12 @@ "outputs": [], "source": [ "import random\n", + "\n", + "\n", "def rand2d(rows, cols):\n", " return [[random.choice([+1, -1]) for _ in range(cols)] for _ in range(rows)]\n", "\n", + "\n", "def random_instance(length):\n", " # transverse field terms\n", " h = rand2d(length, length)\n", @@ -260,6 +264,7 @@ " jc = rand2d(length, length - 1)\n", " return (h, jr, jc)\n", "\n", + "\n", "h, jr, jc = random_instance(3)\n", "print(f'transverse fields: {h}')\n", "print(f'row j fields: {jr}')\n", @@ -338,7 +343,7 @@ "source": [ "def rot_11_layer(jr, jc, half_turns):\n", " \"\"\"Yields rotations about |11> conditioned on the jr and jc fields.\"\"\"\n", - " cz_gate = cirq.CZPowGate(exponent=half_turns) \n", + " cz_gate = cirq.CZPowGate(exponent=half_turns)\n", " for i, jr_row in enumerate(jr):\n", " for j, jr_ij in enumerate(jr_row):\n", " q = cirq.GridQubit(i, j)\n", @@ -386,15 +391,17 @@ "def initial_step(length):\n", " yield prepare_plus_layer(length)\n", "\n", + "\n", "def one_step(h, jr, jc, x_half_turns, h_half_turns, j_half_turns):\n", " length = len(h)\n", " yield rot_z_layer(h, h_half_turns)\n", " yield rot_11_layer(jr, jc, j_half_turns)\n", " yield rot_x_layer(length, x_half_turns)\n", "\n", + "\n", "h, jr, jc = random_instance(3)\n", "\n", - "circuit = cirq.Circuit() \n", + "circuit = cirq.Circuit()\n", "circuit.append(initial_step(len(h)))\n", "circuit.append(one_step(h, jr, jc, 0.1, 0.2, 0.3))\n", "print(circuit)" @@ -458,11 +465,11 @@ "source": [ "import numpy as np\n", "\n", + "\n", "def energy_func(length, h, jr, jc):\n", " def energy(measurements):\n", " # Reshape measurement into array that matches grid shape.\n", - " meas_list_of_lists = [measurements[i * length:(i + 1) * length]\n", - " for i in range(length)]\n", + " meas_list_of_lists = [measurements[i * length : (i + 1) * length] for i in range(length)]\n", " # Convert true/false to +1/-1.\n", " pm_meas = 1 - 2 * np.array(meas_list_of_lists).astype(np.int32)\n", "\n", @@ -474,7 +481,10 @@ " for j, jc_ij in enumerate(jc_row):\n", " tot_energy += jc_ij * pm_meas[i, j] * pm_meas[i, j + 1]\n", " return tot_energy\n", + "\n", " return energy\n", + "\n", + "\n", "print(results.histogram(key='x', fold_func=energy_func(3, h, jr, jc)))" ] }, @@ -497,7 +507,9 @@ "source": [ "def obj_func(result):\n", " energy_hist = result.histogram(key='x', fold_func=energy_func(3, h, jr, jc))\n", - " return np.sum([k * v for k,v in energy_hist.items()]) / result.repetitions\n", + " return np.sum([k * v for k, v in energy_hist.items()]) / result.repetitions\n", + "\n", + "\n", "print(f'Value of the objective function {obj_func(results)}')" ] }, @@ -525,6 +537,7 @@ "outputs": [], "source": [ "import sympy\n", + "\n", "circuit = cirq.Circuit()\n", "alpha = sympy.Symbol('alpha')\n", "beta = sympy.Symbol('beta')\n", @@ -579,9 +592,11 @@ }, "outputs": [], "source": [ - "sweep = (cirq.Linspace(key='alpha', start=0.1, stop=0.9, length=5)\n", - " * cirq.Linspace(key='beta', start=0.1, stop=0.9, length=5)\n", - " * cirq.Linspace(key='gamma', start=0.1, stop=0.9, length=5))\n", + "sweep = (\n", + " cirq.Linspace(key='alpha', start=0.1, stop=0.9, length=5)\n", + " * cirq.Linspace(key='beta', start=0.1, stop=0.9, length=5)\n", + " * cirq.Linspace(key='gamma', start=0.1, stop=0.9, length=5)\n", + ")\n", "results = simulator.run_sweep(circuit, params=sweep, repetitions=100)\n", "for result in results:\n", " print(result.params.param_dict, obj_func(result))" @@ -607,9 +622,11 @@ "outputs": [], "source": [ "sweep_size = 10\n", - "sweep = (cirq.Linspace(key='alpha', start=0.0, stop=1.0, length=sweep_size)\n", - " * cirq.Linspace(key='beta', start=0.0, stop=1.0, length=sweep_size)\n", - " * cirq.Linspace(key='gamma', start=0.0, stop=1.0, length=sweep_size))\n", + "sweep = (\n", + " cirq.Linspace(key='alpha', start=0.0, stop=1.0, length=sweep_size)\n", + " * cirq.Linspace(key='beta', start=0.0, stop=1.0, length=sweep_size)\n", + " * cirq.Linspace(key='gamma', start=0.0, stop=1.0, length=sweep_size)\n", + ")\n", "results = simulator.run_sweep(circuit, params=sweep, repetitions=100)\n", "\n", "min = None\n", diff --git a/docs/gatezoo.ipynb b/docs/gatezoo.ipynb index 92a583a6203..678b3a99d47 100644 --- a/docs/gatezoo.ipynb +++ b/docs/gatezoo.ipynb @@ -9,7 +9,7 @@ }, "outputs": [], "source": [ - "#@title Copyright 2022 The Cirq Developers\n", + "# @title Copyright 2022 The Cirq Developers\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", @@ -77,11 +77,12 @@ " print(\"installing cirq...\")\n", " !pip install --quiet cirq\n", " print(\"installed cirq.\")\n", - " \n", + "\n", "import IPython.display as ipd\n", "import cirq\n", "import inspect\n", "\n", + "\n", "def display_gates(*gates):\n", " for gate_name in gates:\n", " ipd.display(ipd.Markdown(\"---\"))\n", @@ -89,7 +90,7 @@ " ipd.display(ipd.Markdown(f\"#### cirq.{gate_name}\"))\n", " ipd.display(ipd.Markdown(inspect.cleandoc(gate.__doc__ or \"\")))\n", " else:\n", - " ipd.display(ipd.Markdown(\"---\")) " + " ipd.display(ipd.Markdown(\"---\"))" ] }, { diff --git a/docs/google/best_practices.ipynb b/docs/google/best_practices.ipynb index 99edc98e59b..581021ff18a 100644 --- a/docs/google/best_practices.ipynb +++ b/docs/google/best_practices.ipynb @@ -8,7 +8,7 @@ }, "outputs": [], "source": [ - "#@title Copyright 2022 The Cirq Developers\n", + "# @title Copyright 2022 The Cirq Developers\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", @@ -67,6 +67,7 @@ " print(\"installing cirq...\")\n", " !pip install --quiet cirq\n", " import cirq\n", + "\n", " print(\"installed cirq.\")" ] }, @@ -148,7 +149,7 @@ "# Convert the circuit to run on a Google target gateset.\n", "# The google specific `cirq.CompilationTargetGateset` specifies the target gateset\n", "# and a sequence of appropriate optimization routines that should be executed to compile\n", - "# a circuit to run on this target. \n", + "# a circuit to run on this target.\n", "sycamore_circuit = cirq.optimize_for_target_gateset(my_circuit, gateset=cg.SycamoreTargetGateset())" ] }, @@ -216,9 +217,7 @@ "outputs": [], "source": [ "syc_circuit = cirq.optimize_for_target_gateset(\n", - " short_circuit,\n", - " gateset=cg.SycamoreTargetGateset(),\n", - " context=cirq.TransformerContext(deep=True)\n", + " short_circuit, gateset=cg.SycamoreTargetGateset(), context=cirq.TransformerContext(deep=True)\n", ")\n", "print(syc_circuit)" ] @@ -275,11 +274,8 @@ "sampler = cirq.Simulator()\n", "\n", "# STRATEGY #1: Have a separate circuit and sample call for each basis.\n", - "circuit_z = cirq.Circuit(\n", - " cirq.measure(q, key='out'))\n", - "circuit_x = cirq.Circuit(\n", - " cirq.H(q),\n", - " cirq.measure(q, key='out'))\n", + "circuit_z = cirq.Circuit(cirq.measure(q, key='out'))\n", + "circuit_x = cirq.Circuit(cirq.H(q), cirq.measure(q, key='out'))\n", "samples_z = sampler.sample(circuit_z, repetitions=5)\n", "samples_x = sampler.sample(circuit_x, repetitions=5)\n", "\n", @@ -296,13 +292,9 @@ "outputs": [], "source": [ "# STRATEGY #2: Have a parameterized circuit.\n", - "circuit_sweep = cirq.Circuit(\n", - " cirq.H(q)**sympy.Symbol('t'),\n", - " cirq.measure(q, key='out'))\n", + "circuit_sweep = cirq.Circuit(cirq.H(q) ** sympy.Symbol('t'), cirq.measure(q, key='out'))\n", "\n", - "samples_sweep = sampler.sample(circuit_sweep,\n", - " repetitions=5,\n", - " params=[{'t': 0}, {'t': 1}])\n", + "samples_sweep = sampler.sample(circuit_sweep, repetitions=5, params=[{'t': 0}, {'t': 1}])\n", "print(samples_sweep)" ] }, diff --git a/docs/google/concepts.ipynb b/docs/google/concepts.ipynb index 83379197ef7..d58920ab25e 100644 --- a/docs/google/concepts.ipynb +++ b/docs/google/concepts.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -122,12 +122,9 @@ }, "outputs": [], "source": [ - "q0, q1, q2 = cirq.GridQubit.rect(1,3)\n", + "q0, q1, q2 = cirq.GridQubit.rect(1, 3)\n", "circuit = cirq.Circuit(\n", - " (cirq.X ** 0.5).on_each(q0, q1, q2),\n", - " cirq.CZ(q0, q1),\n", - " cirq.CZ(q1, q2),\n", - " cirq.measure(q2, key='m')\n", + " (cirq.X**0.5).on_each(q0, q1, q2), cirq.CZ(q0, q1), cirq.CZ(q1, q2), cirq.measure(q2, key='m')\n", ")\n", "print(circuit)" ] diff --git a/docs/google/internal_gates.ipynb b/docs/google/internal_gates.ipynb index 3272c74f5c0..e8b855470da 100644 --- a/docs/google/internal_gates.ipynb +++ b/docs/google/internal_gates.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -123,10 +123,11 @@ " # Arguments to be passed to the constructor of the internal gate.\n", "}\n", "internal_gate = cirq_google.InternalGate(\n", - " gate_module='GATE_MODULE', # Module of class. \n", + " gate_module='GATE_MODULE', # Module of class.\n", " gate_name='GATE_NAMPE', # Class name.\n", " num_qubits=2, # Number of qubits that the gate acts on.\n", - " **internal_gate_args)\n", + " **internal_gate_args,\n", + ")\n", "internal_gate" ] }, diff --git a/docs/google/qubit-placement.ipynb b/docs/google/qubit-placement.ipynb index 33aef87ed66..14ee09038cc 100644 --- a/docs/google/qubit-placement.ipynb +++ b/docs/google/qubit-placement.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -113,6 +113,7 @@ "outputs": [], "source": [ "from cirq_google.workflow import SimulatedProcessorWithLocalDeviceRecord\n", + "\n", "rainbow_record = SimulatedProcessorWithLocalDeviceRecord('rainbow')\n", "rainbow_device = rainbow_record.get_device()\n", "rainbow_graph = rainbow_device.metadata.nx_graph\n", @@ -152,11 +153,11 @@ "outputs": [], "source": [ "circuit = cirq.experiments.random_rotations_between_grid_interaction_layers_circuit(\n", - " qubits=sorted(topo.nodes_as_gridqubits()),\n", - " depth=4,\n", + " qubits=sorted(topo.nodes_as_gridqubits()), depth=4\n", ")\n", "\n", "from cirq.contrib.svg import SVGCircuit\n", + "\n", "SVGCircuit(circuit)" ] }, @@ -180,6 +181,7 @@ "outputs": [], "source": [ "from cirq.contrib.routing import get_circuit_connectivity\n", + "\n", "circuit_graph = get_circuit_connectivity(circuit)\n", "_ = cirq.draw_gridlike(circuit_graph, tilted=False)" ] @@ -208,6 +210,7 @@ "# handled for you.\n", "\n", "from cirq_google.workflow import SharedRuntimeInfo\n", + "\n", "shared_rt_info = SharedRuntimeInfo(run_id='example', device=rainbow_device)\n", "\n", "rs = np.random.RandomState(10)" @@ -245,7 +248,9 @@ "source": [ "rdp = RandomDevicePlacer()\n", "\n", - "placed_c, placement = rdp.place_circuit(circuit, problem_topology=topo, shared_rt_info=shared_rt_info, rs=rs)\n", + "placed_c, placement = rdp.place_circuit(\n", + " circuit, problem_topology=topo, shared_rt_info=shared_rt_info, rs=rs\n", + ")\n", "cirq.draw_placements(rainbow_graph, circuit_graph, [placement])" ] }, @@ -270,7 +275,9 @@ "source": [ "naive = NaiveQubitPlacer()\n", "\n", - "placed_c, placement = naive.place_circuit(circuit, problem_topology=topo, shared_rt_info=shared_rt_info, rs=rs)\n", + "placed_c, placement = naive.place_circuit(\n", + " circuit, problem_topology=topo, shared_rt_info=shared_rt_info, rs=rs\n", + ")\n", "cirq.draw_placements(rainbow_graph, circuit_graph, [placement])" ] }, @@ -297,18 +304,22 @@ "source": [ "import itertools\n", "\n", + "\n", "def all_offset_placements(device_graph, offset=(4, 2), min_sidelength=2, max_sidelength=5):\n", " # Generate candidate tilted square lattice topologies\n", " sidelens = list(itertools.product(range(min_sidelength, max_sidelength + 1), repeat=2))\n", " topos = [cirq.TiltedSquareLattice(width, height) for width, height in sidelens]\n", - " \n", + "\n", " # Make placements using TiltedSquareLattice.nodes_to_gridqubits offset parameter\n", " placements = {topo: topo.nodes_to_gridqubits(offset=offset) for topo in topos}\n", - " \n", + "\n", " # Only allow placements that are valid on the device graph\n", - " placements = {topo: mapping for topo, mapping in placements.items()\n", - " if cirq.is_valid_placement(device_graph, topo.graph, mapping)}\n", - " return placements\n" + " placements = {\n", + " topo: mapping\n", + " for topo, mapping in placements.items()\n", + " if cirq.is_valid_placement(device_graph, topo.graph, mapping)\n", + " }\n", + " return placements" ] }, { @@ -331,7 +342,9 @@ "rainbow_mapping = all_offset_placements(rainbow_graph)\n", "hardcoded = HardcodedQubitPlacer(mapping=rainbow_mapping)\n", "\n", - "placed_c, placement = hardcoded.place_circuit(circuit, problem_topology=topo, shared_rt_info=shared_rt_info, rs=rs)\n", + "placed_c, placement = hardcoded.place_circuit(\n", + " circuit, problem_topology=topo, shared_rt_info=shared_rt_info, rs=rs\n", + ")\n", "cirq.draw_placements(rainbow_graph, circuit_graph, [placement])" ] }, @@ -357,15 +370,14 @@ "from math import ceil\n", "\n", "n_col = 3\n", - "n_row = int(ceil(len(rainbow_mapping)/n_col))\n", - "fig, axes = plt.subplots(n_row, n_col, figsize=(4*n_col, 3*n_row))\n", + "n_row = int(ceil(len(rainbow_mapping) / n_col))\n", + "fig, axes = plt.subplots(n_row, n_col, figsize=(4 * n_col, 3 * n_row))\n", "axes = axes.reshape(-1)\n", "for i, (topo, mapping) in enumerate(rainbow_mapping.items()):\n", "\n", " axes[i].set_title(f'{topo.width}x{topo.height}')\n", - " cirq.draw_placements(rainbow_graph, topo.graph, [mapping], \n", - " tilted=False, axes=axes[i:i+1])\n", - " \n", + " cirq.draw_placements(rainbow_graph, topo.graph, [mapping], tilted=False, axes=axes[i : i + 1])\n", + "\n", "fig.suptitle(\"All hardcoded placements\", fontsize=14)\n", "fig.tight_layout()" ] diff --git a/docs/hardware/aqt/getting_started.ipynb b/docs/hardware/aqt/getting_started.ipynb index ea27fd788ed..a29e2fe0df4 100644 --- a/docs/hardware/aqt/getting_started.ipynb +++ b/docs/hardware/aqt/getting_started.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -102,6 +102,7 @@ "import cirq\n", "from cirq.aqt.aqt_device import get_aqt_device\n", "from cirq.aqt.aqt_sampler import AQTSampler\n", + "\n", "access_token = 'MY_TOKEN'" ] }, @@ -191,7 +192,7 @@ } ], "source": [ - "circuit = cirq.Circuit(cirq.XX(qubits[0], qubits[1])**0.5)\n", + "circuit = cirq.Circuit(cirq.XX(qubits[0], qubits[1]) ** 0.5)\n", "device.validate_circuit(circuit)\n", "print(circuit, qubits)" ] diff --git a/docs/hardware/azure-quantum/getting_started_honeywell.ipynb b/docs/hardware/azure-quantum/getting_started_honeywell.ipynb index 80d247c5dc5..d8fb5a00415 100644 --- a/docs/hardware/azure-quantum/getting_started_honeywell.ipynb +++ b/docs/hardware/azure-quantum/getting_started_honeywell.ipynb @@ -79,10 +79,9 @@ "outputs": [], "source": [ "from azure.quantum.cirq import AzureQuantumService\n", + "\n", "service = AzureQuantumService(\n", - " resource_id=\"\",\n", - " location=\"\",\n", - " default_target=\"honeywell.hqs-lt-s1-apival\"\n", + " resource_id=\"\", location=\"\", default_target=\"honeywell.hqs-lt-s1-apival\"\n", ")" ] }, @@ -167,9 +166,9 @@ "\n", "q0, q1 = cirq.LineQubit.range(2)\n", "circuit = cirq.Circuit(\n", - " cirq.H(q0), # Hadamard\n", - " cirq.CNOT(q0, q1), # CNOT\n", - " cirq.measure(q0, q1, key='b') # Measure both qubits into classical register \"b\"\n", + " cirq.H(q0), # Hadamard\n", + " cirq.CNOT(q0, q1), # CNOT\n", + " cirq.measure(q0, q1, key='b'), # Measure both qubits into classical register \"b\"\n", ")\n", "circuit" ] @@ -249,10 +248,7 @@ }, "outputs": [], "source": [ - "job = service.create_job(\n", - " program=circuit,\n", - " repetitions=100\n", - ")" + "job = service.create_job(program=circuit, repetitions=100)" ] }, { diff --git a/docs/hardware/azure-quantum/getting_started_ionq.ipynb b/docs/hardware/azure-quantum/getting_started_ionq.ipynb index 747b0bca246..b190facc34e 100644 --- a/docs/hardware/azure-quantum/getting_started_ionq.ipynb +++ b/docs/hardware/azure-quantum/getting_started_ionq.ipynb @@ -88,11 +88,8 @@ "outputs": [], "source": [ "from azure.quantum.cirq import AzureQuantumService\n", - "service = AzureQuantumService(\n", - " resource_id=\"\",\n", - " location=\"\",\n", - " default_target=\"ionq.simulator\"\n", - ")" + "\n", + "service = AzureQuantumService(resource_id=\"\", location=\"\", default_target=\"ionq.simulator\")" ] }, { @@ -177,9 +174,9 @@ "\n", "q0, q1 = cirq.LineQubit.range(2)\n", "circuit = cirq.Circuit(\n", - " cirq.X(q0)**0.5, # Square root of X\n", - " cirq.CX(q0, q1), # CNOT\n", - " cirq.measure(q0, q1, key='b') # Measure both qubits\n", + " cirq.X(q0) ** 0.5, # Square root of X\n", + " cirq.CX(q0, q1), # CNOT\n", + " cirq.measure(q0, q1, key='b'), # Measure both qubits\n", ")\n", "circuit" ] @@ -264,7 +261,7 @@ " program=circuit,\n", " repetitions=100,\n", " target=\"ionq.qpu\",\n", - " timeout_seconds=500 # Set timeout to 500 seconds to accommodate current queue time on QPU\n", + " timeout_seconds=500, # Set timeout to 500 seconds to accommodate current queue time on QPU\n", ")" ] }, @@ -316,11 +313,7 @@ }, "outputs": [], "source": [ - "job = service.create_job(\n", - " program=circuit,\n", - " repetitions=100,\n", - " target=\"ionq.simulator\"\n", - ")" + "job = service.create_job(program=circuit, repetitions=100, target=\"ionq.simulator\")" ] }, { diff --git a/docs/hardware/ionq/getting_started.ipynb b/docs/hardware/ionq/getting_started.ipynb index 695c2f6a4be..61187eb25d1 100644 --- a/docs/hardware/ionq/getting_started.ipynb +++ b/docs/hardware/ionq/getting_started.ipynb @@ -54,6 +54,7 @@ "source": [ "try:\n", " import cirq\n", + "\n", " version = cirq.__version__.split(\".\")\n", " assert int(version[0]) > 0 or int(version[1]) > 9, \"Cirq version >0.9 required\"\n", "except (ImportError, AssertionError):\n", @@ -111,10 +112,9 @@ }, "outputs": [], "source": [ - "API_KEY = 'tomyheart' # Replace with your IonQ API key\n", + "API_KEY = 'tomyheart' # Replace with your IonQ API key\n", "\n", - "service = ionq.Service(api_key=API_KEY, \n", - " default_target='simulator')" + "service = ionq.Service(api_key=API_KEY, default_target='simulator')" ] }, { @@ -148,9 +148,9 @@ "source": [ "q0, q1 = cirq.LineQubit.range(2)\n", "circuit = cirq.Circuit(\n", - " cirq.X(q0) ** 0.5, # Square root of X\n", - " cirq.CX(q0, q1), # CNOT\n", - " cirq.measure(q0, q1, key='b') # Measure both qubits\n", + " cirq.X(q0) ** 0.5, # Square root of X\n", + " cirq.CX(q0, q1), # CNOT\n", + " cirq.measure(q0, q1, key='b'), # Measure both qubits\n", ")\n", "result = service.run(circuit, repetitions=100)\n", "print(result)" diff --git a/docs/hardware/pasqal/getting_started.ipynb b/docs/hardware/pasqal/getting_started.ipynb index f971b7f9283..b8466aeccb9 100644 --- a/docs/hardware/pasqal/getting_started.ipynb +++ b/docs/hardware/pasqal/getting_started.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -117,14 +117,16 @@ }, "outputs": [], "source": [ - "width=6\n", - "height=6\n", - "depth=1\n", + "width = 6\n", + "height = 6\n", + "depth = 1\n", "# Creating p_qubits, a list of ThreeDQubits.\n", - "p_qubits=[ThreeDQubit(row, col, layer) \n", - " for row in range(width) \n", - " for col in range(height)\n", - " for layer in range(depth)]" + "p_qubits = [\n", + " ThreeDQubit(row, col, layer)\n", + " for row in range(width)\n", + " for col in range(height)\n", + " for layer in range(depth)\n", + "]" ] }, { @@ -144,7 +146,7 @@ }, "outputs": [], "source": [ - "p_qubits = TwoDQubit.square(6) # 6x6 square array of TwoDQubits" + "p_qubits = TwoDQubit.square(6) # 6x6 square array of TwoDQubits" ] }, { @@ -175,7 +177,7 @@ "initial_circuit.append(cirq.CX(p_qubits[0], p_qubits[2]))\n", "\n", "# Create a Pasqal device with a control radius of 2.1 (in units of the lattice spacing)\n", - "p_device=PasqalVirtualDevice(control_radius=2.1, qubits=p_qubits)\n", + "p_device = PasqalVirtualDevice(control_radius=2.1, qubits=p_qubits)\n", "\n", "# Validate the circuit using the device\n", "try:\n", @@ -202,13 +204,11 @@ }, "outputs": [], "source": [ - "pasqal_gateset=cirq_pasqal.PasqalGateset(include_additional_controlled_ops=False)\n", - "pasqal_circuit = cirq.optimize_for_target_gateset(initial_circuit,\n", - " gateset=pasqal_gateset)\n", + "pasqal_gateset = cirq_pasqal.PasqalGateset(include_additional_controlled_ops=False)\n", + "pasqal_circuit = cirq.optimize_for_target_gateset(initial_circuit, gateset=pasqal_gateset)\n", "\n", "# TODO(https://github.com/quantumlib/Cirq/issues/6655) - remove after fixup\n", - "pasqal_circuit = cirq.Circuit(pasqal_circuit.all_operations(),\n", - " strategy=cirq.InsertStrategy.NEW)\n", + "pasqal_circuit = cirq.Circuit(pasqal_circuit.all_operations(), strategy=cirq.InsertStrategy.NEW)\n", "\n", "print(pasqal_circuit)\n", "\n", @@ -244,8 +244,7 @@ " # Uh oh! This circuit does not pass validation.\n", " print(e)\n", "\n", - "pasqal_circuit = cirq.Circuit(initial_circuit.all_operations(),\n", - " strategy=cirq.InsertStrategy.NEW)\n", + "pasqal_circuit = cirq.Circuit(initial_circuit.all_operations(), strategy=cirq.InsertStrategy.NEW)\n", "print('')\n", "print('Converted Circuit, passes validation:')\n", "print(pasqal_circuit)\n", @@ -313,22 +312,25 @@ "source": [ "import numpy as np\n", "\n", - "#Place qubits at vertices of an equilateral triangle\n", - "qs = [TwoDQubit(0, 0), TwoDQubit(1, 0), TwoDQubit(0.5, np.sqrt(3)/2)]\n", + "# Place qubits at vertices of an equilateral triangle\n", + "qs = [TwoDQubit(0, 0), TwoDQubit(1, 0), TwoDQubit(0.5, np.sqrt(3) / 2)]\n", "q_meas = [TwoDQubit(1, 0), TwoDQubit(0, 0)]\n", "\n", + "\n", "def state_preparation():\n", " for q in qs[:-1]:\n", " yield cirq.H(q)\n", " yield cirq.X(qs[-1])\n", " yield cirq.H(qs[-1])\n", "\n", + "\n", "def oracle():\n", " # Signals the state 10\n", " yield cirq.X(qs[0])\n", " yield cirq.CCX(*qs)\n", " yield cirq.X(qs[0])\n", "\n", + "\n", "def grover_operator():\n", " for q in qs[:-1]:\n", " yield cirq.H(q)\n", @@ -339,20 +341,23 @@ " for q in qs[:-1]:\n", " yield cirq.X(q)\n", " yield cirq.H(q)\n", - " \n", + "\n", + "\n", "def generate_grover():\n", " yield state_preparation()\n", " yield oracle()\n", " yield grover_operator()\n", - " \n", + "\n", + "\n", "def generate_pasqal_grover():\n", - " pasqal_gateset=cirq_pasqal.PasqalGateset(include_additional_controlled_ops=False)\n", - " grover_cicruit = cirq.optimize_for_target_gateset(cirq.Circuit(generate_grover()),\n", - " gateset=pasqal_gateset)\n", - " return cirq.Circuit(grover_cicruit.all_operations(),\n", - " strategy=cirq.InsertStrategy.NEW)\n", - " \n", - "device = PasqalVirtualDevice(control_radius=1.1, qubits=qs) \n", + " pasqal_gateset = cirq_pasqal.PasqalGateset(include_additional_controlled_ops=False)\n", + " grover_cicruit = cirq.optimize_for_target_gateset(\n", + " cirq.Circuit(generate_grover()), gateset=pasqal_gateset\n", + " )\n", + " return cirq.Circuit(grover_cicruit.all_operations(), strategy=cirq.InsertStrategy.NEW)\n", + "\n", + "\n", + "device = PasqalVirtualDevice(control_radius=1.1, qubits=qs)\n", "grover_circuit = generate_pasqal_grover()\n", "device.validate_circuit(grover_circuit)\n", "grover_circuit.append(cirq.measure(*q_meas, key='x'))" @@ -422,19 +427,19 @@ "\n", "# Create dictionary of results\n", "data0 = data_raw.data.to_dict()\n", - "vec=[j for j in range(4)]\n", - "res=np.zeros(len(vec))\n", + "vec = [j for j in range(4)]\n", + "res = np.zeros(len(vec))\n", "for jj in range(200):\n", " number = data0['x'][jj]\n", " res[number] += 1\n", - "res=res/200.\n", + "res = res / 200.0\n", "\n", "# Display plot of states\n", "fig = plt.figure()\n", "ax = fig.add_axes([0.16, 0.16, 0.78, 0.78])\n", - "ax.plot(vec, res,'o')\n", + "ax.plot(vec, res, 'o')\n", "ax.set_xticks(vec)\n", - "ax.set_xticklabels([r'$|00\\rangle$',r'$|01\\rangle$', r'$|10\\rangle$', r'$|11\\rangle$'])\n", + "ax.set_xticklabels([r'$|00\\rangle$', r'$|01\\rangle$', r'$|10\\rangle$', r'$|11\\rangle$'])\n", "plt.xlabel(r'$j$', fontsize=20)\n", "plt.ylabel(r'$p$', fontsize=20)\n", "plt.show()" @@ -479,18 +484,18 @@ "\n", "# Plot the results\n", "data0 = data_raw.data.to_dict()\n", - "vec=[j for j in range(4)]\n", - "res=np.zeros(len(vec))\n", + "vec = [j for j in range(4)]\n", + "res = np.zeros(len(vec))\n", "for jj in range(200):\n", " number = data0['x'][jj]\n", " res[number] += 1\n", - "res=res/200.\n", + "res = res / 200.0\n", "\n", "fig = plt.figure()\n", "ax = fig.add_axes([0.16, 0.16, 0.78, 0.78])\n", - "ax.plot(vec, res,'o')\n", + "ax.plot(vec, res, 'o')\n", "ax.set_xticks(vec)\n", - "ax.set_xticklabels([r'$|00\\rangle$',r'$|01\\rangle$', r'$|10\\rangle$', r'$|11\\rangle$'])\n", + "ax.set_xticklabels([r'$|00\\rangle$', r'$|01\\rangle$', r'$|10\\rangle$', r'$|11\\rangle$'])\n", "plt.xlabel(r'$j$', fontsize=20)\n", "plt.ylabel(r'$p$', fontsize=20)\n", "plt.show()" diff --git a/docs/hardware/rigetti/getting_started.ipynb b/docs/hardware/rigetti/getting_started.ipynb index d33d4bd059d..5dbb127e3f2 100644 --- a/docs/hardware/rigetti/getting_started.ipynb +++ b/docs/hardware/rigetti/getting_started.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -431,7 +431,7 @@ } ], "source": [ - "cirq.plot_state_histogram(result.histogram(key='m')) " + "cirq.plot_state_histogram(result.histogram(key='m'))" ] }, { @@ -494,20 +494,23 @@ "source": [ "from pyquil.quilbase import Reset, Pragma\n", "\n", + "\n", "def hook(program, measurement_id_map):\n", " program._instructions.insert(0, Reset())\n", " program._instructions.insert(1, Pragma('INITIAL_REWIRING', freeform_string='GREEDY'))\n", " print(program)\n", " return program, measurement_id_map\n", "\n", + "\n", "# assign qubits explicitly to hardware or virtual machine qubits.\n", - "qubit_id_map = {\n", - " qubits[0]: 4,\n", - " qubits[1]: 5,\n", - "}\n", + "qubit_id_map = {qubits[0]: 4, qubits[1]: 5}\n", "executor = circuit_sweep_executors.with_quilc_compilation_and_cirq_parameter_resolution\n", - "transformer = circuit_transformers.build(qubit_id_map=qubit_id_map, qubits=qubits, post_transformation_hooks=[hook])\n", - "service = get_rigetti_qcs_service(SERVICE_NAME, as_qvm=True, executor=executor, transformer=transformer)\n", + "transformer = circuit_transformers.build(\n", + " qubit_id_map=qubit_id_map, qubits=qubits, post_transformation_hooks=[hook]\n", + ")\n", + "service = get_rigetti_qcs_service(\n", + " SERVICE_NAME, as_qvm=True, executor=executor, transformer=transformer\n", + ")\n", "result = service.run(bell_circuit, repetitions=1000)\n", "\n", "cirq.plot_state_histogram(result.histogram(key='m'))" @@ -569,9 +572,7 @@ "\n", "qubit = cirq.LineQubit.range(1)[0]\n", "\n", - "circuit = cirq.Circuit(\n", - " cirq.H(qubit)**sympy.Symbol('t'),\n", - " cirq.measure(qubit, key='m'))\n", + "circuit = cirq.Circuit(cirq.H(qubit) ** sympy.Symbol('t'), cirq.measure(qubit, key='m'))\n", "params = cirq.Linspace('t', start=0, stop=4, length=5)\n", "\n", "print(circuit)" @@ -808,7 +809,10 @@ "import pandas as pd\n", "\n", "results = sampler.run_sweep(circuit, params, repetitions=10)\n", - "data = {f't={result.params[\"t\"]}': [measurement[0] for measurement in result.measurements['m']] for result in results}\n", + "data = {\n", + " f't={result.params[\"t\"]}': [measurement[0] for measurement in result.measurements['m']]\n", + " for result in results\n", + "}\n", "\n", "pd.DataFrame(data)" ] diff --git a/docs/named_topologies.ipynb b/docs/named_topologies.ipynb index f6377988fc5..b9b31318265 100644 --- a/docs/named_topologies.ipynb +++ b/docs/named_topologies.ipynb @@ -20,7 +20,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -78,7 +78,7 @@ " print(\"installing cirq...\")\n", " !pip install --quiet cirq\n", " print(\"installed cirq.\")\n", - " \n", + "\n", "import cirq" ] }, @@ -126,24 +126,24 @@ "import itertools\n", "from cirq import TiltedSquareLattice\n", "\n", - "side_lens = np.arange(1, 4+1)\n", + "side_lens = np.arange(1, 4 + 1)\n", "l = len(side_lens)\n", "\n", - "fig, axes = plt.subplots(l, l, figsize=(3.5*l, 3*l))\n", + "fig, axes = plt.subplots(l, l, figsize=(3.5 * l, 3 * l))\n", "for widthi, heighti in itertools.product(np.arange(l), repeat=2):\n", " width = side_lens[widthi]\n", " height = side_lens[heighti]\n", " ax = axes[heighti, widthi]\n", " topo = TiltedSquareLattice(width, height)\n", " topo.draw(ax=ax, tilted=False)\n", - " \n", + "\n", " if widthi == 0:\n", " ax.set_ylabel(f'Height {height}', fontsize=14)\n", - " if heighti == l-1:\n", + " if heighti == l - 1:\n", " ax.set_xlabel(f'Width {width}', fontsize=14)\n", - " \n", + "\n", " ax.set_title(f'n = {topo.n_nodes}', fontsize=14)\n", - " \n", + "\n", "fig.tight_layout()" ] }, @@ -179,19 +179,43 @@ "outputs": [], "source": [ "import networkx as nx\n", - "SYC23_GRAPH = nx.from_edgelist([\n", - " ((3, 2), (4, 2)), ((4, 1), (5, 1)), ((4, 2), (4, 1)), \n", - " ((4, 2), (4, 3)), ((4, 2), (5, 2)), ((4, 3), (5, 3)), \n", - " ((5, 1), (5, 0)), ((5, 1), (5, 2)), ((5, 1), (6, 1)), \n", - " ((5, 2), (5, 3)), ((5, 2), (6, 2)), ((5, 3), (5, 4)), \n", - " ((5, 3), (6, 3)), ((5, 4), (6, 4)), ((6, 1), (6, 2)), \n", - " ((6, 2), (6, 3)), ((6, 2), (7, 2)), ((6, 3), (6, 4)), \n", - " ((6, 3), (7, 3)), ((6, 4), (6, 5)), ((6, 4), (7, 4)), \n", - " ((6, 5), (7, 5)), ((7, 2), (7, 3)), ((7, 3), (7, 4)), \n", - " ((7, 3), (8, 3)), ((7, 4), (7, 5)), ((7, 4), (8, 4)), \n", - " ((7, 5), (7, 6)), ((7, 5), (8, 5)), ((8, 3), (8, 4)), \n", - " ((8, 4), (8, 5)), ((8, 4), (9, 4)), \n", - "])" + "\n", + "SYC23_GRAPH = nx.from_edgelist(\n", + " [\n", + " ((3, 2), (4, 2)),\n", + " ((4, 1), (5, 1)),\n", + " ((4, 2), (4, 1)),\n", + " ((4, 2), (4, 3)),\n", + " ((4, 2), (5, 2)),\n", + " ((4, 3), (5, 3)),\n", + " ((5, 1), (5, 0)),\n", + " ((5, 1), (5, 2)),\n", + " ((5, 1), (6, 1)),\n", + " ((5, 2), (5, 3)),\n", + " ((5, 2), (6, 2)),\n", + " ((5, 3), (5, 4)),\n", + " ((5, 3), (6, 3)),\n", + " ((5, 4), (6, 4)),\n", + " ((6, 1), (6, 2)),\n", + " ((6, 2), (6, 3)),\n", + " ((6, 2), (7, 2)),\n", + " ((6, 3), (6, 4)),\n", + " ((6, 3), (7, 3)),\n", + " ((6, 4), (6, 5)),\n", + " ((6, 4), (7, 4)),\n", + " ((6, 5), (7, 5)),\n", + " ((7, 2), (7, 3)),\n", + " ((7, 3), (7, 4)),\n", + " ((7, 3), (8, 3)),\n", + " ((7, 4), (7, 5)),\n", + " ((7, 4), (8, 4)),\n", + " ((7, 5), (7, 6)),\n", + " ((7, 5), (8, 5)),\n", + " ((8, 3), (8, 4)),\n", + " ((8, 4), (8, 5)),\n", + " ((8, 4), (9, 4)),\n", + " ]\n", + ")" ] }, { @@ -213,10 +237,12 @@ "source": [ "topo = TiltedSquareLattice(4, 2)\n", "\n", - "cirq.draw_placements(SYC23_GRAPH, topo.graph, [\n", - " topo.nodes_to_gridqubits(offset=(3,2)),\n", - " topo.nodes_to_gridqubits(offset=(5,3)),\n", - "], tilted=False)" + "cirq.draw_placements(\n", + " SYC23_GRAPH,\n", + " topo.graph,\n", + " [topo.nodes_to_gridqubits(offset=(3, 2)), topo.nodes_to_gridqubits(offset=(5, 3))],\n", + " tilted=False,\n", + ")" ] }, { @@ -267,14 +293,14 @@ "source": [ "from cirq import LineTopology\n", "\n", - "lens = np.arange(3, 12+1, 3)\n", + "lens = np.arange(3, 12 + 1, 3)\n", "l = len(lens)\n", - "fig, axes = plt.subplots(1,l, figsize=(3.5*l, 3*1))\n", + "fig, axes = plt.subplots(1, l, figsize=(3.5 * l, 3 * 1))\n", "\n", "for ax, n_nodes in zip(axes, lens):\n", " LineTopology(n_nodes).draw(ax=ax, tilted=False)\n", " ax.set_title(f'n = {n_nodes}')\n", - " \n", + "\n", "fig.tight_layout()" ] }, @@ -297,13 +323,29 @@ "source": [ "topo = LineTopology(9)\n", "\n", - "cirq.draw_placements(SYC23_GRAPH, topo.graph, [\n", - " {i: q for i, q in enumerate([\n", - " cirq.GridQubit(4, 1), cirq.GridQubit(4, 2), cirq.GridQubit(5, 2), \n", - " cirq.GridQubit(5, 3), cirq.GridQubit(6, 3), cirq.GridQubit(6, 4), \n", - " cirq.GridQubit(7, 4), cirq.GridQubit(7, 5), cirq.GridQubit(8, 5), \n", - " ])}\n", - "], tilted=False)" + "cirq.draw_placements(\n", + " SYC23_GRAPH,\n", + " topo.graph,\n", + " [\n", + " {\n", + " i: q\n", + " for i, q in enumerate(\n", + " [\n", + " cirq.GridQubit(4, 1),\n", + " cirq.GridQubit(4, 2),\n", + " cirq.GridQubit(5, 2),\n", + " cirq.GridQubit(5, 3),\n", + " cirq.GridQubit(6, 3),\n", + " cirq.GridQubit(6, 4),\n", + " cirq.GridQubit(7, 4),\n", + " cirq.GridQubit(7, 5),\n", + " cirq.GridQubit(8, 5),\n", + " ]\n", + " )\n", + " }\n", + " ],\n", + " tilted=False,\n", + ")" ] }, { diff --git a/docs/noise/heatmaps.ipynb b/docs/noise/heatmaps.ipynb index 06610b1db2c..34edb44f687 100644 --- a/docs/noise/heatmaps.ipynb +++ b/docs/noise/heatmaps.ipynb @@ -121,12 +121,14 @@ }, "outputs": [], "source": [ - "single_qubit_heatmap = cirq.Heatmap({\n", - " (cirq.GridQubit(0, 0),): 0.1,\n", - " (cirq.GridQubit(0, 1),): 0.2,\n", - " (cirq.GridQubit(0, 2),): 0.3,\n", - " (cirq.GridQubit(1, 0),): 0.4,\n", - "})\n", + "single_qubit_heatmap = cirq.Heatmap(\n", + " {\n", + " (cirq.GridQubit(0, 0),): 0.1,\n", + " (cirq.GridQubit(0, 1),): 0.2,\n", + " (cirq.GridQubit(0, 2),): 0.3,\n", + " (cirq.GridQubit(1, 0),): 0.4,\n", + " }\n", + ")\n", "\n", "_, ax = plt.subplots(figsize=(8, 8))\n", "_ = single_qubit_heatmap.plot(ax);" @@ -158,12 +160,16 @@ }, "outputs": [], "source": [ - "two_qubit_interaction_heatmap = cirq.TwoQubitInteractionHeatmap({\n", - " (cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)): 0.1,\n", - " (cirq.GridQubit(0, 1), cirq.GridQubit(0, 2)): 0.2,\n", - " (cirq.GridQubit(1, 0), cirq.GridQubit(0, 0)): 0.3,\n", - " (cirq.GridQubit(3, 3), cirq.GridQubit(3, 2)): 0.9,\n", - "}, annotation_format=\"0.2f\", title = 'Example Two-Qubit Heatmap')\n", + "two_qubit_interaction_heatmap = cirq.TwoQubitInteractionHeatmap(\n", + " {\n", + " (cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)): 0.1,\n", + " (cirq.GridQubit(0, 1), cirq.GridQubit(0, 2)): 0.2,\n", + " (cirq.GridQubit(1, 0), cirq.GridQubit(0, 0)): 0.3,\n", + " (cirq.GridQubit(3, 3), cirq.GridQubit(3, 2)): 0.9,\n", + " },\n", + " annotation_format=\"0.2f\",\n", + " title='Example Two-Qubit Heatmap',\n", + ")\n", "\n", "_, ax = plt.subplots(figsize=(8, 8))\n", "_ = two_qubit_interaction_heatmap.plot(ax)" @@ -208,15 +214,15 @@ "outputs": [], "source": [ "_, ax = plt.subplots(figsize=(8, 8))\n", - "_ = two_qubit_interaction_heatmap.plot(ax,\n", - " title = 'Heatmap with modified Colorbar',\n", - " plot_colorbar = True,\n", - " colorbar_position = 'top',\n", - " colorbar_size = '10%',\n", - " colorbar_pad = '10%',\n", - " colorbar_options = {\n", - " 'drawedges' : True\n", - " })" + "_ = two_qubit_interaction_heatmap.plot(\n", + " ax,\n", + " title='Heatmap with modified Colorbar',\n", + " plot_colorbar=True,\n", + " colorbar_position='top',\n", + " colorbar_size='10%',\n", + " colorbar_pad='10%',\n", + " colorbar_options={'drawedges': True},\n", + ")" ] }, { @@ -237,13 +243,13 @@ "outputs": [], "source": [ "_, ax = plt.subplots(figsize=(8, 8))\n", - "_ = two_qubit_interaction_heatmap.plot(ax,\n", - " title = 'Heatmap with modified Colormap',\n", - " vmin = 0.1,\n", - " vmax = 0.4,\n", - " collection_options = {\n", - " 'cmap' : 'plasma'\n", - " })" + "_ = two_qubit_interaction_heatmap.plot(\n", + " ax,\n", + " title='Heatmap with modified Colormap',\n", + " vmin=0.1,\n", + " vmax=0.4,\n", + " collection_options={'cmap': 'plasma'},\n", + ")" ] }, { @@ -264,14 +270,12 @@ "outputs": [], "source": [ "_, ax = plt.subplots(figsize=(8, 8))\n", - "_ = two_qubit_interaction_heatmap.plot(ax,\n", - " title = 'Heatmap with modified Annotation Text',\n", - " annotation_format = '.1E',\n", - " annotation_text_kwargs = {\n", - " 'family' : 'monospace',\n", - " 'size' : 'large',\n", - " 'weight' : 'bold'\n", - " })" + "_ = two_qubit_interaction_heatmap.plot(\n", + " ax,\n", + " title='Heatmap with modified Annotation Text',\n", + " annotation_format='.1E',\n", + " annotation_text_kwargs={'family': 'monospace', 'size': 'large', 'weight': 'bold'},\n", + ")" ] }, { @@ -295,12 +299,11 @@ "outputs": [], "source": [ "_, ax = plt.subplots(figsize=(8, 8))\n", - "_ = two_qubit_interaction_heatmap.plot(ax,\n", - " title = 'Heatmap with modified PolyCollection',\n", - " collection_options = {\n", - " 'edgecolors' : ('red', 'blue', 'blue', 'red'),\n", - " 'linewidths' : 5,\n", - " })\n" + "_ = two_qubit_interaction_heatmap.plot(\n", + " ax,\n", + " title='Heatmap with modified PolyCollection',\n", + " collection_options={'edgecolors': ('red', 'blue', 'blue', 'red'), 'linewidths': 5},\n", + ")" ] } ], diff --git a/docs/noise/qcvv/coherent_vs_incoherent_xeb.ipynb b/docs/noise/qcvv/coherent_vs_incoherent_xeb.ipynb index 8d271e7e3dc..8a7ba19fe5b 100644 --- a/docs/noise/qcvv/coherent_vs_incoherent_xeb.ipynb +++ b/docs/noise/qcvv/coherent_vs_incoherent_xeb.ipynb @@ -381,6 +381,7 @@ "import cirq.experiments.xeb_sampling as xeb_sampling\n", "import cirq.experiments.xeb_fitting as xeb_fitting\n", "\n", + "\n", "# use the same circuit library, cycle depths, combinations by layer,\n", "# random seed and repetitions for both noise models' samplers.\n", "def sample_df(sampler):\n", diff --git a/docs/noise/qcvv/isolated_xeb.ipynb b/docs/noise/qcvv/isolated_xeb.ipynb index f29b827f7e0..e2952b11598 100644 --- a/docs/noise/qcvv/isolated_xeb.ipynb +++ b/docs/noise/qcvv/isolated_xeb.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -116,8 +116,8 @@ "circuits = rqcg.generate_library_of_2q_circuits(\n", " n_library_circuits=20,\n", " two_qubit_gate=cirq.ISWAP**0.5,\n", - " q0=cirq.GridQubit(4,4),\n", - " q1=cirq.GridQubit(4,5),\n", + " q0=cirq.GridQubit(4, 4),\n", + " q1=cirq.GridQubit(4, 5),\n", ")\n", "print(len(circuits))" ] @@ -161,13 +161,16 @@ " sampler = cirq.DensityMatrixSimulator(noise=cirq.depolarize(5e-3))\n", "else:\n", " import cirq_google as cg\n", + "\n", " sampler = cg.get_engine_sampler(device_name, gate_set_name='sqrt_iswap')\n", " device = cg.get_engine_device(device_name)\n", "\n", " import cirq.contrib.routing as ccr\n", + "\n", " graph = ccr.gridqubits_to_graph_device(device.qubits)\n", " pos = {q: (q.row, q.col) for q in graph.nodes}\n", " import networkx as nx\n", + "\n", " nx.draw_networkx(graph, pos=pos)" ] }, @@ -189,11 +192,9 @@ "outputs": [], "source": [ "from cirq.experiments.xeb_sampling import sample_2q_xeb_circuits\n", + "\n", "sampled_df = sample_2q_xeb_circuits(\n", - " sampler=sampler,\n", - " circuits=circuits,\n", - " cycle_depths=cycle_depths,\n", - " repetitions=10_000,\n", + " sampler=sampler, circuits=circuits, cycle_depths=cycle_depths, repetitions=10_000\n", ")\n", "sampled_df" ] @@ -216,10 +217,9 @@ "outputs": [], "source": [ "from cirq.experiments.xeb_fitting import benchmark_2q_xeb_fidelities\n", + "\n", "fids = benchmark_2q_xeb_fidelities(\n", - " sampled_df=sampled_df,\n", - " circuits=circuits,\n", - " cycle_depths=cycle_depths,\n", + " sampled_df=sampled_df, circuits=circuits, cycle_depths=cycle_depths\n", ")\n", "fids" ] @@ -237,11 +237,13 @@ "\n", "# Exponential reference\n", "xx = np.linspace(0, fids['cycle_depth'].max())\n", - "plt.plot(xx, (1-5e-3)**(4*xx), label=r'Exponential Reference')\n", + "plt.plot(xx, (1 - 5e-3) ** (4 * xx), label=r'Exponential Reference')\n", + "\n", "\n", "def _p(fids):\n", " plt.plot(fids['cycle_depth'], fids['fidelity'], 'o-', label=fids.name)\n", "\n", + "\n", "fids.name = 'Sampled'\n", "_p(fids)\n", "\n", @@ -270,6 +272,7 @@ "outputs": [], "source": [ "import multiprocessing\n", + "\n", "pool = multiprocessing.get_context('spawn').Pool()" ] }, @@ -282,18 +285,18 @@ "outputs": [], "source": [ "from cirq.experiments.xeb_fitting import (\n", - " parameterize_circuit, \n", - " characterize_phased_fsim_parameters_with_xeb, \n", + " parameterize_circuit,\n", + " characterize_phased_fsim_parameters_with_xeb,\n", " SqrtISwapXEBOptions,\n", ")\n", "\n", "# Set which angles we want to characterize (all)\n", "options = SqrtISwapXEBOptions(\n", - " characterize_theta = True,\n", - " characterize_zeta = True,\n", - " characterize_chi = True,\n", - " characterize_gamma = True,\n", - " characterize_phi = True\n", + " characterize_theta=True,\n", + " characterize_zeta=True,\n", + " characterize_chi=True,\n", + " characterize_gamma=True,\n", + " characterize_phi=True,\n", ")\n", "# Parameterize the sqrt(iswap)s in our circuit library\n", "pcircuits = [parameterize_circuit(circuit, options) for circuit in circuits]\n", @@ -306,8 +309,8 @@ " options,\n", " pool=pool,\n", " # ease tolerance so it converges faster:\n", - " fatol=5e-3, \n", - " xatol=5e-3\n", + " fatol=5e-3,\n", + " xatol=5e-3,\n", ")" ] }, @@ -342,6 +345,7 @@ "outputs": [], "source": [ "from cirq.experiments.xeb_fitting import before_and_after_characterization\n", + "\n", "before_after_df = before_and_after_characterization(fids, characterization_result)\n", "before_after_df" ] @@ -364,7 +368,7 @@ " xx = np.linspace(0, np.max(row['cycle_depths_0']))\n", " plt.plot(xx, exponential_decay(xx, a=row['a_0'], layer_fid=row['layer_fid_0']), color='red')\n", " plt.plot(xx, exponential_decay(xx, a=row['a_c'], layer_fid=row['layer_fid_c']), color='blue')\n", - " \n", + "\n", " plt.show()" ] } diff --git a/docs/noise/qcvv/parallel_xeb.ipynb b/docs/noise/qcvv/parallel_xeb.ipynb index 018c73b4297..bf1f7bd9366 100644 --- a/docs/noise/qcvv/parallel_xeb.ipynb +++ b/docs/noise/qcvv/parallel_xeb.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -115,8 +115,10 @@ "# Simulation\n", "qubits = cirq.GridQubit.rect(3, 2, 4, 3)\n", "result = cirq.experiments.parallel_two_qubit_xeb(\n", - " sampler=cirq.DensityMatrixSimulator(noise=cirq.depolarize(5e-3), dtype=np.complex128), # Any simulator or a ProcessorSampler.\n", - " qubits=qubits\n", + " sampler=cirq.DensityMatrixSimulator(\n", + " noise=cirq.depolarize(5e-3), dtype=np.complex128\n", + " ), # Any simulator or a ProcessorSampler.\n", + " qubits=qubits,\n", ")" ] }, @@ -128,9 +130,11 @@ }, "outputs": [], "source": [ - "# The returned result is an instance of the `TwoQubitXEBResult` class which provides visualization methods like \n", - "result.plot_heatmap(); # plot the heatmap of XEB errors\n", - "result.plot_fitted_exponential(*qubits[:2]); # plot the fitted model of xeb error of a qubit pair.\n", + "# The returned result is an instance of the `TwoQubitXEBResult` class which provides visualization methods like\n", + "result.plot_heatmap()\n", + "# plot the heatmap of XEB errors\n", + "result.plot_fitted_exponential(*qubits[:2])\n", + "# plot the fitted model of xeb error of a qubit pair.\n", "result.plot_histogram(); # plot a histogram of all xeb errors." ] }, @@ -182,9 +186,7 @@ "from cirq.experiments import random_quantum_circuit_generation as rqcg\n", "\n", "circuit_library = rqcg.generate_library_of_2q_circuits(\n", - " n_library_circuits=20, \n", - " two_qubit_gate=cirq.ISWAP**0.5,\n", - " random_state=52,\n", + " n_library_circuits=20, two_qubit_gate=cirq.ISWAP**0.5, random_state=52\n", ")\n", "print(len(circuit_library))" ] @@ -236,6 +238,7 @@ " graph = ccr.gridqubits_to_graph_device(qubits)\n", "else:\n", " import cirq_google as cg\n", + "\n", " sampler = cg.get_engine_sampler(device_name, gate_set_name='sqrt_iswap')\n", " device = cg.get_engine_device(device_name)\n", " qubits = sorted(device.qubits)\n", @@ -267,10 +270,7 @@ "outputs": [], "source": [ "combs_by_layer = rqcg.get_random_combinations_for_device(\n", - " n_library_circuits=len(circuit_library),\n", - " n_combinations=10,\n", - " device_graph=graph,\n", - " random_state=53,\n", + " n_library_circuits=len(circuit_library), n_combinations=10, device_graph=graph, random_state=53\n", ")\n", "combs_by_layer" ] @@ -293,13 +293,15 @@ }, "outputs": [], "source": [ - "fig, axes = plt.subplots(2,2, figsize=(9,6))\n", + "fig, axes = plt.subplots(2, 2, figsize=(9, 6))\n", "for comb_layer, ax in zip(combs_by_layer, axes.reshape(-1)):\n", " active_qubits = np.array(comb_layer.pairs).reshape(-1)\n", " colors = ['red' if q in active_qubits else 'blue' for q in graph.nodes]\n", " nx.draw_networkx(graph, pos=pos, node_color=colors, ax=ax)\n", - " nx.draw_networkx_edges(graph, pos=pos, edgelist=comb_layer.pairs, width=3, edge_color='red', ax=ax)\n", - " \n", + " nx.draw_networkx_edges(\n", + " graph, pos=pos, edgelist=comb_layer.pairs, width=3, edge_color='red', ax=ax\n", + " )\n", + "\n", "plt.tight_layout()" ] }, @@ -323,6 +325,7 @@ "outputs": [], "source": [ "from cirq.experiments.xeb_sampling import sample_2q_xeb_circuits\n", + "\n", "sampled_df = sample_2q_xeb_circuits(\n", " sampler=sampler,\n", " circuits=circuit_library,\n", @@ -352,10 +355,9 @@ "outputs": [], "source": [ "from cirq.experiments.xeb_fitting import benchmark_2q_xeb_fidelities\n", + "\n", "fids = benchmark_2q_xeb_fidelities(\n", - " sampled_df=sampled_df,\n", - " circuits=circuit_library,\n", - " cycle_depths=cycle_depths,\n", + " sampled_df=sampled_df, circuits=circuit_library, cycle_depths=cycle_depths\n", ")\n", "fids" ] @@ -369,6 +371,7 @@ "outputs": [], "source": [ "from cirq.experiments.xeb_fitting import fit_exponential_decays, exponential_decay\n", + "\n", "fidelities = fit_exponential_decays(fids)" ] }, @@ -420,13 +423,22 @@ "\n", "# Exponential reference\n", "xx = np.linspace(0, fids['cycle_depth'].max())\n", - "plt.plot(xx, (1-5e-3)**(4*xx), label=r'Exponential Reference', color='black')\n", + "plt.plot(xx, (1 - 5e-3) ** (4 * xx), label=r'Exponential Reference', color='black')\n", + "\n", "\n", "# Plot each pair\n", "def _p(fids):\n", " q0, q1 = fids.name\n", - " plt.plot(fids['cycle_depth'], fids['fidelity'], \n", - " 'o-', label=f'{q0}-{q1}', color=colors[fids.name], alpha=0.5)\n", + " plt.plot(\n", + " fids['cycle_depth'],\n", + " fids['fidelity'],\n", + " 'o-',\n", + " label=f'{q0}-{q1}',\n", + " color=colors[fids.name],\n", + " alpha=0.5,\n", + " )\n", + "\n", + "\n", "fids.groupby('pair').apply(_p)\n", "\n", "plt.ylabel('Circuit fidelity')\n", @@ -455,6 +467,7 @@ "outputs": [], "source": [ "import multiprocessing\n", + "\n", "pool = multiprocessing.get_context('spawn').Pool()" ] }, @@ -467,18 +480,18 @@ "outputs": [], "source": [ "from cirq.experiments.xeb_fitting import (\n", - " parameterize_circuit, \n", - " characterize_phased_fsim_parameters_with_xeb_by_pair, \n", + " parameterize_circuit,\n", + " characterize_phased_fsim_parameters_with_xeb_by_pair,\n", " SqrtISwapXEBOptions,\n", ")\n", "\n", "# Set which angles we want to characterize (all)\n", "options = SqrtISwapXEBOptions(\n", - " characterize_theta = True,\n", - " characterize_zeta = True,\n", - " characterize_chi = True,\n", - " characterize_gamma = True,\n", - " characterize_phi = True\n", + " characterize_theta=True,\n", + " characterize_zeta=True,\n", + " characterize_chi=True,\n", + " characterize_gamma=True,\n", + " characterize_phi=True,\n", ")\n", "# Parameterize the sqrt(iswap)s in our circuit library\n", "pcircuits = [parameterize_circuit(circuit, options) for circuit in circuit_library]\n", @@ -491,8 +504,8 @@ " options,\n", " pool=pool,\n", " # ease tolerance so it converges faster:\n", - " fatol=1e-2, \n", - " xatol=1e-2\n", + " fatol=1e-2,\n", + " xatol=1e-2,\n", ")" ] }, @@ -527,6 +540,7 @@ "outputs": [], "source": [ "from cirq.experiments.xeb_fitting import before_and_after_characterization\n", + "\n", "before_after_df = before_and_after_characterization(fids, characterization_result)\n", "before_after_df" ] @@ -545,11 +559,19 @@ " plt.plot(row['cycle_depths_c'], row['fidelities_c'], 'o', color='blue')\n", "\n", " xx = np.linspace(0, np.max(row['cycle_depths_0']))\n", - " plt.plot(xx, exponential_decay(xx, a=row['a_0'], layer_fid=row['layer_fid_0']), \n", - " color='red', label=f'f_0 = {row[\"layer_fid_0\"]:.3f}')\n", - " plt.plot(xx, exponential_decay(xx, a=row['a_c'], layer_fid=row['layer_fid_c']),\n", - " color='blue', label=f'f_c = {row[\"layer_fid_c\"]:.3f}')\n", - " \n", + " plt.plot(\n", + " xx,\n", + " exponential_decay(xx, a=row['a_0'], layer_fid=row['layer_fid_0']),\n", + " color='red',\n", + " label=f'f_0 = {row[\"layer_fid_0\"]:.3f}',\n", + " )\n", + " plt.plot(\n", + " xx,\n", + " exponential_decay(xx, a=row['a_c'], layer_fid=row['layer_fid_c']),\n", + " color='blue',\n", + " label=f'f_c = {row[\"layer_fid_c\"]:.3f}',\n", + " )\n", + "\n", " plt.xlabel('Cycle Depth')\n", " plt.ylabel('Fidelity')\n", " plt.legend(loc='best')\n", diff --git a/docs/noise/qcvv/xeb_calibration_example.ipynb b/docs/noise/qcvv/xeb_calibration_example.ipynb index a642da51038..0d5d5d6fd23 100644 --- a/docs/noise/qcvv/xeb_calibration_example.ipynb +++ b/docs/noise/qcvv/xeb_calibration_example.ipynb @@ -20,7 +20,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -129,14 +129,17 @@ "outputs": [], "source": [ "# The Google Cloud Project id to use.\n", - "project_id = \"\" #@param {type:\"string\"}\n", - "processor_id = \"\" #@param {type:\"string\"}\n", + "project_id = \"\" # @param {type:\"string\"}\n", + "processor_id = \"\" # @param {type:\"string\"}\n", "\n", "from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook\n", + "\n", "device_sampler = get_qcs_objects_for_notebook(project_id, processor_id)\n", "\n", "if not device_sampler.signed_in:\n", - " raise Exception(\"Please setup project_id in this cell or set the `GOOGLE_CLOUD_PROJECT` env var to your project id.\")" + " raise Exception(\n", + " \"Please setup project_id in this cell or set the `GOOGLE_CLOUD_PROJECT` env var to your project id.\"\n", + " )" ] }, { @@ -165,7 +168,7 @@ }, "outputs": [], "source": [ - "#@title Helper functions\n", + "# @title Helper functions\n", "from typing import Optional, Sequence\n", "\n", "\n", @@ -176,17 +179,17 @@ " seed: Optional[int] = None,\n", ") -> cirq.Circuit:\n", " return rqcg.random_rotations_between_grid_interaction_layers_circuit(\n", - " qubits, \n", + " qubits,\n", " depth=cycles,\n", " two_qubit_op_factory=lambda a, b, _: twoq_gate.on(a, b),\n", " pattern=cirq.experiments.GRID_STAGGERED_PATTERN,\n", - " single_qubit_gates=[cirq.PhasedXPowGate(phase_exponent=p, exponent=0.5)\n", - " for p in np.arange(-1.0, 1.0, 0.25)],\n", - " seed=seed\n", + " single_qubit_gates=[\n", + " cirq.PhasedXPowGate(phase_exponent=p, exponent=0.5) for p in np.arange(-1.0, 1.0, 0.25)\n", + " ],\n", + " seed=seed,\n", " )\n", "\n", "\n", - "\n", "def create_loschmidt_echo_circuit(\n", " qubits: Sequence[cirq.GridQubit],\n", " cycles: int,\n", @@ -206,7 +209,6 @@ " return forward + cirq.inverse(forward) + cirq.measure(*qubits, key=\"z\")\n", "\n", "\n", - "\n", "def to_ground_state_prob(result: cirq.Result) -> float:\n", " return np.mean(np.sum(result.measurements[\"z\"], axis=1) == 0)" ] @@ -261,26 +263,24 @@ } ], "source": [ - "processor_id = \"\" #@param {type:\"string\"}\n", - "metrics = \"parallel_p00_error, two_qubit_sqrt_iswap_gate_xeb_pauli_error_per_cycle\" #@param {type:\"string\"}\n", + "processor_id = \"\" # @param {type:\"string\"}\n", + "metrics = \"parallel_p00_error, two_qubit_sqrt_iswap_gate_xeb_pauli_error_per_cycle\" # @param {type:\"string\"}\n", "metrics = [m.strip() for m in metrics.split(sep=\",\")]\n", "\n", "from matplotlib.colors import LogNorm\n", "\n", "\n", - "_, axes = plt.subplots(\n", - " nrows=1, ncols=len(metrics), figsize=(min(16, 8 * len(metrics)), 7)\n", - ")\n", + "_, axes = plt.subplots(nrows=1, ncols=len(metrics), figsize=(min(16, 8 * len(metrics)), 7))\n", "\n", "\n", "calibration = cg.get_engine_calibration(processor_id=processor_id)\n", "for i, metric in enumerate(metrics):\n", " calibration.heatmap(metric).plot(\n", - " ax=axes[i] if len(metrics) > 1 else axes, \n", - " collection_options={\"norm\": LogNorm()}, \n", - " annotation_format=\"0.3f\", \n", - " annotation_text_kwargs = {\"size\": \"small\"}\n", - ");" + " ax=axes[i] if len(metrics) > 1 else axes,\n", + " collection_options={\"norm\": LogNorm()},\n", + " annotation_format=\"0.3f\",\n", + " annotation_text_kwargs={\"size\": \"small\"},\n", + " );" ] }, { @@ -301,10 +301,7 @@ "outputs": [], "source": [ "# Select qubit indices here.\n", - "qubit_indices = [\n", - " (2, 5), (2, 6), (2, 7), (2, 8), (3, 8), \n", - " (3, 7), (3, 6), (3, 5), (4, 5), (4, 6) \n", - "]\n", + "qubit_indices = [(2, 5), (2, 6), (2, 7), (2, 8), (3, 8), (3, 7), (3, 6), (3, 5), (4, 5), (4, 6)]\n", "qubits = [cirq.GridQubit(*idx) for idx in qubit_indices]" ] }, @@ -450,19 +447,19 @@ "outputs": [], "source": [ "\"\"\"Setup the Loschmidt echo experiment.\"\"\"\n", + "\n", "cycle_values = range(0, 40 + 1, 4)\n", "nreps = 20_000\n", "trials = 10\n", "\n", "sampler = cg.get_engine_sampler(\n", - " project_id=project_id,\n", - " processor_id=processor_id, \n", - " gate_set_name=\"sqrt_iswap\",\n", + " project_id=project_id, processor_id=processor_id, gate_set_name=\"sqrt_iswap\"\n", ")\n", "\n", "loschmidt_echo_batch = [\n", " create_loschmidt_echo_circuit(qubits, cycles=c, seed=trial)\n", - " for trial in range(trials) for c in cycle_values\n", + " for trial in range(trials)\n", + " for c in cycle_values\n", "]" ] }, @@ -496,9 +493,9 @@ "raw_results = sampler.run_batch(programs=loschmidt_echo_batch, repetitions=nreps)\n", "\n", "# Convert measurements to survival probabilities.\n", - "raw_probs = np.array(\n", - " [to_ground_state_prob(*res) for res in raw_results]\n", - ").reshape(trials, len(cycle_values))" + "raw_probs = np.array([to_ground_state_prob(*res) for res in raw_results]).reshape(\n", + " trials, len(cycle_values)\n", + ")" ] }, { @@ -539,7 +536,9 @@ ], "source": [ "# Get characterization requests.\n", - "characterization_requests = cg.prepare_characterization_for_operations(loschmidt_echo_batch, xeb_options)\n", + "characterization_requests = cg.prepare_characterization_for_operations(\n", + " loschmidt_echo_batch, xeb_options\n", + ")\n", "\n", "# Characterize the requests on the engine.\n", "characterizations = cg.run_calibrations(characterization_requests, sampler)\n", @@ -572,9 +571,9 @@ "xeb_results = sampler.run_batch(programs=xeb_calibrated_batch, repetitions=nreps)\n", "\n", "# Convert measurements to survival probabilities.\n", - "xeb_probs = np.array(\n", - " [to_ground_state_prob(*res) for res in xeb_results]\n", - ").reshape(trials, len(cycle_values))" + "xeb_probs = np.array([to_ground_state_prob(*res) for res in xeb_results]).reshape(\n", + " trials, len(cycle_values)\n", + ")" ] }, { diff --git a/docs/noise/qcvv/xeb_theory.ipynb b/docs/noise/qcvv/xeb_theory.ipynb index 417c0b44170..ba7bfd5551c 100644 --- a/docs/noise/qcvv/xeb_theory.ipynb +++ b/docs/noise/qcvv/xeb_theory.ipynb @@ -9,7 +9,7 @@ }, "outputs": [], "source": [ - "#@title Copyright 2021 The Cirq Developers\n", + "# @title Copyright 2021 The Cirq Developers\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", @@ -59,6 +59,7 @@ " print(\"installing cirq...\")\n", " !pip install --quiet cirq\n", " import cirq\n", + "\n", " print(\"installed cirq.\")" ] }, @@ -130,7 +131,7 @@ }, "outputs": [], "source": [ - "exponents = np.linspace(0, 7/4, 8)\n", + "exponents = np.linspace(0, 7 / 4, 8)\n", "exponents" ] }, @@ -143,6 +144,7 @@ "outputs": [], "source": [ "import itertools\n", + "\n", "SINGLE_QUBIT_GATES = [\n", " cirq.PhasedXZGate(x_exponent=0.5, z_exponent=z, axis_phase_exponent=a)\n", " for a, z in itertools.product(exponents, repeat=2)\n", @@ -174,10 +176,11 @@ "\n", "q0, q1 = cirq.LineQubit.range(2)\n", "circuit = rqcg.random_rotations_between_two_qubit_circuit(\n", - " q0, q1, \n", - " depth=4, \n", - " two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b), \n", - " single_qubit_gates=SINGLE_QUBIT_GATES\n", + " q0,\n", + " q1,\n", + " depth=4,\n", + " two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b),\n", + " single_qubit_gates=SINGLE_QUBIT_GATES,\n", ")\n", "SVGCircuit(circuit)" ] @@ -224,10 +227,12 @@ "N_CIRCUITS = 10\n", "circuits = [\n", " rqcg.random_rotations_between_two_qubit_circuit(\n", - " q0, q1, \n", - " depth=MAX_DEPTH, \n", - " two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b), \n", - " single_qubit_gates=SINGLE_QUBIT_GATES)\n", + " q0,\n", + " q1,\n", + " depth=MAX_DEPTH,\n", + " two_qubit_op_factory=lambda a, b, _: cirq.SQRT_ISWAP(a, b),\n", + " single_qubit_gates=SINGLE_QUBIT_GATES,\n", + " )\n", " for _ in range(N_CIRCUITS)\n", "]" ] @@ -276,7 +281,7 @@ "records = []\n", "for cycle_depth in cycle_depths:\n", " for circuit_i, circuit in enumerate(circuits):\n", - " \n", + "\n", " # Truncate the long circuit to the requested cycle_depth\n", " circuit_depth = cycle_depth * 2 + 1\n", " assert circuit_depth <= len(circuit)\n", @@ -284,21 +289,23 @@ "\n", " # Pure-state simulation\n", " psi = pure_sim.simulate(trunc_circuit).final_state_vector\n", - " pure_probs = np.abs(psi)**2\n", + " pure_probs = np.abs(psi) ** 2\n", "\n", " # Noisy execution\n", " meas_circuit = trunc_circuit + cirq.measure(q0, q1)\n", - " sampled_inds = noisy_sim.sample(meas_circuit, repetitions=10_000).values[:,0]\n", + " sampled_inds = noisy_sim.sample(meas_circuit, repetitions=10_000).values[:, 0]\n", " sampled_probs = np.bincount(sampled_inds, minlength=DIM) / len(sampled_inds)\n", "\n", " # Save the results\n", - " records += [{\n", - " 'circuit_i': circuit_i,\n", - " 'cycle_depth': cycle_depth,\n", - " 'circuit_depth': circuit_depth,\n", - " 'pure_probs': pure_probs,\n", - " 'sampled_probs': sampled_probs,\n", - " }]\n", + " records += [\n", + " {\n", + " 'circuit_i': circuit_i,\n", + " 'cycle_depth': cycle_depth,\n", + " 'circuit_depth': circuit_depth,\n", + " 'pure_probs': pure_probs,\n", + " 'sampled_probs': sampled_probs,\n", + " }\n", + " ]\n", " print('.', end='', flush=True)" ] }, @@ -354,14 +361,10 @@ "outputs": [], "source": [ "for record in records:\n", - " e_u = np.sum(record['pure_probs']**2)\n", + " e_u = np.sum(record['pure_probs'] ** 2)\n", " u_u = np.sum(record['pure_probs']) / DIM\n", " m_u = np.sum(record['pure_probs'] * record['sampled_probs'])\n", - " record.update(\n", - " e_u=e_u,\n", - " u_u=u_u,\n", - " m_u=m_u, \n", - " )" + " record.update(e_u=e_u, u_u=u_u, m_u=m_u)" ] }, { @@ -400,6 +403,7 @@ "outputs": [], "source": [ "import pandas as pd\n", + "\n", "df = pd.DataFrame(records)\n", "df['y'] = df['m_u'] - df['u_u']\n", "df['x'] = df['e_u'] - df['u_u']\n", @@ -433,27 +437,31 @@ "\n", "# Color by cycle depth\n", "import seaborn as sns\n", - "colors = sns.cubehelix_palette(n_colors=len(cycle_depths)) \n", + "\n", + "colors = sns.cubehelix_palette(n_colors=len(cycle_depths))\n", "colors = {k: colors[i] for i, k in enumerate(cycle_depths)}\n", "\n", "_lines = []\n", + "\n", + "\n", "def per_cycle_depth(df):\n", " fid_lsq = df['numerator'].sum() / df['denominator'].sum()\n", - " \n", - " cycle_depth = df.name \n", + "\n", + " cycle_depth = df.name\n", " xx = np.linspace(0, df['x'].max())\n", - " l, = plt.plot(xx, fid_lsq*xx, color=colors[cycle_depth])\n", + " (l,) = plt.plot(xx, fid_lsq * xx, color=colors[cycle_depth])\n", " plt.scatter(df['x'], df['y'], color=colors[cycle_depth])\n", - " \n", + "\n", " global _lines\n", - " _lines += [l] # for legend\n", + " _lines += [l] # for legend\n", " return pd.Series({'fidelity': fid_lsq})\n", "\n", + "\n", "fids = df.groupby('cycle_depth').apply(per_cycle_depth).reset_index()\n", "plt.xlabel(r'$e_U - u_U$', fontsize=18)\n", "plt.ylabel(r'$m_U - u_U$', fontsize=18)\n", "_lines = np.asarray(_lines)\n", - "plt.legend(_lines[[0,-1]], cycle_depths[[0,-1]], loc='best', title='Cycle depth')\n", + "plt.legend(_lines[[0, -1]], cycle_depths[[0, -1]], loc='best', title='Cycle depth')\n", "plt.tight_layout()" ] }, @@ -474,11 +482,7 @@ }, "outputs": [], "source": [ - "plt.plot(\n", - " fids['cycle_depth'], \n", - " fids['fidelity'],\n", - " marker='o',\n", - " label='Least Squares')\n", + "plt.plot(fids['cycle_depth'], fids['fidelity'], marker='o', label='Least Squares')\n", "\n", "xx = np.linspace(0, fids['cycle_depth'].max())\n", "\n", @@ -486,12 +490,12 @@ "# related to (but not equal to) the Pauli error.\n", "# For the latter, an error involves doing X, Y, or Z with E_PAULI/3\n", "# but for the former, an error involves doing I, X, Y, or Z with e_depol/4\n", - "e_depol = E_PAULI / (1 - 1/DIM**2)\n", + "e_depol = E_PAULI / (1 - 1 / DIM**2)\n", "\n", "# The additional factor of four in the exponent is because each layer\n", "# involves two moments of two qubits (so each layer has four applications\n", "# of a single-qubit single-moment depolarizing channel).\n", - "plt.plot(xx, (1-e_depol)**(4*xx), label=r'$(1-\\mathrm{e\\_depol})^{4d}$')\n", + "plt.plot(xx, (1 - e_depol) ** (4 * xx), label=r'$(1-\\mathrm{e\\_depol})^{4d}$')\n", "\n", "plt.ylabel('Circuit fidelity', fontsize=18)\n", "plt.xlabel('Cycle Depth $d$', fontsize=18)\n", diff --git a/docs/noise/representing_noise.ipynb b/docs/noise/representing_noise.ipynb index fe88b344e86..36f9564479f 100644 --- a/docs/noise/representing_noise.ipynb +++ b/docs/noise/representing_noise.ipynb @@ -9,7 +9,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -121,10 +121,7 @@ "outputs": [], "source": [ "q0 = cirq.LineQubit(0)\n", - "circuit = cirq.Circuit(\n", - " cirq.bit_flip(p=0.2).on(q0),\n", - " cirq.measure(q0, key='result')\n", - ")\n", + "circuit = cirq.Circuit(cirq.bit_flip(p=0.2).on(q0), cirq.measure(q0, key='result'))\n", "result = cirq.Simulator(seed=0).run(circuit, repetitions=1000)\n", "print(result.histogram(key='result'))" ] @@ -161,9 +158,7 @@ "source": [ "q0 = cirq.LineQubit(0)\n", "circuit = cirq.Circuit(\n", - " cirq.X(q0),\n", - " cirq.amplitude_damp(gamma=0.2).on(q0),\n", - " cirq.measure(q0, key='result')\n", + " cirq.X(q0), cirq.amplitude_damp(gamma=0.2).on(q0), cirq.measure(q0, key='result')\n", ")\n", "result = cirq.Simulator(seed=0).run(circuit, repetitions=1000)\n", "print(result.histogram(key='result'))" @@ -232,10 +227,7 @@ "source": [ "q0 = cirq.LineQubit(0)\n", "circuit = cirq.Circuit(\n", - " cirq.H(q0),\n", - " cirq.phase_flip(p=0.2).on(q0),\n", - " cirq.H(q0),\n", - " cirq.measure(q0, key='result')\n", + " cirq.H(q0), cirq.phase_flip(p=0.2).on(q0), cirq.H(q0), cirq.measure(q0, key='result')\n", ")\n", "result = cirq.Simulator(seed=0).run(circuit, repetitions=1000)\n", "print(\"Phase flip:\", result.histogram(key='result'))" @@ -264,10 +256,7 @@ "gamma = 1 - (2 * p - 1) ** 2\n", "print(f\"{gamma=}\")\n", "circuit = cirq.Circuit(\n", - " cirq.H(q0),\n", - " cirq.phase_damp(gamma=gamma).on(q0),\n", - " cirq.H(q0),\n", - " cirq.measure(q0, key='result')\n", + " cirq.H(q0), cirq.phase_damp(gamma=gamma).on(q0), cirq.H(q0), cirq.measure(q0, key='result')\n", ")\n", "result = cirq.Simulator(seed=0).run(circuit, repetitions=1000)\n", "print(\"Phase damp:\", result.histogram(key='result'))" @@ -383,11 +372,7 @@ "outputs": [], "source": [ "q0 = cirq.LineQubit(0)\n", - "circuit = cirq.Circuit(\n", - " cirq.bit_flip(p=0.2).on(q0),\n", - " cirq.reset(q0),\n", - " cirq.measure(q0, key='result')\n", - ")\n", + "circuit = cirq.Circuit(cirq.bit_flip(p=0.2).on(q0), cirq.reset(q0), cirq.measure(q0, key='result'))\n", "result = cirq.Simulator(seed=0).run(circuit, repetitions=1000)\n", "print(result.histogram(key='result'))" ] @@ -414,13 +399,9 @@ "q0 = cirq.LineQubit(0)\n", "# equivalent to cirq.bit_flip(p=0.2)\n", "my_channel = cirq.MixedUnitaryChannel(\n", - " [(0.8, cirq.unitary(cirq.I)), (0.2, cirq.unitary(cirq.X))],\n", - " key='op_num',\n", - ")\n", - "circuit = cirq.Circuit(\n", - " my_channel.on(q0),\n", - " cirq.measure(q0, key='result')\n", + " [(0.8, cirq.unitary(cirq.I)), (0.2, cirq.unitary(cirq.X))], key='op_num'\n", ")\n", + "circuit = cirq.Circuit(my_channel.on(q0), cirq.measure(q0, key='result'))\n", "result = cirq.Simulator(seed=0).run(circuit, repetitions=20)\n", "# `op_num` and `result` are always equal.\n", "print(result)" @@ -450,16 +431,12 @@ "gamma = 0.2\n", "my_channel = cirq.KrausChannel(\n", " [\n", - " np.array([[0, np.sqrt(gamma)], [0, 0]]), # decay |1) -> |0)\n", - " np.array([[1, 0], [0, np.sqrt(1-gamma)]]), # stay in |1)\n", + " np.array([[0, np.sqrt(gamma)], [0, 0]]), # decay |1) -> |0)\n", + " np.array([[1, 0], [0, np.sqrt(1 - gamma)]]), # stay in |1)\n", " ],\n", " key='op_num',\n", ")\n", - "circuit = cirq.Circuit(\n", - " cirq.X(q0),\n", - " my_channel.on(q0),\n", - " cirq.measure(q0, key='result')\n", - ")\n", + "circuit = cirq.Circuit(cirq.X(q0), my_channel.on(q0), cirq.measure(q0, key='result'))\n", "result = cirq.Simulator(seed=0).run(circuit, repetitions=20)\n", "# `op_num` and `result` are always equal.\n", "print(result)" @@ -508,9 +485,7 @@ "source": [ "q0 = cirq.LineQubit(0)\n", "circuit = cirq.Circuit(\n", - " cirq.I(q0),\n", - " cirq.measure(q0, key='result_0'),\n", - " cirq.measure(q0, key='result_1'),\n", + " cirq.I(q0), cirq.measure(q0, key='result_0'), cirq.measure(q0, key='result_1')\n", ")\n", "# Applies noise after every gate, even measurements.\n", "noisy_circuit = circuit.with_noise(cirq.X)\n", @@ -551,11 +526,7 @@ "from cirq.devices import InsertionNoiseModel\n", "\n", "q0 = cirq.LineQubit(0)\n", - "circuit = cirq.Circuit(\n", - " cirq.I(q0),\n", - " cirq.X(q0),\n", - " cirq.measure(q0, key='result'),\n", - ")\n", + "circuit = cirq.Circuit(cirq.I(q0), cirq.X(q0), cirq.measure(q0, key='result'))\n", "# Apply bitflip noise after each X gate.\n", "target_op = cirq.OpIdentifier(cirq.XPowGate, q0)\n", "insert_op = cirq.bit_flip(p=0.2).on(q0)\n", @@ -602,10 +573,7 @@ "outputs": [], "source": [ "q0 = cirq.LineQubit(0)\n", - "circuit = cirq.Circuit(\n", - " cirq.X(q0),\n", - " cirq.measure(q0, key='result', invert_mask=[True])\n", - ")\n", + "circuit = cirq.Circuit(cirq.X(q0), cirq.measure(q0, key='result', invert_mask=[True]))\n", "result = cirq.Simulator(seed=0).run(circuit, repetitions=1000)\n", "print(result.histogram(key='result'))" ] @@ -643,10 +611,7 @@ "q0 = cirq.LineQubit(0)\n", "# 10% chance to report |0) as |1), 20% chance to report |1) as |0).\n", "cmap = {(0,): np.array([[0.9, 0.1], [0.2, 0.8]])}\n", - "circuit = cirq.Circuit(\n", - " cirq.X(q0),\n", - " cirq.measure(q0, key='result', confusion_map=cmap)\n", - ")\n", + "circuit = cirq.Circuit(cirq.X(q0), cirq.measure(q0, key='result', confusion_map=cmap))\n", "result = cirq.Simulator(seed=0).run(circuit, repetitions=1000)\n", "print(result.histogram(key='result'))" ] diff --git a/docs/simulate/noisy_simulation.ipynb b/docs/simulate/noisy_simulation.ipynb index ba27b94c9b2..fcc77206339 100644 --- a/docs/simulate/noisy_simulation.ipynb +++ b/docs/simulate/noisy_simulation.ipynb @@ -178,6 +178,7 @@ "outputs": [], "source": [ "\"\"\"Example of using channels in a circuit.\"\"\"\n", + "\n", "# See the number of qubits a channel acts on.\n", "nqubits = bit_flip.num_qubits()\n", "print(f\"Bit flip channel acts on {nqubits} qubit(s).\\n\")\n", @@ -205,6 +206,7 @@ "outputs": [], "source": [ "\"\"\"Example of controlling a channel.\"\"\"\n", + "\n", "# Get the controlled channel.\n", "controlled_bit_flip = bit_flip.controlled(num_controls=1)\n", "\n", @@ -260,6 +262,7 @@ "outputs": [], "source": [ "\"\"\"Get an asymmetric depolarizing channel.\"\"\"\n", + "\n", "depo = cirq.asymmetric_depolarize(p_x=0.10, p_y=0.05, p_z=0.15)\n", "\n", "circuit = cirq.Circuit(depo(cirq.LineQubit(0)))\n", @@ -305,6 +308,7 @@ "outputs": [], "source": [ "\"\"\"Example of using the mixture protocol.\"\"\"\n", + "\n", "for prob, kraus in cirq.mixture(bit_flip):\n", " print(f\"With probability {prob}, apply\\n\", kraus, end=\"\\n\\n\")" ] @@ -335,6 +339,7 @@ "outputs": [], "source": [ "\"\"\"The amplitude damping channel is an example of a channel without a mixture.\"\"\"\n", + "\n", "channel = cirq.amplitude_damp(0.1)\n", "\n", "if cirq.has_mixture(channel):\n", @@ -508,6 +513,7 @@ "outputs": [], "source": [ "\"\"\"Custom channels can be used like any other channels.\"\"\"\n", + "\n", "bit_phase_flip = BitAndPhaseFlipChannel(p=0.05)\n", "\n", "for prob, kraus in cirq.mixture(bit_phase_flip):\n", @@ -541,6 +547,7 @@ "outputs": [], "source": [ "\"\"\"Example of using a custom channel in a circuit.\"\"\"\n", + "\n", "circuit = cirq.Circuit(bit_phase_flip.on_each(*cirq.LineQubit.range(3)))\n", "circuit" ] @@ -572,6 +579,7 @@ "outputs": [], "source": [ "\"\"\"Create a channel with Gate.with_probability.\"\"\"\n", + "\n", "channel = cirq.Y.with_probability(probability=0.05)" ] }, @@ -641,6 +649,7 @@ "outputs": [], "source": [ "\"\"\"Simulating a circuit with the density matrix simulator.\"\"\"\n", + "\n", "# Get a circuit.\n", "qbit = cirq.GridQubit(0, 0)\n", "circuit = cirq.Circuit(cirq.X(qbit), cirq.amplitude_damp(0.1).on(qbit))\n", @@ -696,6 +705,7 @@ "outputs": [], "source": [ "\"\"\"Simulating a noisy circuit via Monte Carlo simulation.\"\"\"\n", + "\n", "# Get a circuit.\n", "qbit = cirq.NamedQubit(\"Q\")\n", "circuit = cirq.Circuit(cirq.bit_flip(p=0.5).on(qbit))\n", @@ -731,6 +741,7 @@ "outputs": [], "source": [ "\"\"\"Example of Monte Carlo wavefunction simulation with the `run` method.\"\"\"\n", + "\n", "circuit = cirq.Circuit(cirq.bit_flip(p=0.5).on(qbit), cirq.measure(qbit))\n", "res = sim.run(circuit, repetitions=100)\n", "print(res.histogram(key=qbit))" @@ -772,6 +783,7 @@ "outputs": [], "source": [ "\"\"\"One method to insert noise in a circuit.\"\"\"\n", + "\n", "# Define some noiseless circuit.\n", "circuit = cirq.testing.random_circuit(qubits=3, n_moments=3, op_density=1, random_state=11)\n", "\n", @@ -814,6 +826,7 @@ "outputs": [], "source": [ "\"\"\"Add noise to an operation, moment, or sequence of moments.\"\"\"\n", + "\n", "# Create a noise model.\n", "noise_model = cirq.NoiseModel.from_noise_model_like(cirq.depolarize(p=0.01))\n", "\n", @@ -860,6 +873,7 @@ "outputs": [], "source": [ "\"\"\"Creating a circuit from a noisy cirq.OP_TREE.\"\"\"\n", + "\n", "cirq.Circuit(noisy_moment)" ] }, @@ -881,6 +895,7 @@ "outputs": [], "source": [ "\"\"\"Define a density matrix simulator with a `cirq.NOISE_MODEL_LIKE` object.\"\"\"\n", + "\n", "noisy_dsim = cirq.DensityMatrixSimulator(noise=cirq.generalized_amplitude_damp(p=0.1, gamma=0.5))" ] }, @@ -911,6 +926,7 @@ "outputs": [], "source": [ "\"\"\"Defining a circuit with multiple noisy channels.\"\"\"\n", + "\n", "qreg = cirq.LineQubit.range(4)\n", "circ = cirq.Circuit(\n", " cirq.H.on_each(qreg),\n", @@ -945,6 +961,7 @@ "outputs": [], "source": [ "\"\"\"Example of inserting channels in circuits.\"\"\"\n", + "\n", "circ.insert(0, cirq.bit_flip(p=0.1).on_each(qreg))\n", "print(circ)" ] diff --git a/docs/simulate/params.ipynb b/docs/simulate/params.ipynb index b0c6ed7c387..fad8a62022d 100644 --- a/docs/simulate/params.ipynb +++ b/docs/simulate/params.ipynb @@ -102,10 +102,10 @@ "source": [ "q0 = cirq.LineQubit(0)\n", "\n", - "circuit1 = cirq.Circuit([cirq.H(q0), cirq.Z(q0)**0.5, cirq.H(q0), cirq.measure(q0)])\n", + "circuit1 = cirq.Circuit([cirq.H(q0), cirq.Z(q0) ** 0.5, cirq.H(q0), cirq.measure(q0)])\n", "print(f\"circuit1:\\n{circuit1}\")\n", "\n", - "circuit2 = cirq.Circuit([cirq.H(q0), cirq.Z(q0)**0.25, cirq.H(q0), cirq.measure(q0)])\n", + "circuit2 = cirq.Circuit([cirq.H(q0), cirq.Z(q0) ** 0.25, cirq.H(q0), cirq.measure(q0)])\n", "print(f\"circuit2:\\n{circuit2}\")" ] }, @@ -132,7 +132,7 @@ "\n", "theta = sympy.Symbol(\"theta\")\n", "\n", - "circuit = cirq.Circuit([cirq.H(q0), cirq.Z(q0)**theta, cirq.H(q0), cirq.measure(q0)])\n", + "circuit = cirq.Circuit([cirq.H(q0), cirq.Z(q0) ** theta, cirq.H(q0), cirq.measure(q0)])\n", "print(f\"circuit:\\n{circuit}\")" ] }, @@ -153,9 +153,7 @@ }, "outputs": [], "source": [ - "circuit = cirq.Circuit(\n", - " cirq.H(q0), cirq.ZPowGate(exponent=theta)(q0), cirq.H(q0), cirq.measure(q0)\n", - ")\n", + "circuit = cirq.Circuit(cirq.H(q0), cirq.ZPowGate(exponent=theta)(q0), cirq.H(q0), cirq.measure(q0))\n", "print(f\"circuit:\\n{circuit}\")" ] }, @@ -379,7 +377,7 @@ "outputs": [], "source": [ "# Use the expression in the circuit:\n", - "circuit = cirq.Circuit(cirq.X(q0)**expr, cirq.measure(q0))\n", + "circuit = cirq.Circuit(cirq.X(q0) ** expr, cirq.measure(q0))\n", "print(f\"circuit:\\n{circuit}\")" ] }, @@ -443,7 +441,7 @@ }, "outputs": [], "source": [ - "print(sympy.cos(sympy.Symbol(\"a\"))**sympy.Symbol(\"b\"))" + "print(sympy.cos(sympy.Symbol(\"a\")) ** sympy.Symbol(\"b\"))" ] }, { @@ -477,7 +475,7 @@ "outputs": [], "source": [ "a = sympy.Symbol('a')\n", - "circuit = cirq.Circuit(cirq.X(q0)**(a / 4), cirq.Y(q0)**(1 - a / 2), cirq.measure(q0))\n", + "circuit = cirq.Circuit(cirq.X(q0) ** (a / 4), cirq.Y(q0) ** (1 - a / 2), cirq.measure(q0))\n", "print(circuit)" ] }, diff --git a/docs/simulate/qvm_stabilizer_example.ipynb b/docs/simulate/qvm_stabilizer_example.ipynb index 319392c0722..0789ace0eab 100644 --- a/docs/simulate/qvm_stabilizer_example.ipynb +++ b/docs/simulate/qvm_stabilizer_example.ipynb @@ -370,7 +370,7 @@ "source": [ "# A labeling function.\n", "def fold_func(bits) -> str:\n", - " suffix = \"\".join(map(str, [bits[i][0] for i in range(1,5)]))\n", + " suffix = \"\".join(map(str, [bits[i][0] for i in range(1, 5)]))\n", " return f\"{bits[0][0]}_{suffix}\"\n", "\n", "\n", diff --git a/docs/simulate/state_histograms.ipynb b/docs/simulate/state_histograms.ipynb index 93c9a381dea..6f761cc20f1 100644 --- a/docs/simulate/state_histograms.ipynb +++ b/docs/simulate/state_histograms.ipynb @@ -125,7 +125,13 @@ "outputs": [], "source": [ "q = cirq.LineQubit.range(6)\n", - "circuit = cirq.Circuit([cirq.H(q[0]), [cirq.CNOT(q[0], q[i]) for i in range(1, 6, 1)], cirq.measure(*q, key='measure_all')])\n", + "circuit = cirq.Circuit(\n", + " [\n", + " cirq.H(q[0]),\n", + " [cirq.CNOT(q[0], q[i]) for i in range(1, 6, 1)],\n", + " cirq.measure(*q, key='measure_all'),\n", + " ]\n", + ")\n", "result = cirq.Simulator().run(circuit, repetitions=100)\n", "_ = cirq.plot_state_histogram(result, plt.subplot())\n", "plt.show()" @@ -149,7 +155,7 @@ }, "outputs": [], "source": [ - "histogram = result.histogram(key = 'measure_all')\n", + "histogram = result.histogram(key='measure_all')\n", "_ = cirq.plot_state_histogram(histogram, plt.subplot())\n", "plt.show()" ] @@ -177,12 +183,13 @@ "def count_ones(bits):\n", " return 'even' if sum(bits) % 2 == 0 else 'odd'\n", "\n", + "\n", "q = cirq.LineQubit.range(6)\n", "# Uniform superposition over all 2 ** 6 states.\n", "circuit = cirq.Circuit([cirq.H.on_each(*q), cirq.measure(*q, key='measure_all')])\n", "result = cirq.Simulator().run(circuit, repetitions=100)\n", "# Create a customized histogram by processing the measurement results using `fold_func`.\n", - "custom_histogram = result.histogram(key = 'measure_all', fold_func=count_ones)\n", + "custom_histogram = result.histogram(key='measure_all', fold_func=count_ones)\n", "# Plot the custom histogram using cirq.plot_state_histogram\n", "_ = cirq.plot_state_histogram(custom_histogram, plt.subplot())\n", "plt.show()" @@ -207,12 +214,20 @@ "outputs": [], "source": [ "def binary_labels(num_qubits):\n", - " return [bin(x)[2:].zfill(num_qubits) for x in range(2 ** num_qubits)]\n", + " return [bin(x)[2:].zfill(num_qubits) for x in range(2**num_qubits)]\n", + "\n", "\n", "q = cirq.LineQubit.range(3)\n", "circuit = cirq.Circuit([cirq.H.on_each(*q), cirq.measure(*q)])\n", "result = cirq.Simulator().run(circuit, repetitions=100)\n", - "_ = cirq.plot_state_histogram(result, plt.subplot(), title = 'Custom Plot Title', xlabel = 'Custom X-Axis Label', ylabel = 'Custom Y-Axis Label', tick_label=binary_labels(3))\n", + "_ = cirq.plot_state_histogram(\n", + " result,\n", + " plt.subplot(),\n", + " title='Custom Plot Title',\n", + " xlabel='Custom X-Axis Label',\n", + " ylabel='Custom Y-Axis Label',\n", + " tick_label=binary_labels(3),\n", + ")\n", "plt.show()" ] } diff --git a/docs/start/intro.ipynb b/docs/start/intro.ipynb index d71beb51d9f..767462b0bef 100644 --- a/docs/start/intro.ipynb +++ b/docs/start/intro.ipynb @@ -126,6 +126,7 @@ "outputs": [], "source": [ "\"\"\"Test successful installation by printing out the Sycamore device.\"\"\"\n", + "\n", "import cirq_google\n", "\n", "print(cirq_google.Sycamore)" @@ -210,6 +211,7 @@ "outputs": [], "source": [ "\"\"\"Creating a circuit.\"\"\"\n", + "\n", "# Define three qubits.\n", "a = cirq.NamedQubit(\"a\")\n", "b = cirq.NamedQubit(\"b\")\n", @@ -318,6 +320,7 @@ "outputs": [], "source": [ "\"\"\"Get the unitary of a gate, here the Hadamard gate.\"\"\"\n", + "\n", "cirq.unitary(cirq.H)" ] }, @@ -356,6 +359,7 @@ "outputs": [], "source": [ "\"\"\"Print out the moments in a circuit.\"\"\"\n", + "\n", "print(\"Circuit:\\n\")\n", "print(circuit)\n", "\n", @@ -383,6 +387,7 @@ "outputs": [], "source": [ "\"\"\"Print the repr of a circuit.\"\"\"\n", + "\n", "print(repr(circuit))" ] }, @@ -572,6 +577,7 @@ "outputs": [], "source": [ "\"\"\"Appending operations with InsertStrategy.EARLIEST.\"\"\"\n", + "\n", "# Create an empty circuit.\n", "circuit = cirq.Circuit()\n", "\n", @@ -626,6 +632,7 @@ "outputs": [], "source": [ "\"\"\"Appending operations with InsertStrategy.NEW_THEN_INLINE.\"\"\"\n", + "\n", "# Create an empty circuit.\n", "circuit = cirq.Circuit()\n", "\n", @@ -777,6 +784,7 @@ "outputs": [], "source": [ "\"\"\"Example of simulating a circuit in Cirq.\"\"\"\n", + "\n", "# Get a simulator.\n", "simulator = cirq.Simulator()\n", "\n", @@ -817,6 +825,7 @@ "outputs": [], "source": [ "\"\"\"Simulating a circuit with the `simulate` method.\"\"\"\n", + "\n", "# Get a circuit without measurements.\n", "circuit = cirq.Circuit(basic_circuit(measure=False))\n", "\n", @@ -892,6 +901,7 @@ "outputs": [], "source": [ "\"\"\"Simulate a circuit using 1000 repetitions.\"\"\"\n", + "\n", "# Get a circuit with terminal measurements to simulate.\n", "circuit = cirq.Circuit(basic_circuit())\n", "\n", @@ -1036,6 +1046,7 @@ "outputs": [], "source": [ "\"\"\"Store the operations to query each function in a dictionary.\"\"\"\n", + "\n", "# Get qubits for the operations to act on.\n", "q0, q1 = cirq.LineQubit.range(2)\n", "\n", @@ -1134,6 +1145,7 @@ "outputs": [], "source": [ "\"\"\"Simulate each of the circuits.\"\"\"\n", + "\n", "simulator = cirq.Simulator()\n", "for key, oracle in oracles.items():\n", " result = simulator.run(cirq.Circuit(deutsch_algorithm(oracle)), repetitions=10)\n", @@ -1181,6 +1193,7 @@ "\"\"\"Operations to query all possible functions on two bits.\n", "Two of these functions are constant, and six of these functions are balanced.\n", "\"\"\"\n", + "\n", "# Define three qubits to use.\n", "q0, q1, q2 = cirq.LineQubit.range(3)\n", "\n", @@ -1217,7 +1230,7 @@ "outputs": [], "source": [ "# @title Attempt the solution here\n", - "\"\"\"Exercise: Write a quantum circuit that can distinguish \n", + "\"\"\"Exercise: Write a quantum circuit that can distinguish\n", "constant from balanced functions on two bits.\n", "\"\"\"\n", "\n", @@ -1247,6 +1260,7 @@ "outputs": [], "source": [ "\"\"\"Check your answer by running this cell.\"\"\"\n", + "\n", "simulator = cirq.Simulator()\n", "\n", "print(\"\\nYour result on constant functions:\")\n", @@ -1306,6 +1320,7 @@ "outputs": [], "source": [ "\"\"\"Simulate the Deutsch-Jozsa circuit and check the results.\"\"\"\n", + "\n", "print(\"Result on constant functions:\")\n", "for oracle in constant:\n", " result = simulator.run(cirq.Circuit(dj_circuit(oracle)), repetitions=10)\n", @@ -1353,6 +1368,7 @@ "outputs": [], "source": [ "\"\"\"Examples of common gates defined in Cirq.\"\"\"\n", + "\n", "# Get some qubits.\n", "q0, q1, q2 = cirq.LineQubit.range(3)\n", "\n", @@ -1399,6 +1415,7 @@ "outputs": [], "source": [ "\"\"\"Get the unitary of CNOT.\"\"\"\n", + "\n", "print(cirq.unitary(cirq.CNOT))" ] }, @@ -1434,6 +1451,7 @@ "outputs": [], "source": [ "\"\"\"Plot the probability of measuring a qubit in the ground state.\"\"\"\n", + "\n", "# Get a qubit.\n", "a = cirq.NamedQubit('a')\n", "\n", @@ -1474,6 +1492,7 @@ "outputs": [], "source": [ "\"\"\"Plot the probability of measuring a qubit in the ground state by sampling.\"\"\"\n", + "\n", "# Number of times to sample.\n", "repetitions = 100\n", "\n", @@ -1563,6 +1582,7 @@ "outputs": [], "source": [ "\"\"\"Using the custom gate in a circuit.\"\"\"\n", + "\n", "a = cirq.NamedQubit('a')\n", "rg = RationalGate()\n", "print(cirq.Circuit(rg(a)))" @@ -1606,6 +1626,7 @@ "outputs": [], "source": [ "\"\"\"Simulate a circuit with a custom gate.\"\"\"\n", + "\n", "circuit = cirq.Circuit(rg(a))\n", "simulator = cirq.Simulator()\n", "result = simulator.simulate(circuit)\n", @@ -1736,6 +1757,7 @@ "outputs": [], "source": [ "\"\"\"Display a circuit with the custom gate.\"\"\"\n", + "\n", "# Get qubits.\n", "a = cirq.NamedQubit('a')\n", "b = cirq.NamedQubit('b')\n", @@ -1807,6 +1829,7 @@ "outputs": [], "source": [ "\"\"\"Use the gate in a circuit.\"\"\"\n", + "\n", "HX = HXGate()\n", "\n", "a = cirq.NamedQubit('a')\n", @@ -1833,6 +1856,7 @@ "outputs": [], "source": [ "\"\"\"Decompose the gate.\"\"\"\n", + "\n", "print(cirq.Circuit(cirq.decompose(circuit)))" ] }, @@ -1854,6 +1878,7 @@ "outputs": [], "source": [ "\"\"\"Decompose the gate once.\"\"\"\n", + "\n", "print(cirq.Circuit(cirq.decompose_once(HX(a))))" ] }, @@ -1925,6 +1950,7 @@ "outputs": [], "source": [ "\"\"\"Define a circuit with parameterized gates.\"\"\"\n", + "\n", "# Import sympy for parameterized values.\n", "import sympy as sp\n", "\n", @@ -1961,6 +1987,7 @@ "outputs": [], "source": [ "\"\"\"Simulate the circuit at multiple parameter values.\"\"\"\n", + "\n", "simulator = cirq.Simulator()\n", "\n", "# Simulate the circuit for several values of the parameter.\n", @@ -1990,6 +2017,7 @@ "outputs": [], "source": [ "\"\"\"Simulate the circuit at multiple parameter values.\"\"\"\n", + "\n", "# Get a list of param resolvers.\n", "num_params = 5\n", "resolvers = [cirq.ParamResolver({'s': y / 8.0}) for y in range(num_params)]\n", @@ -2044,6 +2072,7 @@ "outputs": [], "source": [ "\"\"\"Alternative method of getting a sequence of param resolvers.\"\"\"\n", + "\n", "linspace = cirq.Linspace(start=0, stop=1.0, length=11, key='x')\n", "for p in linspace:\n", " print(p)" @@ -2157,6 +2186,7 @@ "outputs": [], "source": [ "\"\"\"Create a circuit with a depolarizing channel.\"\"\"\n", + "\n", "circuit = cirq.Circuit(cirq.depolarize(0.2)(a), cirq.measure(a))\n", "print(circuit)" ] @@ -2222,6 +2252,7 @@ "outputs": [], "source": [ "\"\"\"Example of simulating a noisy circuit with the density matrix simulator.\"\"\"\n", + "\n", "# Circuit to simulate.\n", "circuit = cirq.Circuit(cirq.depolarize(0.2)(a))\n", "print(f'Circuit:\\n{circuit}\\n')\n", @@ -2252,6 +2283,7 @@ "outputs": [], "source": [ "\"\"\"Simulating a circuit with measurements using the DensityMatrixSimulator.\"\"\"\n", + "\n", "# Get a circuit with measurements.\n", "circuit = cirq.Circuit(cirq.depolarize(0.5)(a), cirq.measure(a))\n", "\n", @@ -2298,6 +2330,7 @@ "outputs": [], "source": [ "\"\"\"Use the cirq.mixture protocol on the cirq.depolarize channel.\"\"\"\n", + "\n", "for p, u in cirq.mixture(cirq.depolarize(0.2)):\n", " print(f\"prob = {p}\\nunitary: \\n{u}\\n\")" ] @@ -2320,6 +2353,7 @@ "outputs": [], "source": [ "\"\"\"Check if cirq.depolarize has _kraus_ and _mixture_ methods.\"\"\"\n", + "\n", "# Get a depolarizing channel.\n", "d = cirq.depolarize(0.2)\n", "\n", @@ -2350,6 +2384,7 @@ "outputs": [], "source": [ "\"\"\"Use the wavefunction simulator on a channel that implements the mixture protocol.\"\"\"\n", + "\n", "circuit = cirq.Circuit(cirq.depolarize(0.5).on(a), cirq.measure(a))\n", "simulator = cirq.Simulator()\n", "result = simulator.run(circuit, repetitions=10)\n", @@ -2394,6 +2429,7 @@ "outputs": [], "source": [ "\"\"\"Adding noise to a circuit.\"\"\"\n", + "\n", "# Get a noiseless circuit.\n", "noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2))\n", "circuit = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b))\n", @@ -2425,6 +2461,7 @@ "outputs": [], "source": [ "\"\"\"Perform noisy simulation by defining a density matrix simulator with a noise model.\"\"\"\n", + "\n", "# Define a noise model.\n", "noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2))\n", "\n", @@ -2490,6 +2527,7 @@ "outputs": [], "source": [ "\"\"\"Get the duration of an operation.\"\"\"\n", + "\n", "op = cirq.X.on(cirq.GridQubit(5, 5))\n", "gate_durations = cirq_google.Sycamore.metadata.gate_durations\n", "for gate_family in gate_durations:\n", @@ -2515,6 +2553,7 @@ "outputs": [], "source": [ "\"\"\"Validate operations on a device.\"\"\"\n", + "\n", "# Get non-adjacent qubits on the Sycamore device.\n", "q55 = cirq.GridQubit(5, 5)\n", "q56 = cirq.GridQubit(5, 6)\n", @@ -2640,7 +2679,6 @@ "source": [ "\"\"\"Example of writing a custom cirq transformer.\"\"\"\n", "\n", - "\n", "@cirq.transformer\n", "def xz_optimizer(circuit, *, context=None):\n", " \"\"\"Replaces an X followed by a Z with a Y.\"\"\"\n", @@ -2878,6 +2916,7 @@ "outputs": [], "source": [ "\"\"\"Export a circuit to Qasm.\"\"\"\n", + "\n", "a, b, c = cirq.LineQubit.range(3)\n", "circuit = cirq.Circuit(cirq.H(a), cirq.H(c), cirq.CNOT(a, b), cirq.CCZ(a, b, c))\n", "print(circuit.to_qasm())" @@ -2901,6 +2940,7 @@ "outputs": [], "source": [ "\"\"\"Export a circuit to a Quirk URL.\"\"\"\n", + "\n", "from cirq.contrib.quirk.export_to_quirk import circuit_to_quirk_url\n", "\n", "print(circuit_to_quirk_url(circuit))" diff --git a/docs/transform/routing_transformer.ipynb b/docs/transform/routing_transformer.ipynb index 8f1c5723d15..1ed40ae2641 100644 --- a/docs/transform/routing_transformer.ipynb +++ b/docs/transform/routing_transformer.ipynb @@ -152,13 +152,15 @@ "source": [ "# The circuit to be routed\n", "q = cirq.LineQubit.range(4)\n", - "circuit = cirq.Circuit([\n", - " cirq.Moment(cirq.CNOT(q[2], q[0]), cirq.CNOT(q[1], q[3])),\n", - " cirq.Moment(cirq.X(q[0]), cirq.CNOT(q[1], q[2])),\n", - " cirq.Moment(cirq.CNOT(q[0], q[1])),\n", - " cirq.Moment(cirq.H.on_each(q[1], q[2])),\n", - " cirq.Moment(cirq.CNOT(q[1], q[0]), cirq.CNOT(q[3], q[2])),\n", - "])\n", + "circuit = cirq.Circuit(\n", + " [\n", + " cirq.Moment(cirq.CNOT(q[2], q[0]), cirq.CNOT(q[1], q[3])),\n", + " cirq.Moment(cirq.X(q[0]), cirq.CNOT(q[1], q[2])),\n", + " cirq.Moment(cirq.CNOT(q[0], q[1])),\n", + " cirq.Moment(cirq.H.on_each(q[1], q[2])),\n", + " cirq.Moment(cirq.CNOT(q[1], q[0]), cirq.CNOT(q[3], q[2])),\n", + " ]\n", + ")\n", "print(circuit)" ] }, @@ -172,6 +174,7 @@ "source": [ "# Initialize the router with Sycamore device hardware\n", "import cirq_google as cg\n", + "\n", "device = cg.Sycamore\n", "device_graph = device.metadata.nx_graph\n", "router = cirq.RouteCQC(device_graph)\n", @@ -202,7 +205,9 @@ "source": [ "# Compile the gates in routed_circuit to Sycamore gates (this is done because `validate_circuit` checks\n", "# that all 2-qubit operations are physically adjacent AND that all gates are part of the device's gateset).\n", - "routed_circuit = cirq.optimize_for_target_gateset(routed_circuit, gateset = cg.SycamoreTargetGateset())\n", + "routed_circuit = cirq.optimize_for_target_gateset(\n", + " routed_circuit, gateset=cg.SycamoreTargetGateset()\n", + ")\n", "# Validate our circuit\n", "device.validate_circuit(routed_circuit)" ] @@ -262,7 +267,9 @@ }, "outputs": [], "source": [ - "routed_circuit = router(circuit, lookahead_radius = 5, tag_inserted_swaps=True, initial_mapper=hc_initial_mapper)\n", + "routed_circuit = router(\n", + " circuit, lookahead_radius=5, tag_inserted_swaps=True, initial_mapper=hc_initial_mapper\n", + ")\n", "print(routed_circuit)" ] }, @@ -295,7 +302,9 @@ "outputs": [], "source": [ "# Example with appending a QubitPermutationGate to `routed_circuit` and permuting initial order of qubits.\n", - "routed_circuit, initial_mapping, swap_mapping = router.route_circuit(circuit, initial_mapper=hc_initial_mapper)\n", + "routed_circuit, initial_mapping, swap_mapping = router.route_circuit(\n", + " circuit, initial_mapper=hc_initial_mapper\n", + ")\n", "print(circuit)\n", "print(routed_circuit)\n", "\n", @@ -350,7 +359,9 @@ "print(routed_circuit)\n", "\n", "# This will not raise an errors now\n", - "cirq.testing.assert_allclose_up_to_global_phase(circuit.unitary(), routed_circuit.unitary(qubit_order=order), atol=1e-8)" + "cirq.testing.assert_allclose_up_to_global_phase(\n", + " circuit.unitary(), routed_circuit.unitary(qubit_order=order), atol=1e-8\n", + ")" ] }, { @@ -403,9 +414,10 @@ "\n", "QidIntPair = Tuple[int, int]\n", "\n", + "\n", "class RouteCQCSimpleCostFunction(cirq.RouteCQC):\n", - " @classmethod\n", - " def _cost(\n", + " @classmethod\n", + " def _cost(\n", " cls,\n", " mm: cirq.MappingManager,\n", " swaps: Tuple[QidIntPair, ...],\n", diff --git a/docs/tutorials/google/colab.ipynb b/docs/tutorials/google/colab.ipynb index 102aa205991..0d1be4dbc82 100644 --- a/docs/tutorials/google/colab.ipynb +++ b/docs/tutorials/google/colab.ipynb @@ -18,7 +18,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -174,10 +174,11 @@ "outputs": [], "source": [ "# The Google Cloud Project id to use.\n", - "project_id = '' #@param {type:\"string\"}\n", - "processor_id = \"\" #@param {type:\"string\"}\n", + "project_id = '' # @param {type:\"string\"}\n", + "processor_id = \"\" # @param {type:\"string\"}\n", "\n", "from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook\n", + "\n", "# For real engine instances, delete 'virtual=True' below.\n", "qcs_objects = get_qcs_objects_for_notebook(project_id, processor_id, virtual=True)\n", "engine = qcs_objects.engine\n", @@ -207,23 +208,27 @@ "from google.api_core.exceptions import PermissionDenied\n", "\n", "# Create an Engine object to use, providing the project id and the args\n", - "try: \n", - " if qcs_objects.signed_in: # This line only needed for colab testing.\n", + "try:\n", + " if qcs_objects.signed_in: # This line only needed for colab testing.\n", " engine = cirq_google.get_engine()\n", " print(f\"Successful authentication using project {project_id}!\")\n", " print('Available Processors: ')\n", " print(engine.list_processors())\n", " print(f'Using processor: {processor_id}')\n", " processor = engine.get_processor(processor_id)\n", - "except DefaultCredentialsError as err: \n", + "except DefaultCredentialsError as err:\n", " print(\"Could not authenticate to Google Quantum Computing Service.\")\n", " print(\" Tips: If you are using Colab: make sure the previous cell was executed successfully.\")\n", - " print(\" If this notebook is not in Colab (e.g. Jupyter notebook), make sure gcloud is installed and `gcloud auth application-default login` was executed.\")\n", + " print(\n", + " \" If this notebook is not in Colab (e.g. Jupyter notebook), make sure gcloud is installed and `gcloud auth application-default login` was executed.\"\n", + " )\n", " print()\n", " print(\"Error message:\")\n", " print(err)\n", "except PermissionDenied as err:\n", - " print(f\"While you are authenticated to Google Cloud it seems the project '{project_id}' does not exist or does not have the Quantum Engine API enabled.\")\n", + " print(\n", + " f\"While you are authenticated to Google Cloud it seems the project '{project_id}' does not exist or does not have the Quantum Engine API enabled.\"\n", + " )\n", " print(\"Error message:\")\n", " print(err)" ] @@ -247,11 +252,9 @@ "source": [ "# A simple example.\n", "q = cirq.GridQubit(5, 2)\n", - "circuit = cirq.Circuit(cirq.X(q)**0.5, cirq.measure(q, key='m'))\n", + "circuit = cirq.Circuit(cirq.X(q) ** 0.5, cirq.measure(q, key='m'))\n", "\n", - "job = processor.run_sweep(\n", - " program=circuit,\n", - " repetitions=1000)\n", + "job = processor.run_sweep(program=circuit, repetitions=1000)\n", "\n", "results = [str(int(b)) for b in job.results()[0].measurements['m'][:, 0]]\n", "print('Success! Results:')\n", diff --git a/docs/tutorials/google/echoes.ipynb b/docs/tutorials/google/echoes.ipynb index dfb98c16ef4..5e024430dfb 100644 --- a/docs/tutorials/google/echoes.ipynb +++ b/docs/tutorials/google/echoes.ipynb @@ -20,7 +20,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -164,10 +164,11 @@ ], "source": [ "# The Google Cloud Project id to use.\n", - "project_id = '' #@param {type:\"string\"}\n", - "processor_id = \"\" #@param {type:\"string\"}\n", + "project_id = '' # @param {type:\"string\"}\n", + "processor_id = \"\" # @param {type:\"string\"}\n", "\n", "from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook\n", + "\n", "device_sampler = get_qcs_objects_for_notebook(project_id, processor_id)" ] }, @@ -205,7 +206,7 @@ " seed: Optional[int] = None,\n", ") -> cirq.Circuit:\n", " \"\"\"Returns a Loschmidt echo circuit using a random unitary U.\n", - " \n", + "\n", " Args:\n", " qubits: Qubits to use.\n", " cycles: Depth of random rotations in the forward & reverse unitary.\n", @@ -215,13 +216,14 @@ " \"\"\"\n", " # Forward (U) operations.\n", " forward = random_rotations_between_grid_interaction_layers_circuit(\n", - " qubits, \n", + " qubits,\n", " depth=cycles,\n", " two_qubit_op_factory=lambda a, b, _: twoq_gate.on(a, b),\n", " pattern=cirq.experiments.GRID_STAGGERED_PATTERN,\n", - " single_qubit_gates=[cirq.PhasedXPowGate(phase_exponent=p, exponent=0.5)\n", - " for p in np.arange(-1.0, 1.0, 0.25)],\n", - " seed=seed\n", + " single_qubit_gates=[\n", + " cirq.PhasedXPowGate(phase_exponent=p, exponent=0.5) for p in np.arange(-1.0, 1.0, 0.25)\n", + " ],\n", + " seed=seed,\n", " )\n", "\n", " # Optional pause.\n", @@ -229,7 +231,7 @@ " wait = cirq.Moment(cirq.WaitGate(pause).on(q) for q in qubits)\n", " else:\n", " wait = []\n", - " \n", + "\n", " # Reverse (U^\\dagger) operations.\n", " reverse = cirq.inverse(forward)\n", "\n", @@ -285,6 +287,7 @@ ], "source": [ "\"\"\"See an example circuit.\"\"\"\n", + "\n", "circuit = create_loschmidt_echo_circuit(\n", " qubits=cirq.GridQubit.square(2), cycles=2, pause=cirq.Duration(nanos=5.0)\n", ")\n", @@ -317,6 +320,7 @@ ], "source": [ "\"\"\"Loschmidt echo benchmark on a simulator.\"\"\"\n", + "\n", "# Simulate the circuit.\n", "nreps = 20_000\n", "res = cirq.Simulator().run(circuit, repetitions=nreps)\n", @@ -381,6 +385,7 @@ "outputs": [], "source": [ "\"\"\"Set parameters for Loschmidt echo benchmark.\"\"\"\n", + "\n", "processor_id = \"weber\"\n", "cycle_values = range(0, 80 + 1, 2)\n", "pause = None\n", @@ -452,16 +457,23 @@ "outputs": [], "source": [ "\"\"\"Pick sets of qubits to run Loschmidt echoes on.\"\"\"\n", + "\n", "qubit_sets_indices = [\n", " [(4, 7), (4, 8), (5, 8), (5, 7)],\n", - " [(0, 5), (0, 6), (1, 6), (1, 5)], # From the calibration, we expect this to be the worst configuration.\n", + " [\n", + " (0, 5),\n", + " (0, 6),\n", + " (1, 6),\n", + " (1, 5),\n", + " ], # From the calibration, we expect this to be the worst configuration.\n", " [(2, 6), (2, 7), (3, 7), (3, 6)],\n", " [(7, 3), (7, 4), (8, 4), (8, 3)],\n", "]\n", "\n", "# Convert indices to grid qubits.\n", - "qubit_sets = [[cirq.GridQubit(*idx) for idx in qubit_indices] \n", - " for qubit_indices in qubit_sets_indices]" + "qubit_sets = [\n", + " [cirq.GridQubit(*idx) for idx in qubit_indices] for qubit_indices in qubit_sets_indices\n", + "]" ] }, { @@ -490,6 +502,7 @@ ], "source": [ "\"\"\"Run the Loschmidt echo experiment.\"\"\"\n", + "\n", "sampler = cg.get_engine_sampler(processor_id=processor_id, gate_set_name=\"sqrt_iswap\")\n", "\n", "probs = []\n", @@ -499,7 +512,8 @@ " # Create the batch of circuits.\n", " batch = [\n", " create_loschmidt_echo_circuit(qubits, cycles=c, pause=pause, seed=trial)\n", - " for qubits in qubit_sets for c in cycle_values\n", + " for qubits in qubit_sets\n", + " for c in cycle_values\n", " ]\n", "\n", " # Run the batch.\n", @@ -558,12 +572,12 @@ "\n", "for i in range(len(qubit_sets)):\n", " plt.errorbar(\n", - " x=cycle_values, \n", - " y=avg_probs[i], \n", + " x=cycle_values,\n", + " y=avg_probs[i],\n", " yerr=std_probs[i],\n", " capsize=5,\n", " lw=2,\n", - " label=f\"Qubit configuration {i}\"\n", + " label=f\"Qubit configuration {i}\",\n", " )\n", "\n", "plt.legend()\n", @@ -610,18 +624,16 @@ ], "source": [ "\"\"\"Fit an exponential decay to the collected data.\"\"\"\n", + "\n", "from scipy.optimize import curve_fit\n", "\n", + "\n", "def fit(cycle, a, f):\n", " return a * np.exp((f - 1.0) * cycle)\n", "\n", "\n", "for i in range(len(qubit_sets)):\n", - " (a, f), _ = curve_fit(\n", - " fit,\n", - " xdata=cycle_values, \n", - " ydata=avg_probs[i],\n", - " )\n", + " (a, f), _ = curve_fit(fit, xdata=cycle_values, ydata=avg_probs[i])\n", " print(f\"Error/cycle on qubit configuration {i}: {round((1 - f) * 100, 2)}%\")" ] }, diff --git a/docs/tutorials/google/identifying_hardware_changes.ipynb b/docs/tutorials/google/identifying_hardware_changes.ipynb index 4e3122e4300..8e3e36eec37 100644 --- a/docs/tutorials/google/identifying_hardware_changes.ipynb +++ b/docs/tutorials/google/identifying_hardware_changes.ipynb @@ -20,7 +20,7 @@ }, "outputs": [], "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", @@ -272,9 +272,9 @@ "from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook\n", "\n", "# Set key variables\n", - "project_id = \"your_project_id_here\" #@param {type:\"string\"}\n", - "processor_id = \"your_processor_id_here\" #@param {type:\"string\"}\n", - "repetitions = 2000 #@param {type:\"integer\"}\n", + "project_id = \"your_project_id_here\" # @param {type:\"string\"}\n", + "processor_id = \"your_processor_id_here\" # @param {type:\"string\"}\n", + "repetitions = 2000 # @param {type:\"integer\"}\n", "\n", "# Get device sampler\n", "qcs_objects = get_qcs_objects_for_notebook(project_id=project_id, processor_id=processor_id)\n", @@ -286,11 +286,11 @@ "qubits = device.qubit_set()\n", "\n", "# Limit device qubits to only those before row/column `device_limit`\n", - "device_limit = 10 #@param {type:\"integer\"}\n", - "qubits = {qb for qb in qubits if qb.row state).\n", "circuit = cirq.Circuit(\n", - " cirq.X(qubit), # NOT gate.\n", - " cirq.measure(qubit, key='result') # Measurement.\n", + " cirq.X(qubit), cirq.measure(qubit, key='result') # NOT gate. # Measurement.\n", ")\n", "\n", "print(\"Circuit:\")\n", @@ -302,7 +302,7 @@ }, "outputs": [], "source": [ - "processor_id = \"\" #@param {type:\"string\"}" + "processor_id = \"\" # @param {type:\"string\"}" ] }, { @@ -460,8 +460,10 @@ "outputs": [], "source": [ "print(\"Scheduling execution on the Quantum Engine...\\n\")\n", - "print(\"You can view jobs at: https://console.cloud.google.com/quantum/\"\n", - " \"jobs?project={}\\n\".format(project_id))\n", + "print(\n", + " \"You can view jobs at: https://console.cloud.google.com/quantum/\"\n", + " \"jobs?project={}\\n\".format(project_id)\n", + ")\n", "\n", "# Print out the results. This blocks until the results are returned.\n", "results = sampler.run(hw_circuit, repetitions=1000)\n", @@ -516,6 +518,7 @@ "import cirq\n", "import cirq_google as cg\n", "\n", + "\n", "def example(engine, processor_id):\n", " \"\"\"Hello qubit example run against a quantum processor.\"\"\"\n", "\n", @@ -525,8 +528,8 @@ "\n", " # Create a circuit (qubits start in the |0> state).\n", " circuit = cirq.Circuit(\n", - " cirq.X(qubit)**0.5, # Square root of NOT.\n", - " cirq.measure(qubit, key='result') # Measurement.\n", + " cirq.X(qubit) ** 0.5, # Square root of NOT.\n", + " cirq.measure(qubit, key='result'), # Measurement.\n", " )\n", "\n", " sampler = processor.get_sampler()\n", @@ -536,9 +539,11 @@ " print(\"\\nMeasurement results:\")\n", " print(results)\n", "\n", + "\n", "if __name__ == '__main__':\n", " # Set up QCS objects.\n", " from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook\n", + "\n", " qcs_objects = get_qcs_objects_for_notebook(project_id='')\n", " processor_id = qcs_objects.processor_id\n", " engine = qcs_objects.engine\n", diff --git a/docs/tutorials/google/visualizing_calibration_metrics.ipynb b/docs/tutorials/google/visualizing_calibration_metrics.ipynb index f8997dff60f..c7bda0d8387 100644 --- a/docs/tutorials/google/visualizing_calibration_metrics.ipynb +++ b/docs/tutorials/google/visualizing_calibration_metrics.ipynb @@ -82,7 +82,7 @@ }, "outputs": [], "source": [ - "#@title Necessary Imports\n", + "# @title Necessary Imports\n", "try:\n", " import cirq\n", "except ImportError:\n", @@ -134,14 +134,17 @@ "import cirq_google as cg\n", "\n", "# The Google Cloud Project id to use.\n", - "project_id = \"\" #@param {type:\"string\"}\n", - "processor_id = \"\" #@param {type:\"string\"}\n", + "project_id = \"\" # @param {type:\"string\"}\n", + "processor_id = \"\" # @param {type:\"string\"}\n", "\n", "from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook\n", + "\n", "device_sampler = get_qcs_objects_for_notebook(project_id, processor_id)\n", "\n", "if not device_sampler.signed_in:\n", - " raise Exception(\"Please setup project_id in this cell or set the `GOOGLE_CLOUD_PROJECT` env var to your project id.\")" + " raise Exception(\n", + " \"Please setup project_id in this cell or set the `GOOGLE_CLOUD_PROJECT` env var to your project id.\"\n", + " )" ] }, { @@ -155,7 +158,7 @@ "source": [ "# @title Quantum Engine Configuration\n", "# @markdown Replace the `PROCESSOR_ID` and `YOUR_PROJECT_ID` with your details.\n", - "PROCESSOR_ID = '' #@param {type: 'string'}\n", + "PROCESSOR_ID = '' # @param {type: 'string'}\n", "cals = cirq_google.get_engine_calibration(PROCESSOR_ID, YOUR_PROJECT_ID)" ] }, @@ -196,8 +199,8 @@ } ], "source": [ - "#@title View available calibration metrics\n", - "#@markdown See https://quantumai.google/cirq/google/calibration for a description of the available calibration metrics\n", + "# @title View available calibration metrics\n", + "# @markdown See https://quantumai.google/cirq/google/calibration for a description of the available calibration metrics\n", "for k, v in cals.items():\n", " print(k)" ] @@ -291,7 +294,7 @@ } ], "source": [ - "fig, _ = cals.plot('single_qubit_rb_incoherent_error_per_gate', fig=plt.figure(figsize=(20, 10)))\n" + "fig, _ = cals.plot('single_qubit_rb_incoherent_error_per_gate', fig=plt.figure(figsize=(20, 10)))" ] }, { @@ -326,7 +329,7 @@ } ], "source": [ - "fig, _ = cals.plot('single_qubit_rb_pauli_error_per_gate', fig=plt.figure(figsize=(20, 10)))\n" + "fig, _ = cals.plot('single_qubit_rb_pauli_error_per_gate', fig=plt.figure(figsize=(20, 10)))" ] }, { @@ -371,7 +374,11 @@ } ], "source": [ - "keys = ['single_qubit_rb_pauli_error_per_gate', 'single_qubit_rb_average_error_per_gate', 'single_qubit_rb_incoherent_error_per_gate']\n", + "keys = [\n", + " 'single_qubit_rb_pauli_error_per_gate',\n", + " 'single_qubit_rb_average_error_per_gate',\n", + " 'single_qubit_rb_incoherent_error_per_gate',\n", + "]\n", "fig, ax = plt.subplots(figsize=(16, 8))\n", "cals.plot_histograms(keys, ax)\n", "ax.set_title(\"Single Qubit Error Comparison Histograms\")" @@ -618,7 +625,9 @@ } ], "source": [ - "fig, _ = cals.plot('two_qubit_sqrt_iswap_gate_xeb_average_error_per_cycle', fig=plt.figure(figsize=(20, 10)))" + "fig, _ = cals.plot(\n", + " 'two_qubit_sqrt_iswap_gate_xeb_average_error_per_cycle', fig=plt.figure(figsize=(20, 10))\n", + ")" ] }, { @@ -653,7 +662,9 @@ } ], "source": [ - "fig, _ = cals.plot('two_qubit_sqrt_iswap_gate_xeb_incoherent_error_per_cycle', fig=plt.figure(figsize=(20, 10)))" + "fig, _ = cals.plot(\n", + " 'two_qubit_sqrt_iswap_gate_xeb_incoherent_error_per_cycle', fig=plt.figure(figsize=(20, 10))\n", + ")" ] }, { @@ -688,7 +699,9 @@ } ], "source": [ - "fig, _ = cals.plot('two_qubit_sqrt_iswap_gate_xeb_pauli_error_per_cycle', fig=plt.figure(figsize=(20, 10)))" + "fig, _ = cals.plot(\n", + " 'two_qubit_sqrt_iswap_gate_xeb_pauli_error_per_cycle', fig=plt.figure(figsize=(20, 10))\n", + ")" ] }, { @@ -734,7 +747,10 @@ } ], "source": [ - "fig, _ = cals.plot('two_qubit_parallel_sqrt_iswap_gate_xeb_average_error_per_cycle', fig=plt.figure(figsize=(20, 10)))" + "fig, _ = cals.plot(\n", + " 'two_qubit_parallel_sqrt_iswap_gate_xeb_average_error_per_cycle',\n", + " fig=plt.figure(figsize=(20, 10)),\n", + ")" ] }, { @@ -769,7 +785,10 @@ } ], "source": [ - "fig, _ = cals.plot('two_qubit_parallel_sqrt_iswap_gate_xeb_incoherent_error_per_cycle', fig=plt.figure(figsize=(20, 10)))" + "fig, _ = cals.plot(\n", + " 'two_qubit_parallel_sqrt_iswap_gate_xeb_incoherent_error_per_cycle',\n", + " fig=plt.figure(figsize=(20, 10)),\n", + ")" ] }, { @@ -804,7 +823,9 @@ } ], "source": [ - "fig, _ = cals.plot('two_qubit_parallel_sqrt_iswap_gate_xeb_pauli_error_per_cycle', fig=plt.figure(figsize=(20, 10)))" + "fig, _ = cals.plot(\n", + " 'two_qubit_parallel_sqrt_iswap_gate_xeb_pauli_error_per_cycle', fig=plt.figure(figsize=(20, 10))\n", + ")" ] } ], diff --git a/examples/advanced/quantum_utility_sim_4a.ipynb b/examples/advanced/quantum_utility_sim_4a.ipynb index badf7eb9a45..dce93a04fb1 100644 --- a/examples/advanced/quantum_utility_sim_4a.ipynb +++ b/examples/advanced/quantum_utility_sim_4a.ipynb @@ -123,7 +123,9 @@ " *range(71, 73), # row 3\n", " *range(75, 82), # row 4\n", " *range(90, 92), # row 5\n", - " 94, 95, 98, # row 6\n", + " 94,\n", + " 95,\n", + " 98, # row 6\n", "]\n", "q = {i: cirq.NamedQubit(f'q{i}') for i in qubit_ids}\n", "qubits = list(q.values())\n", @@ -133,7 +135,7 @@ "x_rotations = cirq.Moment(cirq.rx(theta).on_each(qubits))\n", "\n", "# This is the ZZ(-pi/2) gate described in equation (2).\n", - "zz_pi_2 = cirq.ZZ ** -0.5\n", + "zz_pi_2 = cirq.ZZ**-0.5\n", "\n", "# Each of these moments performs ZZ interactions along\n", "# 1/3 of the edges in the region, corresponding to the\n", @@ -178,12 +180,7 @@ "\n", "# This circuit encapsulates a single \"step\", as shown\n", "# in Fig. 1a.\n", - "step = cirq.FrozenCircuit(\n", - " x_rotations,\n", - " zz_layer_1,\n", - " zz_layer_2,\n", - " zz_layer_3,\n", - ")\n", + "step = cirq.FrozenCircuit(x_rotations, zz_layer_1, zz_layer_2, zz_layer_3)\n", "# Uncomment this line to print the circuit diagram for\n", "# a single step of the circuit.\n", "# print(step)" @@ -229,7 +226,9 @@ "# This will log after each value of theta is simulated. Its purpose is to\n", "# give an indication of total runtime before all simulations finish.\n", "results = []\n", - "for i, result in enumerate(simulator.simulate_expectation_values_sweep_iter(circuit, observables, params)):\n", + "for i, result in enumerate(\n", + " simulator.simulate_expectation_values_sweep_iter(circuit, observables, params)\n", + "):\n", " results.append(result)\n", " print(f\"Completed theta={theta_values[i]:.3f}; value={result}\")\n", "\n", diff --git a/examples/advanced/quantum_utility_sim_4b.ipynb b/examples/advanced/quantum_utility_sim_4b.ipynb index 20e384f2f21..ed23f8d103e 100644 --- a/examples/advanced/quantum_utility_sim_4b.ipynb +++ b/examples/advanced/quantum_utility_sim_4b.ipynb @@ -122,7 +122,7 @@ "x_rotations = cirq.Moment(cirq.rx(theta).on_each(qubits))\n", "\n", "# This is the ZZ(-pi/2) gate described in equation (2).\n", - "zz_pi_2 = cirq.ZZ ** -0.5\n", + "zz_pi_2 = cirq.ZZ**-0.5\n", "\n", "# Each of these moments performs ZZ interactions along\n", "# 1/3 of the edges in the region, corresponding to the\n", @@ -166,12 +166,7 @@ "\n", "# This circuit encapsulates a single \"step\", as shown\n", "# in Fig. 1a.\n", - "step = cirq.FrozenCircuit(\n", - " x_rotations,\n", - " zz_layer_1,\n", - " zz_layer_2,\n", - " zz_layer_3,\n", - ")\n", + "step = cirq.FrozenCircuit(x_rotations, zz_layer_1, zz_layer_2, zz_layer_3)\n", "# Uncomment this line to print the circuit diagram for\n", "# a single step of the circuit.\n", "# print(step)" @@ -219,7 +214,9 @@ "# This will log after each value of theta is simulated. Its purpose is to\n", "# give an indication of total runtime before all simulations finish.\n", "results = []\n", - "for i, result in enumerate(simulator.simulate_expectation_values_sweep_iter(circuit, observables, params)):\n", + "for i, result in enumerate(\n", + " simulator.simulate_expectation_values_sweep_iter(circuit, observables, params)\n", + "):\n", " results.append(result)\n", " print(f\"Completed theta={theta_values[i]:.3f}; value={result}\")\n", "\n", diff --git a/examples/advanced/quantum_volume.ipynb b/examples/advanced/quantum_volume.ipynb index 55e71bd5e87..e1d8ec4a3ae 100644 --- a/examples/advanced/quantum_volume.ipynb +++ b/examples/advanced/quantum_volume.ipynb @@ -32,7 +32,8 @@ "source": [ "import cirq\n", "import cirq_google\n", - "qubits = cirq.GridQubit.rect(3,2)\n", + "\n", + "qubits = cirq.GridQubit.rect(3, 2)\n", "qubits" ] }, @@ -43,9 +44,11 @@ "outputs": [], "source": [ "import cirq.contrib.routing as ccr\n", + "\n", "device_graph = ccr.gridqubits_to_graph_device(qubits)\n", "\n", "import networkx as nx\n", + "\n", "nx.draw(device_graph)" ] }, @@ -64,27 +67,29 @@ "depths = range(2, max_depth) # The depths and number of qubits\n", "repetitions = 10_000 # The number of times to sample per circuit\n", "\n", + "\n", "def optimize(circuit):\n", " return cirq.optimize_for_target_gateset(circuit, gateset=cirq.CZTargetGateset())\n", "\n", + "\n", "# Here is the important set-up: the samplers and their plot configurations.\n", "# These are what will be run on the generated circuit, and then evaluated.\n", - "samplers = [{\n", - " 'label': 'Ideal simulation',\n", - " 'sampler': cirq.Simulator(),\n", - " 'marker': '+',\n", - " 'color': 'tab:green',\n", - "}, {\n", - " 'label': 'Noisy simulation',\n", - " 'sampler':\n", - " cirq.DensityMatrixSimulator(noise=cirq.ConstantQubitNoiseModel(\n", - " qubit_noise_gate=cirq.DepolarizingChannel(p=0.005))),\n", - " 'color': 'tab:red',\n", - " 'marker': 'o',\n", - "}]\n", - "\n", - "print(f\"Configuration: depths from {depths[0]} to {depths[-1]} with \"\n", - " f\"{num_repetitions} runs of {len(samplers)} samplers\")" + "samplers = [\n", + " {'label': 'Ideal simulation', 'sampler': cirq.Simulator(), 'marker': '+', 'color': 'tab:green'},\n", + " {\n", + " 'label': 'Noisy simulation',\n", + " 'sampler': cirq.DensityMatrixSimulator(\n", + " noise=cirq.ConstantQubitNoiseModel(qubit_noise_gate=cirq.DepolarizingChannel(p=0.005))\n", + " ),\n", + " 'color': 'tab:red',\n", + " 'marker': 'o',\n", + " },\n", + "]\n", + "\n", + "print(\n", + " f\"Configuration: depths from {depths[0]} to {depths[-1]} with \"\n", + " f\"{num_repetitions} runs of {len(samplers)} samplers\"\n", + ")" ] }, { @@ -111,54 +116,53 @@ " print(f\" Repetition {i + 1} of {num_repetitions}\")\n", " # Generate a model circuit and compute its heavy set.\n", " model_circuit = quantum_volume.generate_model_circuit(\n", - " num_qubits, depth, random_state=np.random.RandomState())\n", + " num_qubits, depth, random_state=np.random.RandomState()\n", + " )\n", " heavy_set = quantum_volume.compute_heavy_set(model_circuit)\n", " print(f\" Heavy Set: {heavy_set}\")\n", "\n", " # Route and compile the model circuit.\n", " compilation_result = quantum_volume.compile_circuit(\n", - " model_circuit, \n", - " device_graph=device_graph, \n", - " routing_attempts=1)\n", + " model_circuit, device_graph=device_graph, routing_attempts=1\n", + " )\n", " compiled_circuit = optimize(compilation_result.circuit)\n", "\n", " # Run the given samplers over the model, compiled, and optimized circuits.\n", " for sampler in samplers:\n", " probability = quantum_volume.sample_heavy_set(\n", - " compilation_result, heavy_set, sampler=sampler['sampler'])\n", + " compilation_result, heavy_set, sampler=sampler['sampler']\n", + " )\n", " sampler['probabilities'][depth] += probability\n", " print(f\" {sampler['label']} HOG probability: {probability}\")\n", "\n", " routed_probability = quantum_volume.sample_heavy_set(\n", - " compilation_result,\n", - " heavy_set,\n", - " sampler=sampler['sampler'],\n", - " repetitions=repetitions)\n", - " sampler['routed-probabilities'][depth] += routed_probability\n", - " print(\n", - " f\" {sampler['label']} HOG routed probability: {routed_probability}\"\n", + " compilation_result, heavy_set, sampler=sampler['sampler'], repetitions=repetitions\n", " )\n", + " sampler['routed-probabilities'][depth] += routed_probability\n", + " print(f\" {sampler['label']} HOG routed probability: {routed_probability}\")\n", "\n", " compiled_probability = quantum_volume.sample_heavy_set(\n", - " compilation_result,\n", - " heavy_set,\n", - " sampler=sampler['sampler'])\n", - " sampler['compiled-probabilities'][depth] += compiled_probability\n", - " print(\n", - " f\" {sampler['label']} HOG compiled probability: {compiled_probability}\"\n", + " compilation_result, heavy_set, sampler=sampler['sampler']\n", " )\n", + " sampler['compiled-probabilities'][depth] += compiled_probability\n", + " print(f\" {sampler['label']} HOG compiled probability: {compiled_probability}\")\n", "\n", " # Compute the average performance over the total number of runs.\n", " for sampler in samplers:\n", " sampler['probabilities'][depth] /= num_repetitions\n", " sampler['routed-probabilities'][depth] /= num_repetitions\n", " sampler['compiled-probabilities'][depth] /= num_repetitions\n", - " print(f\" Average {sampler['label']} HOG probability: \"\n", - " f\"{sampler['probabilities'][depth]}\")\n", - " print(f\" Average {sampler['label']} optimized HOG probability: \"\n", - " f\"{sampler['routed-probabilities'][depth]}\")\n", - " print(f\" Average {sampler['label']} compiled HOG probability: \"\n", - " f\"{sampler['compiled-probabilities'][depth]}\")\n" + " print(\n", + " f\" Average {sampler['label']} HOG probability: \" f\"{sampler['probabilities'][depth]}\"\n", + " )\n", + " print(\n", + " f\" Average {sampler['label']} optimized HOG probability: \"\n", + " f\"{sampler['routed-probabilities'][depth]}\"\n", + " )\n", + " print(\n", + " f\" Average {sampler['label']} compiled HOG probability: \"\n", + " f\"{sampler['compiled-probabilities'][depth]}\"\n", + " )" ] }, { @@ -174,28 +178,31 @@ "\n", "fig, axs = plt.subplots()\n", "for idx, sampler in enumerate(samplers):\n", - " axs.scatter([d + idx / 10 for d in depths],\n", - " sampler['probabilities'].values(),\n", - " marker='+',\n", - " c=f\"{sampler['color']}\",\n", - " label=f\"{sampler['label']}\")\n", - " axs.scatter([d + idx / 10 for d in depths],\n", - " sampler['routed-probabilities'].values(),\n", - " marker=\"o\",\n", - " c=f\"{sampler['color']}\",\n", - " label=f\"{sampler['label']} Routed\")\n", - " axs.scatter([d + idx / 10 for d in depths],\n", - " sampler['compiled-probabilities'].values(),\n", - " marker=\"s\",\n", - " c=f\"{sampler['color']}\",\n", - " label=f\"{sampler['label']} Compiled\")\n", + " axs.scatter(\n", + " [d + idx / 10 for d in depths],\n", + " sampler['probabilities'].values(),\n", + " marker='+',\n", + " c=f\"{sampler['color']}\",\n", + " label=f\"{sampler['label']}\",\n", + " )\n", + " axs.scatter(\n", + " [d + idx / 10 for d in depths],\n", + " sampler['routed-probabilities'].values(),\n", + " marker=\"o\",\n", + " c=f\"{sampler['color']}\",\n", + " label=f\"{sampler['label']} Routed\",\n", + " )\n", + " axs.scatter(\n", + " [d + idx / 10 for d in depths],\n", + " sampler['compiled-probabilities'].values(),\n", + " marker=\"s\",\n", + " c=f\"{sampler['color']}\",\n", + " label=f\"{sampler['label']} Compiled\",\n", + " )\n", "\n", "# Line markers for asymptotic ideal heavy output probability and the ideal\n", "# Heavy Output Generation threshold.\n", - "axs.axhline((1 + np.log(2)) / 2,\n", - " color='tab:green',\n", - " label='Asymptotic ideal',\n", - " linestyle='dashed')\n", + "axs.axhline((1 + np.log(2)) / 2, color='tab:green', label='Asymptotic ideal', linestyle='dashed')\n", "axs.axhline(2 / 3, label='HOG threshold', color='k', linestyle='dotted')\n", "# Making the plot look consistent.\n", "axs.set_ybound(0.0, 1)\n", diff --git a/examples/advanced/quantum_volume_errors.ipynb b/examples/advanced/quantum_volume_errors.ipynb index 803a43377e9..575f85c3a9b 100644 --- a/examples/advanced/quantum_volume_errors.ipynb +++ b/examples/advanced/quantum_volume_errors.ipynb @@ -1,151 +1,153 @@ { - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "id": "8e3qhaan0Vwx" - }, - "source": [ - "# Analyzing Quantum Volume Errors\n", - "This notebook analyzes the error rates required for achieving Quantum Volume at a particular depth. For a given m = depth = number of qubits, plot the HOG for np.logspace outputs to view when it crosses the 2/3rds probability threshold." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "bd9529db1c0b" - }, - "outputs": [], - "source": [ - "try:\n", - " import cirq\n", - "except ImportError:\n", - " print(\"installing cirq...\")\n", - " !pip install --quiet cirq\n", - " print(\"installed cirq.\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "1QezTbjO0Vw4" - }, - "outputs": [], - "source": [ - "import cirq\n", - "import cirq_google\n", - "\n", - "# Configuration parameters. Feel free to mess with these!\n", - "num_circuits = 10\n", - "depth = 4\n", - "num_samplers = 50\n", - "repetitions = 10_000\n", - "device=cirq_google.Sycamore\n", - "\n", - "print(f\"Configuration: depth {depth} with \"\n", - " f\"{num_circuits} circuits of {num_samplers} samplers\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "rZ_7U7n90Vw5" - }, - "outputs": [], - "source": [ - "# Run the Quantum Volume algorithm over the above parameters.\n", - "\n", - "import numpy as np\n", - "from cirq.contrib import quantum_volume, routing\n", - "\n", - "errors = np.logspace(-1, -4, num=num_samplers)\n", - "samplers = [\n", - " cirq.DensityMatrixSimulator(noise=cirq.ConstantQubitNoiseModel(\n", - " qubit_noise_gate=cirq.DepolarizingChannel(p=error)))\n", - " for error in errors]\n", - "\n", - "def optimize(circuit):\n", - " return cirq.optimize_for_target_gateset(circuit, gateset=cirq.SqrtIswapTargetGateset())\n", - "\n", - "result = quantum_volume.calculate_quantum_volume(\n", - " num_circuits=num_circuits,\n", - " depth=depth,\n", - " num_qubits=depth,\n", - " device_graph=routing.gridqubits_to_graph_device(device.metadata.qubit_set),\n", - " samplers=samplers,\n", - " compiler=optimize,\n", - " repetitions=repetitions)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "CvJvkMLx0Vw6" - }, - "outputs": [], - "source": [ - "# Create a chart that plots the HOG rate relative to the simulated error ratio.\n", - "\n", - "from matplotlib import pyplot as plt\n", - "import statistics\n", - "\n", - "def chunks(l, n):\n", - " \"\"\"Yield successive n-sized chunks from l.\"\"\"\n", - " for i in range(0, len(l), n):\n", - " yield l[i:i + n]\n", - " \n", - "split = chunks([res.sampler_result for res in result], num_circuits)\n", - "fig, axs = plt.subplots()\n", - "axs.plot(errors,\n", - " [statistics.mean(chunk) for chunk in split])\n", - "\n", - "# Line markers for asymptotic ideal heavy output probability and the ideal Heavy\n", - "# Output Generation threshold.\n", - "axs.axhline((1 + np.log(2)) / 2,\n", - " color='tab:green',\n", - " label='Asymptotic ideal',\n", - " linestyle='dashed')\n", - "axs.axhline(2 / 3, label='HOG threshold', color='k', linestyle='dotted')\n", - "plt.xscale('log')\n", - "axs.set_ybound(0.4, 1)\n", - "axs.set_xlabel(\"error rate\")\n", - "axs.set_ylabel(\"est. heavy output probability\")\n", - "fig.suptitle(f'HOG probability by simulated error rate for d={depth}')" - ] - } - ], - "metadata": { - "colab": { - "name": "quantum_volume_errors.ipynb", - "provenance": [] - }, - "kernelspec": { - "display_name": "Python 3.9.12 ('cirq-py39')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.12" - }, - "vscode": { - "interpreter": { - "hash": "3db3b90ce1706c237bee38396dbe8ac1e0f0d31a71caf46d5ee7d6851b595260" - } - } + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "8e3qhaan0Vwx" + }, + "source": [ + "# Analyzing Quantum Volume Errors\n", + "This notebook analyzes the error rates required for achieving Quantum Volume at a particular depth. For a given m = depth = number of qubits, plot the HOG for np.logspace outputs to view when it crosses the 2/3rds probability threshold." + ] }, - "nbformat": 4, - "nbformat_minor": 0 + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "bd9529db1c0b" + }, + "outputs": [], + "source": [ + "try:\n", + " import cirq\n", + "except ImportError:\n", + " print(\"installing cirq...\")\n", + " !pip install --quiet cirq\n", + " print(\"installed cirq.\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "1QezTbjO0Vw4" + }, + "outputs": [], + "source": [ + "import cirq\n", + "import cirq_google\n", + "\n", + "# Configuration parameters. Feel free to mess with these!\n", + "num_circuits = 10\n", + "depth = 4\n", + "num_samplers = 50\n", + "repetitions = 10_000\n", + "device = cirq_google.Sycamore\n", + "\n", + "print(f\"Configuration: depth {depth} with \" f\"{num_circuits} circuits of {num_samplers} samplers\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "rZ_7U7n90Vw5" + }, + "outputs": [], + "source": [ + "# Run the Quantum Volume algorithm over the above parameters.\n", + "\n", + "import numpy as np\n", + "from cirq.contrib import quantum_volume, routing\n", + "\n", + "errors = np.logspace(-1, -4, num=num_samplers)\n", + "samplers = [\n", + " cirq.DensityMatrixSimulator(\n", + " noise=cirq.ConstantQubitNoiseModel(qubit_noise_gate=cirq.DepolarizingChannel(p=error))\n", + " )\n", + " for error in errors\n", + "]\n", + "\n", + "\n", + "def optimize(circuit):\n", + " return cirq.optimize_for_target_gateset(circuit, gateset=cirq.SqrtIswapTargetGateset())\n", + "\n", + "\n", + "result = quantum_volume.calculate_quantum_volume(\n", + " num_circuits=num_circuits,\n", + " depth=depth,\n", + " num_qubits=depth,\n", + " device_graph=routing.gridqubits_to_graph_device(device.metadata.qubit_set),\n", + " samplers=samplers,\n", + " compiler=optimize,\n", + " repetitions=repetitions,\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "CvJvkMLx0Vw6" + }, + "outputs": [], + "source": [ + "# Create a chart that plots the HOG rate relative to the simulated error ratio.\n", + "\n", + "from matplotlib import pyplot as plt\n", + "import statistics\n", + "\n", + "\n", + "def chunks(l, n):\n", + " \"\"\"Yield successive n-sized chunks from l.\"\"\"\n", + " for i in range(0, len(l), n):\n", + " yield l[i : i + n]\n", + "\n", + "\n", + "split = chunks([res.sampler_result for res in result], num_circuits)\n", + "fig, axs = plt.subplots()\n", + "axs.plot(errors, [statistics.mean(chunk) for chunk in split])\n", + "\n", + "# Line markers for asymptotic ideal heavy output probability and the ideal Heavy\n", + "# Output Generation threshold.\n", + "axs.axhline((1 + np.log(2)) / 2, color='tab:green', label='Asymptotic ideal', linestyle='dashed')\n", + "axs.axhline(2 / 3, label='HOG threshold', color='k', linestyle='dotted')\n", + "plt.xscale('log')\n", + "axs.set_ybound(0.4, 1)\n", + "axs.set_xlabel(\"error rate\")\n", + "axs.set_ylabel(\"est. heavy output probability\")\n", + "fig.suptitle(f'HOG probability by simulated error rate for d={depth}')" + ] + } + ], + "metadata": { + "colab": { + "name": "quantum_volume_errors.ipynb", + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3.9.12 ('cirq-py39')", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.12" + }, + "vscode": { + "interpreter": { + "hash": "3db3b90ce1706c237bee38396dbe8ac1e0f0d31a71caf46d5ee7d6851b595260" + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 } diff --git a/examples/advanced/quantum_volume_routing.ipynb b/examples/advanced/quantum_volume_routing.ipynb index 31160af090c..5b0f77eb40f 100644 --- a/examples/advanced/quantum_volume_routing.ipynb +++ b/examples/advanced/quantum_volume_routing.ipynb @@ -39,13 +39,17 @@ "max_routing_attempts = 100\n", "routing_attempts = range(1, max_routing_attempts, 10)\n", "repetitions = 10_000\n", - "qubits = cirq.GridQubit.rect(3,2)\n", + "qubits = cirq.GridQubit.rect(3, 2)\n", + "\n", "\n", "def compiler(circuit):\n", - " return cirq.optimize_for_target_gateset(circuit, gateset=cirq.CZTargetGateset())\n", + " return cirq.optimize_for_target_gateset(circuit, gateset=cirq.CZTargetGateset())\n", + "\n", "\n", - "print(f\"Configuration: depth {depth} with \"\n", - " f\"{num_circuits} circuits of routing attempts {routing_attempts}\")" + "print(\n", + " f\"Configuration: depth {depth} with \"\n", + " f\"{num_circuits} circuits of routing attempts {routing_attempts}\"\n", + ")" ] }, { @@ -60,21 +64,27 @@ "from cirq.contrib import quantum_volume, routing\n", "\n", "samplers = [\n", - " cirq.DensityMatrixSimulator(noise=cirq.ConstantQubitNoiseModel(\n", - " qubit_noise_gate=cirq.DepolarizingChannel(p=.005)))]\n", + " cirq.DensityMatrixSimulator(\n", + " noise=cirq.ConstantQubitNoiseModel(qubit_noise_gate=cirq.DepolarizingChannel(p=0.005))\n", + " )\n", + "]\n", "\n", "results = []\n", "for r in routing_attempts:\n", " print(f\"Running with {r} routing attempt(s)\")\n", - " results.append(quantum_volume.calculate_quantum_volume(num_circuits=num_circuits,\n", - " depth=depth,\n", - " num_qubits=depth,\n", - " device_graph=routing.gridqubits_to_graph_device(qubits),\n", - " samplers=samplers,\n", - " compiler=compiler,\n", - " random_state=np.random.RandomState(52),\n", - " repetitions=repetitions,\n", - " routing_attempts=r))" + " results.append(\n", + " quantum_volume.calculate_quantum_volume(\n", + " num_circuits=num_circuits,\n", + " depth=depth,\n", + " num_qubits=depth,\n", + " device_graph=routing.gridqubits_to_graph_device(qubits),\n", + " samplers=samplers,\n", + " compiler=compiler,\n", + " random_state=np.random.RandomState(52),\n", + " repetitions=repetitions,\n", + " routing_attempts=r,\n", + " )\n", + " )" ] }, { @@ -98,10 +108,7 @@ "\n", "# Line markers for asymptotic ideal heavy output probability and the ideal Heavy\n", "# Output Generation threshold.\n", - "axs.axhline((1 + np.log(2)) / 2,\n", - " color='tab:green',\n", - " label='Asymptotic ideal',\n", - " linestyle='dashed')\n", + "axs.axhline((1 + np.log(2)) / 2, color='tab:green', label='Asymptotic ideal', linestyle='dashed')\n", "axs.axhline(2 / 3, label='HOG threshold', color='k', linestyle='dotted')\n", "axs.set_ybound(0.4, 1)\n", "axs.set_xlabel(\"Number of routing attempts\")\n", diff --git a/examples/direct_fidelity_estimation.ipynb b/examples/direct_fidelity_estimation.ipynb index d0225db7b41..2b82bb346dd 100644 --- a/examples/direct_fidelity_estimation.ipynb +++ b/examples/direct_fidelity_estimation.ipynb @@ -44,10 +44,12 @@ "import examples.direct_fidelity_estimation as dfe\n", "\n", "qubits = cirq.LineQubit.range(3)\n", - "circuit = cirq.Circuit(cirq.CNOT(qubits[0], qubits[2]),\n", - " cirq.Z(qubits[0]),\n", - " cirq.H(qubits[2]),\n", - " cirq.CNOT(qubits[2], qubits[1]))\n", + "circuit = cirq.Circuit(\n", + " cirq.CNOT(qubits[0], qubits[2]),\n", + " cirq.Z(qubits[0]),\n", + " cirq.H(qubits[2]),\n", + " cirq.CNOT(qubits[2], qubits[1]),\n", + ")\n", "\n", "SVGCircuit(circuit)" ] @@ -71,11 +73,12 @@ "source": [ "# We run the DFE:\n", "estimated_fidelity, intermediate_results = dfe.direct_fidelity_estimation(\n", - " circuit,\n", - " qubits,\n", - " sampler,\n", - " n_measured_operators=None, # None=returns all the Pauli strings\n", - " samples_per_term=0) # 0=use dense matrix simulator\n", + " circuit,\n", + " qubits,\n", + " sampler,\n", + " n_measured_operators=None, # None=returns all the Pauli strings\n", + " samples_per_term=0,\n", + ") # 0=use dense matrix simulator\n", "\n", "print('Estimated fidelity: %.2f' % (estimated_fidelity))" ] @@ -129,7 +132,10 @@ "outputs": [], "source": [ "for trial_result in intermediate_results.trial_results:\n", - " print('rho_i=%.3f\\tsigma_i=%.3f\\tPauli:%s' % (trial_result.pauli_trace.rho_i, trial_result.sigma_i, trial_result.pauli_trace.P_i))" + " print(\n", + " 'rho_i=%.3f\\tsigma_i=%.3f\\tPauli:%s'\n", + " % (trial_result.pauli_trace.rho_i, trial_result.sigma_i, trial_result.pauli_trace.P_i)\n", + " )" ] }, { diff --git a/examples/stabilizer_code.ipynb b/examples/stabilizer_code.ipynb index 3e0aae20db0..f000ed877c6 100644 --- a/examples/stabilizer_code.ipynb +++ b/examples/stabilizer_code.ipynb @@ -26,7 +26,7 @@ " !pip install --quiet cirq\n", " print(\"installed cirq.\")\n", " import cirq\n", - " \n", + "\n", "from cirq.contrib.svg import SVGCircuit\n", "import examples.stabilizer_code as sc" ] @@ -100,9 +100,7 @@ "source": [ "for initial_state in [0, 1]:\n", " results = cirq.Simulator().simulate(circuit, qubit_order=qubits, initial_state=initial_state)\n", - " print('%d becomes %s' % (initial_state, cirq.dirac_notation(results.state_vector())))\n", - " \n", - " " + " print('%d becomes %s' % (initial_state, cirq.dirac_notation(results.state_vector())))" ] }, { @@ -156,7 +154,7 @@ } ], "source": [ - "results = cirq.Simulator().simulate(circuit, qubit_order=(qubits+ancillas), initial_state=0)\n", + "results = cirq.Simulator().simulate(circuit, qubit_order=(qubits + ancillas), initial_state=0)\n", "print('%s' % (cirq.dirac_notation(results.state_vector())))" ] }, @@ -243,7 +241,9 @@ } ], "source": [ - "code = sc.StabilizerCode(group_generators=['XZZXI', 'IXZZX', 'XIXZZ', 'ZXIXZ'], correctable_errors=['X', 'Z'])\n", + "code = sc.StabilizerCode(\n", + " group_generators=['XZZXI', 'IXZZX', 'XIXZZ', 'ZXIXZ'], correctable_errors=['X', 'Z']\n", + ")\n", "\n", "additional_qubits = [cirq.NamedQubit(str(i)) for i in range(code.n - code.k)]\n", "unencoded_qubits = [cirq.NamedQubit('c')]\n", From d381630c11089b74549ca880f1a0fe146476745c Mon Sep 17 00:00:00 2001 From: Saurav Maheshkar Date: Wed, 9 Apr 2025 07:32:49 +0100 Subject: [PATCH 2/3] fix(check/format-incremental): SC2054 --- check/format-incremental | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/check/format-incremental b/check/format-incremental index 3c73dbc8136..cde35a313ba 100755 --- a/check/format-incremental +++ b/check/format-incremental @@ -130,7 +130,7 @@ echo "Running the black formatter... (version: $BLACKVERSION)" args=("${arg_color[@]}") if (( only_print == 1 )); then - args+=("--check" "--diff", "--ipynb") + args+=("--check" "--diff" "--ipynb") fi black "${args[@]}" "${format_files[@]}" From 088a3b8f4585d41850c6b00ffd4250a86f69be58 Mon Sep 17 00:00:00 2001 From: Saurav Maheshkar Date: Wed, 9 Apr 2025 07:39:47 +0100 Subject: [PATCH 3/3] fix(tests): add ipynb flag --- dev_tools/bash_scripts_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev_tools/bash_scripts_test.py b/dev_tools/bash_scripts_test.py index 1c8382e40d3..a699a73c0d8 100644 --- a/dev_tools/bash_scripts_test.py +++ b/dev_tools/bash_scripts_test.py @@ -579,7 +579,7 @@ def test_incremental_format_branch_selection(tmpdir_factory): ) assert result.returncode == 0 assert 'INTERCEPTED isort --color --check --diff alt.py' in result.stdout - assert 'INTERCEPTED black --color --check --diff alt.py' in result.stdout + assert 'INTERCEPTED black --color --check --diff --ipynb alt.py' in result.stdout assert result.stderr.startswith("Comparing against revision 'main' (merge base ")