cirq-core 1.6.0.dev20250425004112__py3-none-any.whl → 1.6.0.dev20250429004516__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of cirq-core might be problematic. Click here for more details.
- cirq/_version.py +1 -1
- cirq/_version_test.py +1 -1
- cirq/protocols/decompose_protocol.py +3 -2
- cirq/protocols/measurement_key_protocol.py +8 -7
- cirq/protocols/pow_protocol.py +7 -7
- cirq/protocols/qasm.py +5 -3
- cirq/protocols/resolve_parameters.py +5 -3
- cirq/qis/clifford_tableau.py +11 -9
- cirq/qis/measures.py +7 -7
- cirq/qis/quantum_state_representation.py +4 -5
- cirq/qis/states.py +19 -17
- cirq/sim/classical_simulator.py +15 -14
- cirq/sim/clifford/clifford_simulator.py +19 -17
- cirq/sim/clifford/clifford_tableau_simulation_state.py +7 -4
- cirq/sim/clifford/stabilizer_ch_form_simulation_state.py +5 -3
- cirq/sim/clifford/stabilizer_sampler.py +6 -4
- cirq/sim/clifford/stabilizer_simulation_state.py +9 -9
- cirq/sim/clifford/stabilizer_state_ch_form.py +6 -4
- cirq/sim/density_matrix_simulation_state.py +17 -18
- cirq/sim/density_matrix_simulator.py +21 -19
- cirq/sim/density_matrix_utils.py +4 -2
- cirq/sim/mux.py +25 -23
- cirq/sim/simulation_product_state.py +12 -12
- cirq/sim/simulation_product_state_test.py +3 -3
- cirq/sim/simulation_state.py +23 -19
- cirq/sim/simulation_state_base.py +16 -12
- cirq/sim/simulation_state_test.py +1 -1
- cirq/sim/simulator.py +71 -72
- cirq/sim/simulator_base.py +22 -23
- cirq/sim/simulator_base_test.py +12 -9
- cirq/sim/simulator_test.py +12 -8
- cirq/sim/sparse_simulator.py +13 -11
- cirq/sim/state_vector.py +9 -6
- cirq/sim/state_vector_simulation_state.py +20 -20
- cirq/sim/state_vector_simulator.py +13 -10
- cirq/study/flatten_expressions.py +8 -5
- cirq/study/resolver.py +12 -9
- cirq/study/result.py +6 -3
- cirq/study/sweeps.py +17 -14
- cirq/testing/consistent_act_on_test.py +2 -2
- cirq/testing/consistent_controlled_gate_op_test.py +10 -6
- cirq/testing/lin_alg_utils.py +8 -7
- cirq/testing/random_circuit.py +17 -16
- cirq/testing/routing_devices.py +4 -1
- cirq/testing/sample_circuits.py +4 -1
- cirq/transformers/align.py +6 -4
- cirq/transformers/analytical_decompositions/clifford_decomposition.py +9 -7
- cirq/transformers/analytical_decompositions/controlled_gate_decomposition.py +15 -13
- cirq/transformers/analytical_decompositions/cphase_to_fsim.py +7 -5
- cirq/transformers/analytical_decompositions/quantum_shannon_decomposition.py +10 -8
- cirq/transformers/analytical_decompositions/single_to_two_qubit_isometry.py +6 -3
- cirq/transformers/analytical_decompositions/two_qubit_state_preparation.py +8 -10
- {cirq_core-1.6.0.dev20250425004112.dist-info → cirq_core-1.6.0.dev20250429004516.dist-info}/METADATA +1 -1
- {cirq_core-1.6.0.dev20250425004112.dist-info → cirq_core-1.6.0.dev20250429004516.dist-info}/RECORD +57 -57
- {cirq_core-1.6.0.dev20250425004112.dist-info → cirq_core-1.6.0.dev20250429004516.dist-info}/WHEEL +1 -1
- {cirq_core-1.6.0.dev20250425004112.dist-info → cirq_core-1.6.0.dev20250429004516.dist-info}/licenses/LICENSE +0 -0
- {cirq_core-1.6.0.dev20250425004112.dist-info → cirq_core-1.6.0.dev20250429004516.dist-info}/top_level.txt +0 -0
cirq/_version.py
CHANGED
cirq/_version_test.py
CHANGED
|
@@ -373,7 +373,7 @@ def decompose_once(
|
|
|
373
373
|
|
|
374
374
|
method = getattr(val, '_decompose_with_context_', None)
|
|
375
375
|
decomposed = NotImplemented if method is None else method(*args, **kwargs, context=context)
|
|
376
|
-
if decomposed is NotImplemented or None:
|
|
376
|
+
if decomposed is NotImplemented or decomposed is None:
|
|
377
377
|
method = getattr(val, '_decompose_', None)
|
|
378
378
|
decomposed = NotImplemented if method is None else method(*args, **kwargs)
|
|
379
379
|
|
|
@@ -389,7 +389,8 @@ def decompose_once(
|
|
|
389
389
|
)
|
|
390
390
|
raise TypeError(
|
|
391
391
|
f"object of type {type(val)} does have a _decompose_ method, "
|
|
392
|
-
"but it returned NotImplemented or None."
|
|
392
|
+
"but it returned NotImplemented or None. The value is not "
|
|
393
|
+
"convertible to simpler operations."
|
|
393
394
|
)
|
|
394
395
|
|
|
395
396
|
|
|
@@ -11,8 +11,11 @@
|
|
|
11
11
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
|
+
|
|
14
15
|
"""Protocol for object that have measurement keys."""
|
|
15
16
|
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
16
19
|
from types import NotImplementedType
|
|
17
20
|
from typing import Any, FrozenSet, Mapping, Optional, Tuple, TYPE_CHECKING, Union
|
|
18
21
|
|
|
@@ -60,7 +63,7 @@ class SupportsMeasurementKey(Protocol):
|
|
|
60
63
|
"""Return if this object is (or contains) a measurement."""
|
|
61
64
|
|
|
62
65
|
@doc_private
|
|
63
|
-
def _measurement_key_obj_(self) ->
|
|
66
|
+
def _measurement_key_obj_(self) -> cirq.MeasurementKey:
|
|
64
67
|
"""Return the key object that will be used to identify this measurement.
|
|
65
68
|
|
|
66
69
|
When a measurement occurs, either on hardware, or in a simulation,
|
|
@@ -71,7 +74,7 @@ class SupportsMeasurementKey(Protocol):
|
|
|
71
74
|
@doc_private
|
|
72
75
|
def _measurement_key_objs_(
|
|
73
76
|
self,
|
|
74
|
-
) -> Union[FrozenSet[
|
|
77
|
+
) -> Union[FrozenSet[cirq.MeasurementKey], NotImplementedType, None]:
|
|
75
78
|
"""Return the key objects for measurements performed by the receiving object.
|
|
76
79
|
|
|
77
80
|
When a measurement occurs, either on hardware, or in a simulation,
|
|
@@ -175,7 +178,7 @@ def measurement_key_name(val: Any, default: Any = RaiseTypeErrorIfNotProvided):
|
|
|
175
178
|
|
|
176
179
|
def _measurement_key_objs_from_magic_methods(
|
|
177
180
|
val: Any,
|
|
178
|
-
) -> Union[FrozenSet[
|
|
181
|
+
) -> Union[FrozenSet[cirq.MeasurementKey], NotImplementedType, None]:
|
|
179
182
|
"""Uses the measurement key related magic methods to get the `MeasurementKey`s for this
|
|
180
183
|
object."""
|
|
181
184
|
|
|
@@ -209,7 +212,7 @@ def _measurement_key_names_from_magic_methods(
|
|
|
209
212
|
return result
|
|
210
213
|
|
|
211
214
|
|
|
212
|
-
def measurement_key_objs(val: Any) -> FrozenSet[
|
|
215
|
+
def measurement_key_objs(val: Any) -> FrozenSet[cirq.MeasurementKey]:
|
|
213
216
|
"""Gets the measurement key objects of measurements within the given value.
|
|
214
217
|
|
|
215
218
|
Args:
|
|
@@ -316,9 +319,7 @@ def with_key_path_prefix(val: Any, prefix: Tuple[str, ...]):
|
|
|
316
319
|
|
|
317
320
|
|
|
318
321
|
def with_rescoped_keys(
|
|
319
|
-
val: Any,
|
|
320
|
-
path: Tuple[str, ...],
|
|
321
|
-
bindable_keys: Optional[FrozenSet['cirq.MeasurementKey']] = None,
|
|
322
|
+
val: Any, path: Tuple[str, ...], bindable_keys: Optional[FrozenSet[cirq.MeasurementKey]] = None
|
|
322
323
|
):
|
|
323
324
|
"""Rescopes any measurement and control keys to the provided path, given the existing keys.
|
|
324
325
|
|
cirq/protocols/pow_protocol.py
CHANGED
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
15
17
|
from typing import Any, Callable, Optional, overload, TYPE_CHECKING, TypeVar, Union
|
|
16
18
|
|
|
17
19
|
if TYPE_CHECKING:
|
|
@@ -26,29 +28,27 @@ TDefault = TypeVar('TDefault')
|
|
|
26
28
|
|
|
27
29
|
# pylint: disable=function-redefined, redefined-builtin
|
|
28
30
|
@overload
|
|
29
|
-
def pow(val:
|
|
31
|
+
def pow(val: cirq.Gate, exponent: Any) -> cirq.Gate:
|
|
30
32
|
pass
|
|
31
33
|
|
|
32
34
|
|
|
33
35
|
@overload
|
|
34
|
-
def pow(val:
|
|
36
|
+
def pow(val: cirq.Operation, exponent: Any) -> cirq.Operation:
|
|
35
37
|
pass
|
|
36
38
|
|
|
37
39
|
|
|
38
40
|
@overload
|
|
39
|
-
def pow(val:
|
|
41
|
+
def pow(val: cirq.Gate, exponent: Any, default: TDefault) -> Union[TDefault, cirq.Gate]:
|
|
40
42
|
pass
|
|
41
43
|
|
|
42
44
|
|
|
43
45
|
@overload
|
|
44
|
-
def pow(
|
|
45
|
-
val: 'cirq.Operation', exponent: Any, default: TDefault
|
|
46
|
-
) -> Union[TDefault, 'cirq.Operation']:
|
|
46
|
+
def pow(val: cirq.Operation, exponent: Any, default: TDefault) -> Union[TDefault, cirq.Operation]:
|
|
47
47
|
pass
|
|
48
48
|
|
|
49
49
|
|
|
50
50
|
@overload
|
|
51
|
-
def pow(val:
|
|
51
|
+
def pow(val: cirq.Circuit, exponent: int, default: TDefault) -> Union[TDefault, cirq.Circuit]:
|
|
52
52
|
pass
|
|
53
53
|
|
|
54
54
|
|
cirq/protocols/qasm.py
CHANGED
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
15
17
|
import string
|
|
16
18
|
from types import NotImplementedType
|
|
17
19
|
from typing import Any, Dict, Iterable, Optional, Tuple, TYPE_CHECKING, TypeVar, Union
|
|
@@ -36,7 +38,7 @@ class QasmArgs(string.Formatter):
|
|
|
36
38
|
self,
|
|
37
39
|
precision: int = 10,
|
|
38
40
|
version: str = '2.0',
|
|
39
|
-
qubit_id_map: Optional[Dict[
|
|
41
|
+
qubit_id_map: Optional[Dict[cirq.Qid, str]] = None,
|
|
40
42
|
meas_key_id_map: Optional[Dict[str, str]] = None,
|
|
41
43
|
meas_key_bitcount: Optional[Dict[str, int]] = None,
|
|
42
44
|
) -> None:
|
|
@@ -124,7 +126,7 @@ class SupportsQasmWithArgsAndQubits(Protocol):
|
|
|
124
126
|
|
|
125
127
|
@doc_private
|
|
126
128
|
def _qasm_(
|
|
127
|
-
self, qubits: Tuple[
|
|
129
|
+
self, qubits: Tuple[cirq.Qid], args: QasmArgs
|
|
128
130
|
) -> Union[None, NotImplementedType, str]:
|
|
129
131
|
pass
|
|
130
132
|
|
|
@@ -134,7 +136,7 @@ def qasm(
|
|
|
134
136
|
val: Any,
|
|
135
137
|
*,
|
|
136
138
|
args: Optional[QasmArgs] = None,
|
|
137
|
-
qubits: Optional[Iterable[
|
|
139
|
+
qubits: Optional[Iterable[cirq.Qid]] = None,
|
|
138
140
|
default: TDefault = RaiseTypeErrorIfNotProvided,
|
|
139
141
|
) -> Union[str, TDefault]:
|
|
140
142
|
"""Returns QASM code for the given value, if possible.
|
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
15
17
|
import numbers
|
|
16
18
|
from typing import AbstractSet, Any, cast, TYPE_CHECKING, TypeVar
|
|
17
19
|
|
|
@@ -48,7 +50,7 @@ class SupportsParameterization(Protocol):
|
|
|
48
50
|
"""
|
|
49
51
|
|
|
50
52
|
@doc_private
|
|
51
|
-
def _resolve_parameters_(self, resolver:
|
|
53
|
+
def _resolve_parameters_(self, resolver: cirq.ParamResolver, recursive: bool) -> Self:
|
|
52
54
|
"""Resolve the parameters in the effect."""
|
|
53
55
|
|
|
54
56
|
|
|
@@ -133,7 +135,7 @@ def parameter_symbols(val: Any) -> AbstractSet[sympy.Symbol]:
|
|
|
133
135
|
|
|
134
136
|
|
|
135
137
|
def resolve_parameters(
|
|
136
|
-
val: T, param_resolver:
|
|
138
|
+
val: T, param_resolver: cirq.ParamResolverOrSimilarType, recursive: bool = True
|
|
137
139
|
) -> T:
|
|
138
140
|
"""Resolves symbol parameters in the effect using the param resolver.
|
|
139
141
|
|
|
@@ -195,6 +197,6 @@ def resolve_parameters(
|
|
|
195
197
|
return val
|
|
196
198
|
|
|
197
199
|
|
|
198
|
-
def resolve_parameters_once(val: Any, param_resolver:
|
|
200
|
+
def resolve_parameters_once(val: Any, param_resolver: cirq.ParamResolverOrSimilarType):
|
|
199
201
|
"""Performs a single parameter resolution step using the param resolver."""
|
|
200
202
|
return resolve_parameters(val, param_resolver, False)
|
cirq/qis/clifford_tableau.py
CHANGED
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
15
17
|
import abc
|
|
16
18
|
from typing import Any, Dict, List, Optional, Sequence, TYPE_CHECKING
|
|
17
19
|
|
|
@@ -286,10 +288,10 @@ class CliffordTableau(StabilizerState):
|
|
|
286
288
|
and np.array_equal(self.zs, other.zs)
|
|
287
289
|
)
|
|
288
290
|
|
|
289
|
-
def __copy__(self) ->
|
|
291
|
+
def __copy__(self) -> CliffordTableau:
|
|
290
292
|
return self.copy()
|
|
291
293
|
|
|
292
|
-
def copy(self, deep_copy_buffers: bool = True) ->
|
|
294
|
+
def copy(self, deep_copy_buffers: bool = True) -> CliffordTableau:
|
|
293
295
|
state = CliffordTableau(self.n)
|
|
294
296
|
state.rs = self.rs.copy()
|
|
295
297
|
state.xs = self.xs.copy()
|
|
@@ -364,7 +366,7 @@ class CliffordTableau(StabilizerState):
|
|
|
364
366
|
|
|
365
367
|
return '\n'.join([title_row, divider, *contents]) + '\n'
|
|
366
368
|
|
|
367
|
-
def then(self, second:
|
|
369
|
+
def then(self, second: CliffordTableau) -> CliffordTableau:
|
|
368
370
|
"""Returns a composed CliffordTableau of this tableau and the second tableau.
|
|
369
371
|
|
|
370
372
|
Then composed tableau is equal to (up to global phase) the composed
|
|
@@ -431,7 +433,7 @@ class CliffordTableau(StabilizerState):
|
|
|
431
433
|
|
|
432
434
|
return merged_tableau
|
|
433
435
|
|
|
434
|
-
def inverse(self) ->
|
|
436
|
+
def inverse(self) -> CliffordTableau:
|
|
435
437
|
"""Returns the inverse Clifford tableau of this tableau."""
|
|
436
438
|
ret_table = CliffordTableau(num_qubits=self.n)
|
|
437
439
|
# It relies on the symplectic property of Clifford tableau.
|
|
@@ -450,7 +452,7 @@ class CliffordTableau(StabilizerState):
|
|
|
450
452
|
ret_table.rs = ret_table.then(self).rs
|
|
451
453
|
return ret_table
|
|
452
454
|
|
|
453
|
-
def __matmul__(self, second:
|
|
455
|
+
def __matmul__(self, second: CliffordTableau):
|
|
454
456
|
if not isinstance(second, CliffordTableau):
|
|
455
457
|
return NotImplemented
|
|
456
458
|
return second.then(self)
|
|
@@ -481,7 +483,7 @@ class CliffordTableau(StabilizerState):
|
|
|
481
483
|
self._xs[q1, :] ^= self._xs[q2, :]
|
|
482
484
|
self._zs[q1, :] ^= self._zs[q2, :]
|
|
483
485
|
|
|
484
|
-
def _row_to_dense_pauli(self, i: int) ->
|
|
486
|
+
def _row_to_dense_pauli(self, i: int) -> cirq.DensePauliString:
|
|
485
487
|
"""Return a dense Pauli string for the given row in the tableau.
|
|
486
488
|
|
|
487
489
|
Args:
|
|
@@ -509,12 +511,12 @@ class CliffordTableau(StabilizerState):
|
|
|
509
511
|
pauli_mask += "I"
|
|
510
512
|
return DensePauliString(pauli_mask, coefficient=coefficient)
|
|
511
513
|
|
|
512
|
-
def stabilizers(self) -> List[
|
|
514
|
+
def stabilizers(self) -> List[cirq.DensePauliString]:
|
|
513
515
|
"""Returns the stabilizer generators of the state. These
|
|
514
516
|
are n operators {S_1,S_2,...,S_n} such that S_i |psi> = |psi>"""
|
|
515
517
|
return [self._row_to_dense_pauli(i) for i in range(self.n, 2 * self.n)]
|
|
516
518
|
|
|
517
|
-
def destabilizers(self) -> List[
|
|
519
|
+
def destabilizers(self) -> List[cirq.DensePauliString]:
|
|
518
520
|
"""Returns the destabilizer generators of the state. These
|
|
519
521
|
are n operators {S_1,S_2,...,S_n} such that along with the stabilizer
|
|
520
522
|
generators above generate the full Pauli group on n qubits."""
|
|
@@ -662,7 +664,7 @@ class CliffordTableau(StabilizerState):
|
|
|
662
664
|
pass
|
|
663
665
|
|
|
664
666
|
def measure(
|
|
665
|
-
self, axes: Sequence[int], seed:
|
|
667
|
+
self, axes: Sequence[int], seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None
|
|
666
668
|
) -> List[int]:
|
|
667
669
|
return [self._measure(axis, random_state.parse_random_state(seed)) for axis in axes]
|
|
668
670
|
|
cirq/qis/measures.py
CHANGED
|
@@ -11,8 +11,10 @@
|
|
|
11
11
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
|
+
|
|
14
15
|
"""Measures on and between quantum states and operations."""
|
|
15
16
|
|
|
17
|
+
from __future__ import annotations
|
|
16
18
|
|
|
17
19
|
from typing import Optional, Tuple, TYPE_CHECKING
|
|
18
20
|
|
|
@@ -58,9 +60,7 @@ def _validate_int_state(state: int, qid_shape: Optional[Tuple[int, ...]]) -> Non
|
|
|
58
60
|
)
|
|
59
61
|
|
|
60
62
|
|
|
61
|
-
def _validate_product_state(
|
|
62
|
-
state: 'cirq.ProductState', qid_shape: Optional[Tuple[int, ...]]
|
|
63
|
-
) -> None:
|
|
63
|
+
def _validate_product_state(state: cirq.ProductState, qid_shape: Optional[Tuple[int, ...]]) -> None:
|
|
64
64
|
if qid_shape is not None and qid_shape != (2,) * len(state):
|
|
65
65
|
raise ValueError(
|
|
66
66
|
'Invalid state for given qid shape: '
|
|
@@ -70,8 +70,8 @@ def _validate_product_state(
|
|
|
70
70
|
|
|
71
71
|
|
|
72
72
|
def fidelity(
|
|
73
|
-
state1:
|
|
74
|
-
state2:
|
|
73
|
+
state1: cirq.QUANTUM_STATE_LIKE,
|
|
74
|
+
state2: cirq.QUANTUM_STATE_LIKE,
|
|
75
75
|
qid_shape: Optional[Tuple[int, ...]] = None,
|
|
76
76
|
validate: bool = True,
|
|
77
77
|
atol: float = 1e-7,
|
|
@@ -255,7 +255,7 @@ def _fidelity_state_vectors_or_density_matrices(state1: np.ndarray, state2: np.n
|
|
|
255
255
|
|
|
256
256
|
|
|
257
257
|
def von_neumann_entropy(
|
|
258
|
-
state:
|
|
258
|
+
state: cirq.QUANTUM_STATE_LIKE,
|
|
259
259
|
qid_shape: Optional[Tuple[int, ...]] = None,
|
|
260
260
|
validate: bool = True,
|
|
261
261
|
atol: float = 1e-7,
|
|
@@ -298,7 +298,7 @@ def von_neumann_entropy(
|
|
|
298
298
|
return 0.0
|
|
299
299
|
|
|
300
300
|
|
|
301
|
-
def entanglement_fidelity(operation:
|
|
301
|
+
def entanglement_fidelity(operation: cirq.SupportsKraus) -> float:
|
|
302
302
|
r"""Returns entanglement fidelity of a given quantum channel.
|
|
303
303
|
|
|
304
304
|
Entanglement fidelity $F_e$ of a quantum channel $E: L(H) \to L(H)$ is the overlap between
|
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
15
17
|
import abc
|
|
16
18
|
from typing import List, Sequence, Tuple, TYPE_CHECKING
|
|
17
19
|
|
|
@@ -38,7 +40,7 @@ class QuantumStateRepresentation(metaclass=abc.ABCMeta):
|
|
|
38
40
|
|
|
39
41
|
@abc.abstractmethod
|
|
40
42
|
def measure(
|
|
41
|
-
self, axes: Sequence[int], seed:
|
|
43
|
+
self, axes: Sequence[int], seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None
|
|
42
44
|
) -> List[int]:
|
|
43
45
|
"""Measures the state.
|
|
44
46
|
|
|
@@ -50,10 +52,7 @@ class QuantumStateRepresentation(metaclass=abc.ABCMeta):
|
|
|
50
52
|
"""
|
|
51
53
|
|
|
52
54
|
def sample(
|
|
53
|
-
self,
|
|
54
|
-
axes: Sequence[int],
|
|
55
|
-
repetitions: int = 1,
|
|
56
|
-
seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
|
|
55
|
+
self, axes: Sequence[int], repetitions: int = 1, seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None
|
|
57
56
|
) -> np.ndarray:
|
|
58
57
|
"""Samples the state. Subclasses can override with more performant method.
|
|
59
58
|
|
cirq/qis/states.py
CHANGED
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
|
|
15
15
|
"""Classes and methods for quantum states."""
|
|
16
16
|
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
17
19
|
import itertools
|
|
18
20
|
from typing import Any, cast, Iterable, List, Optional, Sequence, Set, Tuple, TYPE_CHECKING, Union
|
|
19
21
|
|
|
@@ -64,7 +66,7 @@ class QuantumState:
|
|
|
64
66
|
data: np.ndarray,
|
|
65
67
|
qid_shape: Optional[Tuple[int, ...]] = None,
|
|
66
68
|
*, # Force keyword arguments
|
|
67
|
-
dtype: Optional[
|
|
69
|
+
dtype: Optional[DTypeLike] = None,
|
|
68
70
|
validate: bool = True,
|
|
69
71
|
atol: float = 1e-7,
|
|
70
72
|
) -> None:
|
|
@@ -156,7 +158,7 @@ class QuantumState:
|
|
|
156
158
|
return self.data.shape == (self._dim, self._dim)
|
|
157
159
|
|
|
158
160
|
def validate(
|
|
159
|
-
self, *, dtype: Optional[
|
|
161
|
+
self, *, dtype: Optional[DTypeLike] = None, atol=1e-7 # Force keyword arguments
|
|
160
162
|
) -> None:
|
|
161
163
|
"""Check if this quantum state is valid.
|
|
162
164
|
|
|
@@ -188,12 +190,12 @@ class QuantumState:
|
|
|
188
190
|
|
|
189
191
|
|
|
190
192
|
def quantum_state(
|
|
191
|
-
state:
|
|
193
|
+
state: cirq.QUANTUM_STATE_LIKE,
|
|
192
194
|
qid_shape: Optional[Tuple[int, ...]] = None,
|
|
193
195
|
*, # Force keyword arguments
|
|
194
196
|
copy: bool = False,
|
|
195
197
|
validate: bool = True,
|
|
196
|
-
dtype: Optional[
|
|
198
|
+
dtype: Optional[DTypeLike] = None,
|
|
197
199
|
atol: float = 1e-7,
|
|
198
200
|
) -> QuantumState:
|
|
199
201
|
"""Create a QuantumState object from a state-like object.
|
|
@@ -297,7 +299,7 @@ def density_matrix(
|
|
|
297
299
|
*, # Force keyword arguments
|
|
298
300
|
copy: bool = False,
|
|
299
301
|
validate: bool = True,
|
|
300
|
-
dtype: Optional[
|
|
302
|
+
dtype: Optional[DTypeLike] = None,
|
|
301
303
|
atol: float = 1e-7,
|
|
302
304
|
) -> QuantumState:
|
|
303
305
|
"""Create a QuantumState object from a density matrix.
|
|
@@ -350,7 +352,7 @@ _NON_INT_STATE_LIKE = Union[
|
|
|
350
352
|
]
|
|
351
353
|
|
|
352
354
|
|
|
353
|
-
def infer_qid_shape(*states:
|
|
355
|
+
def infer_qid_shape(*states: cirq.QUANTUM_STATE_LIKE) -> Tuple[int, ...]:
|
|
354
356
|
"""Infer the qid shape of a set of states.
|
|
355
357
|
|
|
356
358
|
This is a heuristic to determine a qid shape compatible with all of the
|
|
@@ -410,7 +412,7 @@ def infer_qid_shape(*states: 'cirq.QUANTUM_STATE_LIKE') -> Tuple[int, ...]:
|
|
|
410
412
|
return qid_shape
|
|
411
413
|
|
|
412
414
|
|
|
413
|
-
def _potential_qid_shapes(state: _NON_INT_STATE_LIKE) ->
|
|
415
|
+
def _potential_qid_shapes(state: _NON_INT_STATE_LIKE) -> _QidShapeSet:
|
|
414
416
|
"""Return a set of qid shapes compatible with a given state."""
|
|
415
417
|
if isinstance(state, QuantumState):
|
|
416
418
|
return _QidShapeSet(explicit_qid_shapes={state.qid_shape})
|
|
@@ -472,7 +474,7 @@ class _QidShapeSet:
|
|
|
472
474
|
self.unfactorized_total_dimension = unfactorized_total_dimension
|
|
473
475
|
self.min_qudit_dimensions = min_qudit_dimensions
|
|
474
476
|
|
|
475
|
-
def intersection_subset(self, other:
|
|
477
|
+
def intersection_subset(self, other: _QidShapeSet):
|
|
476
478
|
"""Return a subset of the intersection with other qid shape set."""
|
|
477
479
|
explicit_qid_shapes = self.explicit_qid_shapes & other.explicit_qid_shapes
|
|
478
480
|
unfactorized_total_dimension = None
|
|
@@ -761,11 +763,11 @@ def dirac_notation(
|
|
|
761
763
|
|
|
762
764
|
|
|
763
765
|
def to_valid_state_vector(
|
|
764
|
-
state_rep:
|
|
766
|
+
state_rep: cirq.STATE_VECTOR_LIKE,
|
|
765
767
|
num_qubits: Optional[int] = None,
|
|
766
768
|
*, # Force keyword arguments
|
|
767
769
|
qid_shape: Optional[Sequence[int]] = None,
|
|
768
|
-
dtype: Optional[
|
|
770
|
+
dtype: Optional[DTypeLike] = None,
|
|
769
771
|
atol: float = 1e-7,
|
|
770
772
|
) -> np.ndarray:
|
|
771
773
|
"""Verifies the state_rep is valid and converts it to ndarray form.
|
|
@@ -830,7 +832,7 @@ def to_valid_state_vector(
|
|
|
830
832
|
|
|
831
833
|
|
|
832
834
|
def _qudit_values_to_state_tensor(
|
|
833
|
-
*, state_vector: np.ndarray, qid_shape: Tuple[int, ...], dtype: Optional[
|
|
835
|
+
*, state_vector: np.ndarray, qid_shape: Tuple[int, ...], dtype: Optional[DTypeLike]
|
|
834
836
|
) -> np.ndarray:
|
|
835
837
|
for i in range(len(qid_shape)):
|
|
836
838
|
s = state_vector[i]
|
|
@@ -863,7 +865,7 @@ def validate_normalized_state_vector(
|
|
|
863
865
|
state_vector: np.ndarray,
|
|
864
866
|
*, # Force keyword arguments
|
|
865
867
|
qid_shape: Tuple[int, ...],
|
|
866
|
-
dtype: Optional[
|
|
868
|
+
dtype: Optional[DTypeLike] = None,
|
|
867
869
|
atol: float = 1e-7,
|
|
868
870
|
) -> None:
|
|
869
871
|
"""Checks that the given state vector is valid.
|
|
@@ -928,11 +930,11 @@ def validate_indices(num_qubits: int, indices: Sequence[int]) -> None:
|
|
|
928
930
|
|
|
929
931
|
|
|
930
932
|
def to_valid_density_matrix(
|
|
931
|
-
density_matrix_rep: Union[np.ndarray,
|
|
933
|
+
density_matrix_rep: Union[np.ndarray, cirq.STATE_VECTOR_LIKE],
|
|
932
934
|
num_qubits: Optional[int] = None,
|
|
933
935
|
*, # Force keyword arguments
|
|
934
936
|
qid_shape: Optional[Tuple[int, ...]] = None,
|
|
935
|
-
dtype: Optional[
|
|
937
|
+
dtype: Optional[DTypeLike] = None,
|
|
936
938
|
atol: float = 1e-7,
|
|
937
939
|
) -> np.ndarray:
|
|
938
940
|
"""Verifies the density_matrix_rep is valid and converts it to ndarray form.
|
|
@@ -981,7 +983,7 @@ def validate_density_matrix(
|
|
|
981
983
|
density_matrix: np.ndarray,
|
|
982
984
|
*, # Force keyword arguments
|
|
983
985
|
qid_shape: Tuple[int, ...],
|
|
984
|
-
dtype: Optional[
|
|
986
|
+
dtype: Optional[DTypeLike] = None,
|
|
985
987
|
atol: float = 1e-7,
|
|
986
988
|
) -> None:
|
|
987
989
|
"""Checks that the given density matrix is valid.
|
|
@@ -1049,7 +1051,7 @@ def one_hot(
|
|
|
1049
1051
|
index: Union[None, int, Sequence[int]] = None,
|
|
1050
1052
|
shape: Union[int, Sequence[int]],
|
|
1051
1053
|
value: Any = 1,
|
|
1052
|
-
dtype:
|
|
1054
|
+
dtype: DTypeLike,
|
|
1053
1055
|
) -> np.ndarray:
|
|
1054
1056
|
"""Returns a numpy array with all 0s and a single non-zero entry(default 1).
|
|
1055
1057
|
|
|
@@ -1070,7 +1072,7 @@ def one_hot(
|
|
|
1070
1072
|
return result
|
|
1071
1073
|
|
|
1072
1074
|
|
|
1073
|
-
def eye_tensor(half_shape: Tuple[int, ...], *, dtype:
|
|
1075
|
+
def eye_tensor(half_shape: Tuple[int, ...], *, dtype: DTypeLike) -> np.ndarray:
|
|
1074
1076
|
"""Returns an identity matrix reshaped into a tensor.
|
|
1075
1077
|
|
|
1076
1078
|
Args:
|
cirq/sim/classical_simulator.py
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
# See the License for the specific language governing permissions and
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
|
|
15
|
+
from __future__ import annotations
|
|
15
16
|
|
|
16
17
|
from copy import copy, deepcopy
|
|
17
18
|
from typing import Any, Dict, Generic, List, Optional, Sequence, TYPE_CHECKING, Union
|
|
@@ -45,7 +46,7 @@ class ClassicalBasisState(qis.QuantumStateRepresentation):
|
|
|
45
46
|
"""
|
|
46
47
|
self.basis = initial_state
|
|
47
48
|
|
|
48
|
-
def copy(self, deep_copy_buffers: bool = True) ->
|
|
49
|
+
def copy(self, deep_copy_buffers: bool = True) -> ClassicalBasisState:
|
|
49
50
|
"""Creates a copy of the ClassicalBasisState object.
|
|
50
51
|
|
|
51
52
|
Args:
|
|
@@ -58,7 +59,7 @@ class ClassicalBasisState(qis.QuantumStateRepresentation):
|
|
|
58
59
|
)
|
|
59
60
|
|
|
60
61
|
def measure(
|
|
61
|
-
self, axes: Sequence[int], seed:
|
|
62
|
+
self, axes: Sequence[int], seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None
|
|
62
63
|
) -> List[int]:
|
|
63
64
|
"""Measures the density matrix.
|
|
64
65
|
|
|
@@ -77,8 +78,8 @@ class ClassicalBasisSimState(SimulationState[ClassicalBasisState]):
|
|
|
77
78
|
def __init__(
|
|
78
79
|
self,
|
|
79
80
|
initial_state: Union[int, List[int]] = 0,
|
|
80
|
-
qubits: Optional[Sequence[
|
|
81
|
-
classical_data: Optional[
|
|
81
|
+
qubits: Optional[Sequence[cirq.Qid]] = None,
|
|
82
|
+
classical_data: Optional[cirq.ClassicalDataStore] = None,
|
|
82
83
|
):
|
|
83
84
|
"""Initializes the ClassicalBasisSimState object.
|
|
84
85
|
|
|
@@ -105,7 +106,7 @@ class ClassicalBasisSimState(SimulationState[ClassicalBasisState]):
|
|
|
105
106
|
raise ValueError('initial_state must be an int or List[int] or np.ndarray')
|
|
106
107
|
super().__init__(state=state, qubits=qubits, classical_data=classical_data)
|
|
107
108
|
|
|
108
|
-
def _act_on_fallback_(self, action, qubits: Sequence[
|
|
109
|
+
def _act_on_fallback_(self, action, qubits: Sequence[cirq.Qid], allow_decompose: bool = True):
|
|
109
110
|
"""Acts on the state with a given operation.
|
|
110
111
|
|
|
111
112
|
Args:
|
|
@@ -182,7 +183,7 @@ class ClassicalStateSimulator(
|
|
|
182
183
|
"""A simulator that accepts only gates with classical counterparts."""
|
|
183
184
|
|
|
184
185
|
def __init__(
|
|
185
|
-
self, *, noise:
|
|
186
|
+
self, *, noise: cirq.NOISE_MODEL_LIKE = None, split_untangled_states: bool = False
|
|
186
187
|
):
|
|
187
188
|
"""Initializes a ClassicalStateSimulator.
|
|
188
189
|
|
|
@@ -199,10 +200,10 @@ class ClassicalStateSimulator(
|
|
|
199
200
|
|
|
200
201
|
def _create_simulator_trial_result(
|
|
201
202
|
self,
|
|
202
|
-
params:
|
|
203
|
+
params: cirq.ParamResolver,
|
|
203
204
|
measurements: Dict[str, np.ndarray],
|
|
204
|
-
final_simulator_state:
|
|
205
|
-
) ->
|
|
205
|
+
final_simulator_state: cirq.SimulationStateBase[ClassicalBasisSimState],
|
|
206
|
+
) -> ClassicalStateTrialResult[ClassicalBasisSimState]:
|
|
206
207
|
"""Creates a trial result for the simulator.
|
|
207
208
|
|
|
208
209
|
Args:
|
|
@@ -217,8 +218,8 @@ class ClassicalStateSimulator(
|
|
|
217
218
|
)
|
|
218
219
|
|
|
219
220
|
def _create_step_result(
|
|
220
|
-
self, sim_state:
|
|
221
|
-
) ->
|
|
221
|
+
self, sim_state: cirq.SimulationStateBase[ClassicalBasisSimState]
|
|
222
|
+
) -> ClassicalStateStepResult[ClassicalBasisSimState]:
|
|
222
223
|
"""Creates a step result for the simulator.
|
|
223
224
|
|
|
224
225
|
Args:
|
|
@@ -231,9 +232,9 @@ class ClassicalStateSimulator(
|
|
|
231
232
|
def _create_partial_simulation_state(
|
|
232
233
|
self,
|
|
233
234
|
initial_state: Any,
|
|
234
|
-
qubits: Sequence[
|
|
235
|
-
classical_data:
|
|
236
|
-
) ->
|
|
235
|
+
qubits: Sequence[cirq.Qid],
|
|
236
|
+
classical_data: cirq.ClassicalDataStore,
|
|
237
|
+
) -> ClassicalBasisSimState:
|
|
237
238
|
"""Creates a partial simulation state for the simulator.
|
|
238
239
|
|
|
239
240
|
Args:
|