Skip to content

Commit

Permalink
Merge branch 'master' into 2021-11-qubit-placement-a
Browse files Browse the repository at this point in the history
  • Loading branch information
CirqBot authored Dec 2, 2021
2 parents ee3b78e + 9053a27 commit f864215
Show file tree
Hide file tree
Showing 55 changed files with 1,503 additions and 125 deletions.
31 changes: 10 additions & 21 deletions check/format-incremental
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ for arg in "$@"; do
fi
done

typeset -a format_files
if (( only_changed == 1 )); then
# Figure out which branch to compare against.
if [ -z "${rev}" ]; then
Expand All @@ -79,28 +80,16 @@ if (( only_changed == 1 )); then
rev="${base}"
fi

# Get the modified and added python files. Lines in git diff --name-status look like this:
# M cirq/__init__.py
# A cirq/added.py
modified_files=$(git diff --name-status ${rev} -- | grep '\.py$' | grep -v '_pb2\.py$' | grep '^[MA].*$' | awk '{print $2}')

# Get the moved python files. Lines in git diff --name-status look like this:
# R100 cirq/_doc.py cirq/_doc2.py
moved_files=$(git diff --name-status ${rev} -- | grep '\.py$' | grep -v '_pb2\.py$' | grep '^R.*$' | awk '{print $3}')

format_files="$modified_files $moved_files"

# Get the modified, added and moved python files.
IFS=$'\n' read -r -d '' -a format_files < \
<(git diff --name-only --diff-filter=MAR ${rev} -- '*.py' ':(exclude)*_pb2.py')
else
echo -e "Formatting all python files." >&2
format_files=$(find . -name "*.py" | grep -v "_pb2\.py$")
IFS=$'\n' read -r -d '' -a format_files < \
<(git ls-files '*.py' ':(exclude)*_pb2.py')
fi

any_files=0
for format_file in ${format_files}; do
any_files=1
done

if (( any_files == 0 )); then
if (( ${#format_files[@]} == 0 )); then
echo -e "\033[32mNo files to format\033[0m."
exit 0
fi
Expand All @@ -110,7 +99,7 @@ if (( only_print == 1 )); then
flynt_args+=("--dry-run")
fi

flynt ${format_files} "${flynt_args[@]}"
flynt "${format_files[@]}" "${flynt_args[@]}"
FLYNTSTATUS=$?

echo "Running the black formatter..."
Expand All @@ -122,9 +111,9 @@ fi

# Warn users about bug in black: https://github.com/psf/black/issues/1629
# Once that is fixed upstream, we can just do:
# black "${args[@]}" ${format_files}
# black "${args[@]}" "${format_files[@]}"
# exit $?
LOGS="$(black "${args[@]}" ${format_files} 2>&1)"
LOGS="$(black "${args[@]}" "${format_files[@]}" 2>&1)"
BLACKSTATUS=$?
echo "${LOGS}"
if [[ "$BLACKSTATUS" == "123" && "$LOGS" =~ ^.*"INTERNAL ERROR: Black produced different code on the second pass of the formatter.".*$ ]]; then
Expand Down
9 changes: 5 additions & 4 deletions check/pylint-changed-files
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,17 @@ else
rev="${base}"
fi

changed=$(git diff --name-only ${rev} -- \
typeset -a changed
IFS=$'\n' read -r -d '' -a changed < \
<(git diff --name-only ${rev} -- \
| grep -E "^(cirq|dev_tools|examples).*.py$"
)

num_changed=$(echo -e "${changed[@]}" | wc -w)
num_changed=${#changed[@]}

# Run it.
echo "Found ${num_changed} lintable files associated with changes." >&2
if [ "${num_changed}" -eq 0 ]; then
exit 0
fi
env PYTHONPATH=dev_tools pylint --rcfile=dev_tools/conf/.pylintrc ${changed[@]}

env PYTHONPATH=dev_tools pylint --rcfile=dev_tools/conf/.pylintrc "${changed[@]}"
8 changes: 5 additions & 3 deletions check/pytest-changed-files
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ fi
echo "Comparing against revision '${rev}'." >&2

# Get the _test version of changed python files.
changed=$(git diff --name-only ${rev} -- \
typeset -a changed
IFS=$'\n' read -r -d '' -a changed < \
<(git diff --name-only ${rev} -- \
| grep "\.py$" \
| sed -e "s/\.py$/_test.py/" \
| sed -e "s/_test_test\.py$/_test.py/" \
Expand All @@ -65,7 +67,7 @@ if git diff --name-only "${rev}" -- | grep "__init__\.py$" > /dev/null; then
# Include global API tests when an __init__ file is touched.
changed+=('cirq-core/cirq/protocols/json_serialization_test.py')
fi
num_changed=$(echo -e "${changed[@]}" | wc -w)
num_changed=${#changed[@]}

# Run it.
echo "Found ${num_changed} test files associated with changes." >&2
Expand All @@ -75,4 +77,4 @@ fi

source dev_tools/pypath

pytest ${rest} ${changed[@]}
pytest ${rest} "${changed[@]}"
8 changes: 6 additions & 2 deletions check/pytest-changed-files-and-incremental-coverage
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,19 @@ else
fi

# Find involved files.
cov_changed_python_file_dirs=$(git diff --name-only "${rev}" -- \
typeset -a cov_changed_python_file_dirs
IFS=$'\n' read -r -d '' -a cov_changed_python_file_dirs < \
<(git diff --name-only "${rev}" -- \
| grep "\.py$" \
| grep -v "_pb2\.py$" \
| xargs -I {} dirname {} \
| perl -ne 'chomp(); if (-e $_) {print "--cov=$_\n"}' \
| sort \
| uniq \
)
changed_python_tests=$(git diff --name-only "${rev}" -- \
typeset -a changed_python_tests
IFS=$'\n' read -r -d '' -a changed_python_tests < \
<(git diff --name-only "${rev}" -- \
| grep "\.py$" \
| sed -e "s/\.py$/_test.py/" \
| sed -e "s/_test_test\.py$/_test.py/" \
Expand Down
9 changes: 4 additions & 5 deletions cirq-core/cirq/circuits/circuit_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def __post_init__(self):
try:
protocols.inverse(self.circuit.unfreeze())
except TypeError:
raise ValueError(f'repetitions are negative but the circuit is not invertible')
raise ValueError('repetitions are negative but the circuit is not invertible')

# Initialize repetition_ids to default, if unspecified. Else, validate their length.
loop_size = abs(self.repetitions)
Expand Down Expand Up @@ -278,9 +278,8 @@ def __repr__(self):

def __str__(self):
# TODO: support out-of-line subcircuit definition in string format.
header = self.circuit.diagram_name() + ':'
msg_lines = str(self.circuit).split('\n')
msg_width = max([len(header) - 4] + [len(line) for line in msg_lines])
msg_width = max([len(line) for line in msg_lines])
circuit_msg = '\n'.join(
'[ {line:<{width}} ]'.format(line=line, width=msg_width) for line in msg_lines
)
Expand All @@ -305,8 +304,8 @@ def dict_str(d: Dict) -> str:
# Only add loops if we haven't added repetition_ids.
args.append(f'loops={self.repetitions}')
if not args:
return f'{header}\n{circuit_msg}'
return f'{header}\n{circuit_msg}({", ".join(args)})'
return circuit_msg
return f'{circuit_msg}({", ".join(args)})'

def __hash__(self):
if self._hash is None:
Expand Down
29 changes: 10 additions & 19 deletions cirq-core/cirq/circuits/circuit_operation_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,12 +321,7 @@ def test_string_format():

fc0 = cirq.FrozenCircuit()
op0 = cirq.CircuitOperation(fc0)
assert (
str(op0)
== f"""\
{op0.circuit.diagram_name()}:
[ ]"""
)
assert str(op0) == f"[ ]"

fc0_global_phase_inner = cirq.FrozenCircuit(
cirq.GlobalPhaseOperation(1j), cirq.GlobalPhaseOperation(1j)
Expand All @@ -339,18 +334,16 @@ def test_string_format():
assert (
str(op0_global_phase_outer)
== f"""\
{op0_global_phase_outer.circuit.diagram_name()}:
[ ]
[ ]
[ global phase: -0.5π ]"""
[ ]
[ ]
[ global phase: -0.5π ]"""
)

fc1 = cirq.FrozenCircuit(cirq.X(x), cirq.H(y), cirq.CX(y, z), cirq.measure(x, y, z, key='m'))
op1 = cirq.CircuitOperation(fc1)
assert (
str(op1)
== f"""\
{op1.circuit.diagram_name()}:
[ 0: ───X───────M('m')─── ]
[ │ ]
[ 1: ───H───@───M──────── ]
Expand All @@ -359,7 +352,7 @@ def test_string_format():
)
assert (
repr(op1)
== f"""\
== """\
cirq.CircuitOperation(
circuit=cirq.FrozenCircuit([
cirq.Moment(
Expand Down Expand Up @@ -387,10 +380,9 @@ def test_string_format():
assert (
str(op2)
== f"""\
{op2.circuit.diagram_name()}:
[ 0: ───X───X─── ]
[ │ ]
[ 1: ───H───@─── ](qubit_map={{1: 2}}, parent_path=('outer', 'inner'),\
[ 0: ───X───X─── ]
[ │ ]
[ 1: ───H───@─── ](qubit_map={{1: 2}}, parent_path=('outer', 'inner'),\
repetition_ids=['a', 'b', 'c'])"""
)
assert (
Expand Down Expand Up @@ -427,8 +419,7 @@ def test_string_format():
assert (
str(op3)
== f"""\
{op3.circuit.diagram_name()}:
[ 0: ───X^b───M('m')─── ](qubit_map={{0: 1}}, \
[ 0: ───X^b───M('m')─── ](qubit_map={{0: 1}}, \
key_map={{m: p}}, params={{b: 2}})"""
)
assert (
Expand All @@ -448,7 +439,7 @@ def test_string_format():
op5 = cirq.CircuitOperation(fc5)
assert (
repr(op5)
== f"""\
== """\
cirq.CircuitOperation(
circuit=cirq.FrozenCircuit([
cirq.Moment(
Expand Down
30 changes: 14 additions & 16 deletions cirq-core/cirq/circuits/circuit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,14 +392,13 @@ def test_control_key_diagram_subcircuit():
cirq.testing.assert_has_diagram(
c,
"""
Circuit_0xfba37d11898c0e81:
[ 0: ───M─────── ]
0: ───[ ║ ]───
[ 1: ───╫───X─── ]
[ ║ ║ ]
[ a: ═══@═══^═══ ]
[ 0: ───M─────── ]
[ ║ ]
0: ───[ 1: ───╫───X─── ]───
[ ║ ║ ]
[ a: ═══@═══^═══ ]
1: ───#2────────────────────────────
1: ───#2───────────────────
""",
use_unicode_characters=True,
)
Expand All @@ -418,16 +417,15 @@ def test_control_key_diagram_subcircuit_layered():
cirq.testing.assert_has_diagram(
c,
"""
Circuit_0xa3bc42bd21c25cca:
[ 0: ───M─────── ]
0: ───M───[ ║ ]───────
║ [ 1: ───╫───X─── ]
║ [ ║ ║ ]
║ [ a: ═══@═══^═══ ]
[ 0: ───M─────── ]
[ ║ ]
0: ───M───[ 1: ───╫───X─── ]───────
║ [ ║ ║ ]
║ [ a: ═══@═══^═══ ]
║ ║
1: ───╫───#2────────────────────────────X───
║ ║
a: ═══@═══╩═════════════════════════════^═══
1: ───╫───#2───────────────────X───
║ ║ ║
a: ═══@═══╩════════════════════^═══
""",
use_unicode_characters=True,
)
Expand Down
5 changes: 0 additions & 5 deletions cirq-core/cirq/circuits/frozen_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,6 @@ def device(self) -> devices.Device:
def __hash__(self):
return hash((self.moments, self.device))

def diagram_name(self):
"""Name used to represent this in circuit diagrams."""
key = hash(self) & 0xFFFF_FFFF_FFFF_FFFF
return f'Circuit_0x{key:016x}'

# Memoized methods for commonly-retrieved properties.

def _num_qubits_(self) -> int:
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/routing/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,5 @@ def route_circuit(
if algo_name is not None:
router = ROUTERS[algo_name]
elif router is None:
raise ValueError(f'No routing algorithm specified.')
raise ValueError('No routing algorithm specified.')
return router(circuit, device_graph, **kwargs)
2 changes: 1 addition & 1 deletion cirq-core/cirq/interop/quirk/cells/input_rotation_cells.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def controlled_by(self, qubit: 'cirq.Qid'):

def operations(self) -> 'cirq.OP_TREE':
if self.register is None:
raise ValueError(f"Missing input 'a'")
raise ValueError("Missing input 'a'")
return QuirkInputRotationOperation(
self.identifier, self.register, self.base_operation, self.exponent_sign
)
Expand Down
4 changes: 4 additions & 0 deletions cirq-core/cirq/json_resolver_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ def _parallel_gate_op(gate, qubits):
import sympy

return {
'AnyIntegerPowerGateFamily': cirq.AnyIntegerPowerGateFamily,
'AmplitudeDampingChannel': cirq.AmplitudeDampingChannel,
'AnyUnitaryGateFamily': cirq.AnyUnitaryGateFamily,
'AsymmetricDepolarizingChannel': cirq.AsymmetricDepolarizingChannel,
'BitFlipChannel': cirq.BitFlipChannel,
'BitstringAccumulator': cirq.work.BitstringAccumulator,
Expand Down Expand Up @@ -81,6 +83,7 @@ def _parallel_gate_op(gate, qubits):
'MutableDensePauliString': cirq.MutableDensePauliString,
'MutablePauliString': cirq.MutablePauliString,
'ObservableMeasuredResult': cirq.work.ObservableMeasuredResult,
'GateFamily': cirq.GateFamily,
'GateOperation': cirq.GateOperation,
'GeneralizedAmplitudeDampingChannel': cirq.GeneralizedAmplitudeDampingChannel,
'GlobalPhaseOperation': cirq.GlobalPhaseOperation,
Expand Down Expand Up @@ -115,6 +118,7 @@ def _parallel_gate_op(gate, qubits):
'_PauliZ': cirq.ops.pauli_gates._PauliZ,
'ParamResolver': cirq.ParamResolver,
'ParallelGate': cirq.ParallelGate,
'ParallelGateFamily': cirq.ParallelGateFamily,
'PauliMeasurementGate': cirq.PauliMeasurementGate,
'PauliString': cirq.PauliString,
'PhaseDampingChannel': cirq.PhaseDampingChannel,
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/linalg/decompositions_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,7 @@ def test_scatter_plot_normalized_kak_interaction_coefficients():
ax = cirq.scatter_plot_normalized_kak_interaction_coefficients(data)
assert ax is not None
ax2 = cirq.scatter_plot_normalized_kak_interaction_coefficients(
data, s=1, c='blue', ax=ax, include_frame=False, label=f'test'
data, s=1, c='blue', ax=ax, include_frame=False, label='test'
)
assert ax2 is ax

Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/linalg/operator_spaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

def kron_bases(*bases: Dict[str, np.ndarray], repeat: int = 1) -> Dict[str, np.ndarray]:
"""Creates tensor product of bases."""
product_basis = {'': np.ones(1)}
product_basis = {'': np.array([[1]])}
for basis in bases * repeat:
product_basis = {
name1 + name2: np.kron(matrix1, matrix2)
Expand Down
4 changes: 1 addition & 3 deletions cirq-core/cirq/linalg/operator_spaces_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,7 @@ def test_kron_bases_consistency(basis1, basis2):
assert np.all(basis1[name] == basis2[name])


@pytest.mark.parametrize(
'basis,repeat', itertools.product((PAULI_BASIS, STANDARD_BASIS), range(1, 5))
)
@pytest.mark.parametrize('basis,repeat', itertools.product((PAULI_BASIS, STANDARD_BASIS), range(5)))
def test_kron_bases_repeat_sanity_checks(basis, repeat):
product_basis = cirq.kron_bases(basis, repeat=repeat)
assert len(product_basis) == 4 ** repeat
Expand Down
Loading

0 comments on commit f864215

Please sign in to comment.