Skip to content
Merged
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
4 changes: 2 additions & 2 deletions cirq-aqt/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import pathlib
import runpy

from setuptools import find_packages, setup
Expand All @@ -27,8 +28,7 @@
)

# README file as long_description.
with open('README.md', encoding='utf-8') as file:
long_description = file.read()
long_description = pathlib.Path('README.md').read_text(encoding='utf-8')

# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
Expand Down
3 changes: 1 addition & 2 deletions cirq-core/cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,8 +587,7 @@ def enqueue_next(qubit: cirq.Qid, moment: int) -> None:
next_moment = self.next_moment_operating_on([qubit], moment)
if next_moment is None:
end_frontier[qubit] = max(len(self), start_frontier[qubit])
if qubit in active:
active.remove(qubit)
active.discard(qubit)
else:
next_op = self.operation_at(qubit, next_moment)
assert next_op is not None
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/circuits/circuit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import itertools
import os
import pathlib
import time
from collections import defaultdict
from collections.abc import Iterator, Sequence
Expand Down Expand Up @@ -3670,8 +3671,7 @@ def test_save_qasm(tmpdir, circuit_cls) -> None:
circuit = circuit_cls(cirq.X(q0))

circuit.save_qasm(file_path)
with open(file_path, 'r') as f:
file_content = f.read()
file_content = pathlib.Path(file_path).read_text()
assert file_content == f"""// Generated from Cirq v{cirq.__version__}

OPENQASM 2.0;
Expand Down
5 changes: 2 additions & 3 deletions cirq-core/cirq/circuits/optimization_pass.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,9 @@ def optimize_circuit(self, circuit: cirq.Circuit) -> None:

flat_new_operations = tuple(ops.flatten_to_ops(new_operations))

new_qubits = set()
new_qubits: set[cirq.Qid] = set()
for flat_op in flat_new_operations:
for q in flat_op.qubits:
new_qubits.add(q)
new_qubits.update(flat_op.qubits)

if not new_qubits.issubset(opt.clear_qubits):
raise ValueError(
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/circuits/qasm_output_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from __future__ import annotations

import os
import pathlib
import re

import numpy as np
Expand Down Expand Up @@ -265,8 +266,7 @@ def test_save_to_file(tmpdir) -> None:
(q0,) = _make_qubits(1)
output = cirq.QasmOutput((), (q0,))
output.save(file_path)
with open(file_path, 'r') as f:
file_content = f.read()
file_content = pathlib.Path(file_path).read_text()
assert file_content == """OPENQASM 2.0;
include "qelib1.inc";

Expand Down
10 changes: 4 additions & 6 deletions cirq-core/cirq/contrib/acquaintance/inspection_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,7 @@ def get_logical_acquaintance_opportunities(
strategy: cirq.Circuit, initial_mapping: LogicalMapping
) -> set[frozenset[int]] | set[frozenset[cirq.Qid]]:
acquaintance_dag = get_acquaintance_dag(strategy, initial_mapping)
logical_acquaintance_opportunities = set()
for op in acquaintance_dag.all_operations():
logical_acquaintance_opportunities.add(
frozenset(op.logical_indices) # type: ignore[attr-defined]
)
return logical_acquaintance_opportunities
return {
frozenset(op.logical_indices) # type: ignore[attr-defined]
for op in acquaintance_dag.all_operations()
}
Original file line number Diff line number Diff line change
Expand Up @@ -588,19 +588,20 @@ def measure_pauli_strings(
normalized_circuits_to_pauli = _normalize_input_paulis(circuits_to_pauli)

# Extract unique qubit tuples from input pauli strings
unique_qubit_tuples = set()
if measure_on_full_support:
full_support: set[ops.Qid] = set()
for pauli_string_groups in normalized_circuits_to_pauli.values():
for pauli_strings in pauli_string_groups:
for pauli_string in pauli_strings:
full_support.update(pauli_string.qubits)
# One calibration group
unique_qubit_tuples.add(tuple(sorted(full_support)))
unique_qubit_tuples = {tuple(sorted(full_support))}
else:
for pauli_string_groups in normalized_circuits_to_pauli.values():
for pauli_strings in pauli_string_groups:
unique_qubit_tuples.add(tuple(_extract_readout_qubits(pauli_strings)))
unique_qubit_tuples = {
tuple(_extract_readout_qubits(pauli_strings))
for pauli_string_groups in normalized_circuits_to_pauli.values()
for pauli_strings in pauli_string_groups
}

# qubits_list is a list of qubit tuples
qubits_list = sorted(unique_qubit_tuples)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ def _format_exponent_for_display(self, exponent: Any) -> str:
is_symbolic_or_special = any(
char.isalpha()
for char in s_exponent
if char.lower() not in ["e"] # Exclude 'e' for scientific notation
if char.lower() != "e" # Exclude 'e' for scientific notation
)
if not is_symbolic_or_special: # If it looks like a number
try:
Expand Down Expand Up @@ -598,10 +598,8 @@ def _generate_latex_body(self) -> str:
active_chunk[i].append(moment_out[i])
moment_out = ["\\qw"] * self.num_qubits
spanned_qubits = set()
for i in range(min_qubit, max_qubit + 1):
spanned_qubits.add(i)
for q in op.qubits:
spanned_qubits.add(self.qubit_to_index[q])
spanned_qubits.update(range(min_qubit, max_qubit + 1))
spanned_qubits.update(self.qubit_to_index[q] for q in op.qubits)
op_rnd = self._render_operation(op)
for idx, tex in op_rnd.items():
moment_out[idx] = tex
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/phased_x_gate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ def test_exponent_consistency(exponent, phase_exponent) -> None:
"""Verifies that instances of PhasedX gate expose consistent exponents."""
g = cirq.PhasedXPowGate(exponent=exponent, phase_exponent=phase_exponent)
assert g.exponent in [exponent, -exponent]
assert g.phase_exponent in [cirq.value.canonicalize_half_turns(g.phase_exponent)]
assert g.phase_exponent == cirq.value.canonicalize_half_turns(g.phase_exponent)

g2 = cirq.PhasedXPowGate(exponent=g.exponent, phase_exponent=g.phase_exponent)
assert g == g2
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/testing/equivalent_basis_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,4 @@ def _sparse_computational_basis_map(
def _bin_dec(x: int | None, num_bits: int) -> str:
if x is None:
return 'None'
return f'0b{bin(x)[2:].zfill(num_bits)} ({x})'
return f"0b{f'{x:b}'.zfill(num_bits)} ({x})"
4 changes: 2 additions & 2 deletions cirq-core/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import pathlib
import runpy

from setuptools import find_packages, setup
Expand All @@ -28,8 +29,7 @@
)

# README file as long_description.
with open('README.md', encoding='utf-8') as file:
long_description = file.read()
long_description = pathlib.Path('README.md').read_text(encoding='utf-8')

# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
Expand Down
4 changes: 2 additions & 2 deletions cirq-google/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import pathlib
import runpy

from setuptools import find_packages, setup
Expand All @@ -27,8 +28,7 @@
)

