Skip to content

feat(fmt): add black[jupyter] as a formatting tool #7256

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion check/format-incremental
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The --ipynb option makes black execution fail as it considers all files to be jupyter notebooks. Please remove.

The format_files array needs to include the .ipynb files to get them checked and formatted. Please make sure these do not leak to isort_files, because isort does not seem to work with notebooks. For now, let isort look only at the python files.

fi

black "${args[@]}" "${format_files[@]}"
Expand Down
36 changes: 16 additions & 20 deletions cirq-core/cirq/contrib/quimb/Cirq-to-Tensor-Networks.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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].\")"
]
},
{
Expand Down Expand Up @@ -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))"
]
},
{
Expand Down Expand Up @@ -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))"
]
},
{
Expand All @@ -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))"
]
},
{
Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -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",
Expand All @@ -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()"
]
Expand Down
48 changes: 26 additions & 22 deletions cirq-core/cirq/contrib/quimb/Contract-a-Grid-Circuit.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
")"
]
},
{
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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))"
Expand All @@ -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",
Expand Down Expand Up @@ -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"
]
},
{
Expand All @@ -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"
]
},
{
Expand Down Expand Up @@ -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",
")"
]
},
{
Expand Down
40 changes: 22 additions & 18 deletions cirq-core/cirq/contrib/svg/example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
")"
]
},
{
Expand All @@ -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",
")"
]
}
],
Expand Down
20 changes: 10 additions & 10 deletions cirq-web/bloch_sphere_example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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)"
]
},
Expand Down
16 changes: 10 additions & 6 deletions cirq-web/circuit_example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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)"
]
},
{
Expand All @@ -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)"
]
Expand Down
2 changes: 1 addition & 1 deletion dev_tools/bash_scripts_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ")


Expand Down
2 changes: 1 addition & 1 deletion dev_tools/requirements/deps/format.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
black==25.1.0
black[jupyter]==25.1.0
isort[colors]~=6.0.1
2 changes: 1 addition & 1 deletion docs/_template.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading