Skip to content

Commit f904a09

Browse files
authored
Roll back the default on unitary to np.complex64, change default for final_state_vector (#5636)
Rolls back change in #5426 that set the default precision on `Circuit#unitary` to `np.complex128`. Also sets the default on `Circuit#final_state_vector` to `np.complex128`. There was a deprecation warning that this was going to be downgraded to `np.complex64`,, but this will now remain `np.complex128`. This is breaking in that is someone explicitly passed `dtype=None` to this method it would now break. Rolls back #5426 #5616 #5537 #5535
1 parent 3744981 commit f904a09

39 files changed

+83
-166
lines changed

cirq-core/cirq/circuits/circuit.py

+7-14
Original file line numberDiff line numberDiff line change
@@ -1003,7 +1003,7 @@ def unitary(
10031003
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
10041004
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
10051005
ignore_terminal_measurements: bool = True,
1006-
dtype: Type[np.complexfloating] = np.complex64,
1006+
dtype: Type[np.complexfloating] = np.complex128,
10071007
) -> np.ndarray:
10081008
"""Converts the circuit into a unitary matrix, if possible.
10091009
@@ -1018,10 +1018,11 @@ def unitary(
10181018
ignore_terminal_measurements: When set, measurements at the end of
10191019
the circuit are ignored instead of causing the method to
10201020
fail.
1021-
dtype: The numpy dtype for the returned unitary. `dtype` must be
1022-
a complex np.dtype, unless all operations in the circuit have
1023-
unitary matrices with exclusively real coefficients
1024-
(e.g. an H + TOFFOLI circuit).
1021+
dtype: The numpy dtype for the returned unitary. Defaults to
1022+
np.complex128. Specifying np.complex64 will run faster at the
1023+
cost of precision. `dtype` must be a complex np.dtype, unless
1024+
all operations in the circuit have unitary matrices with
1025+
exclusively real coefficients (e.g. an H + TOFFOLI circuit).
10251026
10261027
Returns:
10271028
A (possibly gigantic) 2d numpy array corresponding to a matrix
@@ -1093,7 +1094,7 @@ def final_state_vector(
10931094
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
10941095
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
10951096
ignore_terminal_measurements: Optional[bool] = None,
1096-
dtype: Optional[Type[np.complexfloating]] = None,
1097+
dtype: Type[np.complexfloating] = np.complex128,
10971098
param_resolver: 'cirq.ParamResolverOrSimilarType' = None,
10981099
seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
10991100
) -> np.ndarray:
@@ -1143,14 +1144,6 @@ def final_state_vector(
11431144
)
11441145
ignore_terminal_measurements = True
11451146

1146-
if dtype is None:
1147-
_compat._warn_or_error(
1148-
'`dtype` will default to np.complex64 in v0.16. '
1149-
'To use the previous default, please explicitly include '
1150-
'`dtype=np.complex128` when calling this method.'
1151-
)
1152-
dtype = np.complex128
1153-
11541147
from cirq.sim.mux import final_state_vector
11551148

11561149
program = Circuit(cirq.I(q) for q in qubits_that_should_be_present) + self

cirq-core/cirq/circuits/circuit_test.py

-56
Original file line numberDiff line numberDiff line change
@@ -2957,62 +2957,6 @@ def test_final_state_vector(circuit_cls):
29572957
)
29582958

29592959

2960-
@pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit])
2961-
def test_final_state_vector_deprecated_params(circuit_cls):
2962-
a = cirq.NamedQubit('a')
2963-
b = cirq.NamedQubit('b')
2964-
# Extra qubits.
2965-
cirq.testing.assert_allclose_up_to_global_phase(
2966-
circuit_cls().final_state_vector(ignore_terminal_measurements=False, dtype=np.complex128),
2967-
np.array([1]),
2968-
atol=1e-8,
2969-
)
2970-
with cirq.testing.assert_deprecated("Inject identity operators", deadline="v0.16"):
2971-
cirq.testing.assert_allclose_up_to_global_phase(
2972-
circuit_cls().final_state_vector(
2973-
qubits_that_should_be_present=[a],
2974-
ignore_terminal_measurements=False,
2975-
dtype=np.complex128,
2976-
),
2977-
np.array([1, 0]),
2978-
atol=1e-8,
2979-
)
2980-
with cirq.testing.assert_deprecated("Inject identity operators", deadline="v0.16"):
2981-
cirq.testing.assert_allclose_up_to_global_phase(
2982-
circuit_cls(cirq.X(b)).final_state_vector(
2983-
qubits_that_should_be_present=[a],
2984-
ignore_terminal_measurements=False,
2985-
dtype=np.complex128,
2986-
),
2987-
np.array([0, 1, 0, 0]),
2988-
atol=1e-8,
2989-
)
2990-
2991-
with cirq.testing.assert_deprecated("To drop terminal measurements", deadline="v0.16"):
2992-
cirq.testing.assert_allclose_up_to_global_phase(
2993-
circuit_cls(cirq.X(a), cirq.measure(a)).final_state_vector(dtype=np.complex128),
2994-
np.array([0, 1]),
2995-
atol=1e-8,
2996-
)
2997-
2998-
with cirq.testing.assert_deprecated("`dtype` will default to np.complex64", deadline="v0.16"):
2999-
cirq.testing.assert_allclose_up_to_global_phase(
3000-
circuit_cls(cirq.X(a)).final_state_vector(ignore_terminal_measurements=False),
3001-
np.array([0, 1]),
3002-
atol=1e-8,
3003-
)
3004-
3005-
# Non-keyword args.
3006-
with cirq.testing.assert_deprecated("Only use keyword arguments", deadline="v0.16"):
3007-
cirq.testing.assert_allclose_up_to_global_phase(
3008-
circuit_cls(cirq.X(a) ** 0.5).final_state_vector(
3009-
1, ignore_terminal_measurements=False, dtype=np.complex128
3010-
),
3011-
np.array([1, 1j]) * np.sqrt(0.5),
3012-
atol=1e-8,
3013-
)
3014-
3015-
30162960
@pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit])
30172961
@pytest.mark.parametrize('resolve_fn', [cirq.resolve_parameters, cirq.resolve_parameters_once])
30182962
def test_is_parameterized(circuit_cls, resolve_fn):

cirq-core/cirq/contrib/acquaintance/executor_test.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -119,9 +119,7 @@ def test_executor_random(
119119
circuit.append(cca.LinearPermutationGate(num_qubits, permutation)(*qubits))
120120
actual_unitary = circuit.unitary()
121121

122-
np.testing.assert_allclose(
123-
actual=actual_unitary, desired=expected_unitary, verbose=True, atol=1e-6
124-
)
122+
np.testing.assert_allclose(actual=actual_unitary, desired=expected_unitary, verbose=True)
125123

126124

127125
def test_acquaintance_operation():

cirq-core/cirq/contrib/paulistring/clifford_optimize_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -121,4 +121,4 @@ def test_optimize_large_circuit():
121121

122122
c_opt = clifford_optimized_circuit(c_orig)
123123

124-
cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-6)
124+
cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7)

cirq-core/cirq/contrib/paulistring/optimize_test.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,17 @@ def test_optimize():
4848

4949
c_opt = optimized_circuit(c_orig)
5050

51-
cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-6)
51+
cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7)
5252

5353
# TODO(#5546) Fix '[Z]^1' (should be 'Z')
5454
cirq.testing.assert_has_diagram(
5555
c_opt,
5656
"""
57-
0: ───X^0.5────────────@──────────────────────────────────────────────
57+
0: ───X^0.5────────────@────────────────────────────────────────
5858
59-
1: ───@───────X^-0.5───@───@────────────────@───Z^-0.5────────────────
59+
1: ───@───────X^-0.5───@───@────────────────@───Z^-0.5──────────
6060
│ │ │
61-
2: ───@────────────────────@───[X]^(-7/8)───@───[X]^-0.25───[Z]^(1)───
61+
2: ───@────────────────────@───[X]^(-7/8)───@───[X]^-0.25───Z───
6262
""",
6363
)
6464

@@ -69,7 +69,7 @@ def test_optimize_large_circuit():
6969

7070
c_opt = optimized_circuit(c_orig)
7171

72-
cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-6)
72+
cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7)
7373

7474
assert (
7575
sum(
@@ -87,7 +87,7 @@ def test_repeat_limit():
8787

8888
c_opt = optimized_circuit(c_orig, repeat=1)
8989

90-
cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-6)
90+
cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7)
9191

9292
assert (
9393
sum(

cirq-core/cirq/contrib/paulistring/pauli_string_dag_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,5 @@ def test_pauli_string_dag_from_circuit():
2626
c_left_reordered = c_left_dag.to_circuit()
2727

2828
cirq.testing.assert_allclose_up_to_global_phase(
29-
c_left.unitary(), c_left_reordered.unitary(), atol=1e-6
29+
c_left.unitary(), c_left_reordered.unitary(), atol=1e-7
3030
)

cirq-core/cirq/contrib/paulistring/pauli_string_optimize_test.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def test_optimize():
3737
c_opt = pauli_string_optimized_circuit(c_orig)
3838

3939
cirq.testing.assert_allclose_up_to_global_phase(
40-
c_orig.unitary(), c_expected.unitary(), atol=1e-6
40+
c_orig.unitary(), c_expected.unitary(), atol=1e-7
4141
)
4242

4343
cirq.testing.assert_has_diagram(
@@ -81,4 +81,4 @@ def test_optimize_large_circuit():
8181

8282
c_opt = pauli_string_optimized_circuit(c_orig)
8383

84-
cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-6)
84+
cirq.testing.assert_allclose_up_to_global_phase(c_orig.unitary(), c_opt.unitary(), atol=1e-7)

cirq-core/cirq/contrib/paulistring/separate_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def test_toffoli_separate():
2323
c_left, c_right = convert_and_separate_circuit(circuit)
2424

2525
cirq.testing.assert_allclose_up_to_global_phase(
26-
circuit.unitary(), (c_left + c_right).unitary(), atol=1e-6
26+
circuit.unitary(), (c_left + c_right).unitary(), atol=1e-7
2727
)
2828

2929
assert all(isinstance(op, cirq.PauliStringPhasor) for op in c_left.all_operations())

cirq-core/cirq/contrib/qasm_import/qasm_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,6 @@ def test_consistency_with_qasm_output_and_qiskit():
5151
circuit2 = circuit_from_qasm(qasm)
5252

5353
cirq_unitary = cirq.unitary(circuit2)
54-
ct.assert_allclose_up_to_global_phase(cirq_unitary, cirq.unitary(circuit1), atol=1e-6)
54+
ct.assert_allclose_up_to_global_phase(cirq_unitary, cirq.unitary(circuit1), atol=1e-8)
5555

5656
cq.assert_qiskit_parsed_qasm_consistent_with_unitary(qasm, cirq_unitary)

cirq-core/cirq/ion/convert_to_ion_gates_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def test_convert_to_ion_gates():
8888
atol=1e-4,
8989
)
9090
assert cirq.allclose_up_to_global_phase(
91-
cirq.unitary(cirq.Circuit(rcnot)), cirq.unitary(OtherCNOT().on(q0, q1)), atol=1e-6
91+
cirq.unitary(cirq.Circuit(rcnot)), cirq.unitary(OtherCNOT().on(q0, q1)), atol=1e-7
9292
)
9393

9494

cirq-core/cirq/linalg/decompositions.py

+3-11
Original file line numberDiff line numberDiff line change
@@ -549,8 +549,6 @@ def scatter_plot_normalized_kak_interaction_coefficients(
549549
*,
550550
include_frame: bool = True,
551551
ax: Optional[plt.Axes] = None,
552-
rtol: float = 1e-5,
553-
atol: float = 1e-6,
554552
**kwargs,
555553
):
556554
r"""Plots the interaction coefficients of many two-qubit operations.
@@ -592,12 +590,6 @@ def scatter_plot_normalized_kak_interaction_coefficients(
592590
wireframe. Defaults to `True`.
593591
ax: A matplotlib 3d axes object to plot into. If not specified, a new
594592
figure is created, plotted, and shown.
595-
rtol: Per-matrix-entry relative tolerance on equality used if the
596-
kak decomposition is calculated from the `interactions`.
597-
atol: Per-matrix-entry absolute tolerance on equality used if the
598-
kak decomposition is calculated from the `interaction`s. T
599-
This determines how close $k_x$ must be to π/4 to guarantee
600-
$k_z$ ≥ 0. Must be non-negative.
601593
602594
**kwargs: Arguments forwarded into the call to `scatter` that plots the
603595
points. Working arguments include color `c='blue'`, scale `s=2`,
@@ -671,7 +663,7 @@ def coord_transform(
671663
else:
672664
interactions_extracted = [interactions]
673665

674-
points = kak_vector(interactions_extracted, rtol=rtol, atol=atol) * 4 / np.pi
666+
points = kak_vector(interactions_extracted) * 4 / np.pi
675667

676668
ax.scatter(*coord_transform(points), **kwargs)
677669
ax.set_xlim(0, +1)
@@ -819,7 +811,7 @@ def kak_decomposition(
819811
],
820812
*,
821813
rtol: float = 1e-5,
822-
atol: float = 1e-6,
814+
atol: float = 1e-8,
823815
check_preconditions: bool = True,
824816
) -> KakDecomposition:
825817
"""Decomposes a 2-qubit unitary into 1-qubit ops and XX/YY/ZZ interactions.
@@ -955,7 +947,7 @@ def kak_vector(
955947

956948
if check_preconditions:
957949
actual = np.einsum('...ba,...bc', unitary.conj(), unitary) - np.eye(4)
958-
if not np.allclose(np.zeros_like(actual), actual, rtol=rtol, atol=atol):
950+
if not np.allclose(actual, np.zeros_like(actual), rtol=rtol, atol=atol):
959951
raise ValueError(
960952
'Input must correspond to a 4x4 unitary matrix or tensor of '
961953
f'unitary matrices. Received input:\n{unitary}'

cirq-core/cirq/linalg/decompositions_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -782,4 +782,4 @@ def test_extract_right_diag(u):
782782
assert cirq.num_cnots_required(u) == 3
783783
diag = cirq.linalg.extract_right_diag(u)
784784
assert cirq.is_diagonal(diag)
785-
assert cirq.num_cnots_required(u @ diag, atol=1e-6) == 2
785+
assert cirq.num_cnots_required(u @ diag) == 2

cirq-core/cirq/ops/diagonal_gate_test.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def test_decomposition_unitary(n):
5454

5555
# For large qubit counts, the decomposed circuit is rather large, so we lose a lot of
5656
# precision.
57-
np.testing.assert_allclose(decomposed_f, expected_f, atol=5e-6)
57+
np.testing.assert_allclose(decomposed_f, expected_f)
5858

5959

6060
@pytest.mark.parametrize('n', [1, 2, 3, 4])
@@ -65,7 +65,7 @@ def test_diagonal_exponent(n):
6565
sqrt_diagonal_gate = diagonal_gate**0.5
6666

6767
expected_angles = [prime / 2 for prime in diagonal_angles]
68-
np.testing.assert_allclose(expected_angles, sqrt_diagonal_gate._diag_angles_radians, atol=1e-6)
68+
np.testing.assert_allclose(expected_angles, sqrt_diagonal_gate._diag_angles_radians, atol=1e-8)
6969

7070
assert cirq.pow(cirq.DiagonalGate(diagonal_angles), "test", None) is None
7171

@@ -80,7 +80,7 @@ def test_decomposition_diagonal_exponent(n):
8080
expected_f = [np.exp(1j * angle / 2) for angle in diagonal_angles]
8181
decomposed_f = cirq.unitary(decomposed_circ).diagonal()
8282

83-
np.testing.assert_allclose(decomposed_f, expected_f, atol=1e-6)
83+
np.testing.assert_allclose(decomposed_f, expected_f)
8484

8585

8686
@pytest.mark.parametrize('n', [1, 2, 3, 4])
@@ -99,7 +99,7 @@ def test_decomposition_with_parameterization(n):
9999
resolved_op = cirq.resolve_parameters(parameterized_op, resolver)
100100
resolved_circuit = cirq.resolve_parameters(decomposed_circuit, resolver)
101101
np.testing.assert_allclose(
102-
cirq.unitary(resolved_op), cirq.unitary(resolved_circuit), atol=1e-6
102+
cirq.unitary(resolved_op), cirq.unitary(resolved_circuit), atol=1e-8
103103
)
104104

105105

cirq-core/cirq/ops/fsim_gate_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,7 @@ def test_phased_fsim_from_fsim_rz(theta, phi, rz_angles_before, rz_angles_after)
317317
cirq.rz(rz_angles_after[0]).on(q0),
318318
cirq.rz(rz_angles_after[1]).on(q1),
319319
)
320-
cirq.testing.assert_allclose_up_to_global_phase(cirq.unitary(f), cirq.unitary(c), atol=1e-6)
320+
cirq.testing.assert_allclose_up_to_global_phase(cirq.unitary(f), cirq.unitary(c), atol=1e-8)
321321

322322

323323
@pytest.mark.parametrize(

cirq-core/cirq/ops/matrix_gates.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def __init__(
5656
name: str = None,
5757
qid_shape: Optional[Iterable[int]] = None,
5858
unitary_check_rtol: float = 1e-5,
59-
unitary_check_atol: float = 1e-6,
59+
unitary_check_atol: float = 1e-8,
6060
) -> None:
6161
"""Initializes a matrix gate.
6262

cirq-core/cirq/ops/parallel_gate_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def test_unitary(gate, num_copies, qubits):
119119
step = gate.num_qubits()
120120
qubit_lists = [qubits[i * step : (i + 1) * step] for i in range(num_copies)]
121121
np.testing.assert_allclose(
122-
cirq.unitary(g), cirq.unitary(cirq.Circuit(gate.on_each(qubit_lists))), atol=1e-6
122+
cirq.unitary(g), cirq.unitary(cirq.Circuit(gate.on_each(qubit_lists))), atol=1e-8
123123
)
124124

125125

cirq-core/cirq/ops/phased_x_gate_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ def test_parameterize(resolve_fn, global_shift):
176176
np.testing.assert_allclose(
177177
cirq.unitary(resolved_gate(q)),
178178
cirq.unitary(resolve_fn(parameterized_decomposed_circuit, resolver)),
179-
atol=1e-6,
179+
atol=1e-8,
180180
)
181181

182182
unparameterized_gate = cirq.PhasedXPowGate(

cirq-core/cirq/ops/two_qubit_diagonal_gate_test.py

-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@ def test_parameterized_decompose():
5151
np.testing.assert_allclose(
5252
cirq.unitary(cirq.resolve_parameters(parameterized_op, resolver)),
5353
cirq.unitary(cirq.resolve_parameters(decomposed_circuit, resolver)),
54-
atol=1e-6,
5554
)
5655

5756

cirq-core/cirq/optimizers/merge_interactions_test.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def assert_optimization_not_broken(circuit):
5454
cirq.MergeInteractions().optimize_circuit(circuit)
5555
u_after = circuit.unitary()
5656

57-
cirq.testing.assert_allclose_up_to_global_phase(u_before, u_after, atol=1e-6)
57+
cirq.testing.assert_allclose_up_to_global_phase(u_before, u_after, atol=1e-8)
5858

5959

6060
def test_clears_paired_cnot():
@@ -254,4 +254,4 @@ def clean_up(operations):
254254

255255
u_before = c_orig.unitary()
256256
u_after = circuit[1:-1].unitary()
257-
cirq.testing.assert_allclose_up_to_global_phase(u_before, u_after, atol=1e-6)
257+
cirq.testing.assert_allclose_up_to_global_phase(u_before, u_after, atol=1e-8)

cirq-core/cirq/testing/circuit_compare_test.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -126,13 +126,12 @@ def test_measuring_qubits():
126126
'circuit', [cirq.testing.random_circuit(cirq.LineQubit.range(2), 4, 0.5) for _ in range(5)]
127127
)
128128
def test_random_same_matrix(circuit):
129-
circuit_copy = circuit.copy()
130129
a, b = cirq.LineQubit.range(2)
131130
same = cirq.Circuit(
132131
cirq.MatrixGate(circuit.unitary(qubits_that_should_be_present=[a, b])).on(a, b)
133132
)
134133

135-
cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(circuit_copy, same)
134+
cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(circuit, same)
136135

137136
mutable_circuit = circuit.copy()
138137
mutable_circuit.append(cirq.measure(a))

cirq-core/cirq/testing/consistent_decomposition.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,10 @@ def assert_decompose_is_consistent_with_unitary(val: Any, ignoring_global_phase:
4343
actual = circuits.Circuit(dec).unitary(qubit_order=qubits)
4444

4545
if ignoring_global_phase:
46-
lin_alg_utils.assert_allclose_up_to_global_phase(actual, expected, atol=1e-6)
46+
lin_alg_utils.assert_allclose_up_to_global_phase(actual, expected, atol=1e-8)
4747
else:
4848
# coverage: ignore
49-
np.testing.assert_allclose(actual, expected, atol=1e-6)
49+
np.testing.assert_allclose(actual, expected, atol=1e-8)
5050

5151

5252
def _known_gate_with_no_decomposition(val: Any):

0 commit comments

Comments
 (0)