# README file as long_description.
with open('README.md', encoding='utf-8') as file:
long_description = file.read()
long_description = pathlib.Path('README.md').read_text(encoding='utf-8')

# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
Expand Down
4 changes: 2 additions & 2 deletions cirq-ionq/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import pathlib
import runpy

from setuptools import find_packages, setup
Expand All @@ -25,8 +26,7 @@
description = 'A Cirq package to simulate and connect to IonQ quantum computers'

# README file as long_description.
with open('README.md', encoding='utf-8') as file:
long_description = file.read()
long_description = pathlib.Path('README.md').read_text(encoding='utf-8')

# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
Expand Down
2 changes: 1 addition & 1 deletion cirq-pasqal/cirq_pasqal/pasqal_qubits_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def test_pasqal_qubit_ordering_3d():
assert ThreeDQubit(0, 0, 1) >= ThreeDQubit(0, 1, 0)
assert ThreeDQubit(0, 1, 0) >= ThreeDQubit(1, 0, 0)
for i in range(8):
v = [int(x) for x in bin(i)[2:].zfill(3)]
v = [int(x) for x in f'{i:b}'.zfill(3)]

assert ThreeDQubit(0, 0, 0) <= ThreeDQubit(v[0], v[1], v[2])
assert ThreeDQubit(1, 1, 1) >= ThreeDQubit(v[0], v[1], v[2])
Expand Down
2 changes: 1 addition & 1 deletion cirq-pasqal/cirq_pasqal/pasqal_sampler_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def test_run_sweep(mock_post, mock_get):
sweep = cirq.Linspace(key='par', start=0.0, stop=1.0, length=2)

num = np.random.randint(0, 2**9)
binary = bin(num)[2:].zfill(9)
binary = f'{num:b}'.zfill(9)

device = cirq_pasqal.PasqalVirtualDevice(control_radius=1, qubits=qs)
ex_circuit = cirq.Circuit()
Expand Down
4 changes: 2 additions & 2 deletions cirq-pasqal/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import pathlib
import runpy

from setuptools import find_packages, setup
Expand All @@ -25,8 +26,7 @@
description = 'A Cirq package to simulate and connect to Pasqal quantum computers'

# README file as long_description.
with open('README.md', encoding='utf-8') as file:
long_description = file.read()
long_description = pathlib.Path('README.md').read_text(encoding='utf-8')

# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
Expand Down
12 changes: 4 additions & 8 deletions cirq-web/cirq_web/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,7 @@ def generate_html_file(
client_code = self.get_client_code()
contents = self._create_html_content(client_code)
path_of_html_file = os.path.join(output_directory, file_name)
with open(path_of_html_file, 'w', encoding='utf-8') as f:
f.write(contents)
Path(path_of_html_file).write_text(contents, encoding='utf-8')

if open_in_browser:
webbrowser.open(path_of_html_file, new=2)
Expand Down Expand Up @@ -118,9 +117,6 @@ def _to_script_tag(bundle_filename: str) -> str:
Returns:
The bundle file as string (readable by browser) wrapped in HTML script tags.
"""
bundle_file_path = os.path.join(_DIST_PATH, bundle_filename)
with open(bundle_file_path, 'r', encoding='utf-8') as bundle_file:
bundle_file_contents = bundle_file.read()
bundle_html = f'<script>{bundle_file_contents}</script>'

return bundle_html
bundle_file_path = _DIST_PATH.joinpath(bundle_filename)
bundle_file_contents = bundle_file_path.read_text(encoding='utf-8')
return f'<script>{bundle_file_contents}</script>'
3 changes: 1 addition & 2 deletions cirq-web/cirq_web/widget_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,7 @@ def test_generate_html_file_with_browser(tmpdir) -> None:

test_widget = FakeWidget()
test_html_path = test_widget.generate_html_file(str(path), 'test.html', open_in_browser=True)
with open(test_html_path, 'r', encoding='utf-8') as file:
actual = file.read()
actual = Path(test_html_path).read_text(encoding='utf-8')

expected = f"""
<meta charset="UTF-8">
Expand Down
4 changes: 2 additions & 2 deletions cirq-web/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import pathlib
import runpy

from setuptools import find_packages, setup
Expand All @@ -25,8 +26,7 @@
description = 'Web-based 3D visualization tools for Cirq.'

# README file as long_description.
with open('README.md', encoding='utf-8') as file:
long_description = file.read()
long_description = pathlib.Path('README.md').read_text(encoding='utf-8')

# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
Expand Down
13 changes: 7 additions & 6 deletions dev_tools/codeowners_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from __future__ import annotations

import os
import pathlib

import pytest

Expand Down Expand Up @@ -87,9 +88,9 @@ def test_codeowners(filepath, expected) -> None:
# will be skipped
codeowners = pytest.importorskip("codeowners")

with open(".github/CODEOWNERS", encoding="utf8") as f:
owners = codeowners.CodeOwners(f.read())
assert os.path.exists(
filepath
), f"{filepath} should exist to avoid creating/maintaining meaningless codeowners rules."
assert set(owners.of(filepath)) == expected
owners_text = pathlib.Path(".github/CODEOWNERS").read_text(encoding="utf8")
owners = codeowners.CodeOwners(owners_text)
assert os.path.exists(
filepath
), f"{filepath} should exist to avoid creating/maintaining meaningless codeowners rules."
assert set(owners.of(filepath)) == expected
3 changes: 1 addition & 2 deletions dev_tools/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,7 @@ def _check_for_reuse_or_recreate(env_dir: Path):
def _create_base_env(base_dir: Path, pip_install_args: tuple[str, ...]):
try:
create_virtual_env(str(base_dir), [], sys.executable, True)
with open(base_dir / "testrun.uid", mode="w", encoding="utf8") as f:
f.write(testrun_uid)
base_dir.joinpath("testrun.uid").write_text(testrun_uid, encoding="utf8")
if pip_install_args:
shell_tools.run([f"{base_dir}/bin/pip", "install", *pip_install_args])
except BaseException as ex:
Expand Down
4 changes: 2 additions & 2 deletions dev_tools/incremental_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from __future__ import annotations

import os.path
import pathlib
import re
from typing import cast

Expand Down Expand Up @@ -153,8 +154,7 @@ def get_incremental_uncovered_lines(

touched_lines = diff_to_new_interesting_lines(unified_diff_lines)

with open(abs_path, 'r', encoding="utf8") as actual_file:
ignored_lines = determine_ignored_lines(actual_file.read())
ignored_lines = determine_ignored_lines(pathlib.Path(abs_path).read_text(encoding="utf8"))

cover_path = abs_path + ',cover'
has_cover_file = os.path.isfile(cover_path)
Expand Down
3 changes: 1 addition & 2 deletions dev_tools/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,7 @@ def setup(**kwargs):
try:
setuptools.setup = setup
os.chdir(str(folder))
with open("setup.py", encoding="utf8") as file:
setup_py = file.read()
setup_py = Path("setup.py").read_text(encoding="utf8")
exec(setup_py, globals(), {})
assert setup_args, f"Invalid setup.py - setup() was not called in {folder}/setup.py!"
return setup_args
Expand Down
3 changes: 1 addition & 2 deletions dev_tools/modules_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,7 @@ def test_replace_version_errors() -> None:

@chdir(target_dir=None)
def test_error() -> None:
with open("setup.py", mode='w') as f:
f.write('name="test"')
Path("setup.py").write_text('name="test"')

with pytest.raises(AssertionError, match=r"Invalid setup.py - setup\(\) was not called.*"):
modules.main(["list", "--mode", "folder", "--include-parent"])
Loading
Loading