Skip to content

Commit b8bd6c8

Browse files
95-martin-orionrht
authored andcommitted
Move "cirq_type" responsibility to protocols (quantumlib#4704)
Fixes quantumlib#4698. This enforces the `'cirq_type': [<namespace>.]<classname>` convention for JSON serialization by assigning the "cirq_type" field in our protocols instead of in each class. Any external users who define a "cirq_type" will see a warning about this; after a deprecation cycle, we will begin raising errors to prevent explicit definition of "cirq_type" in classes.
1 parent 36fa7cb commit b8bd6c8

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+155
-104
lines changed

cirq-core/cirq/circuits/circuit_operation.py

-1
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,6 @@ def __hash__(self):
329329

330330
def _json_dict_(self):
331331
return {
332-
'cirq_type': 'CircuitOperation',
333332
'circuit': self.circuit,
334333
'repetitions': self.repetitions,
335334
# JSON requires mappings to have keys of basic types.

cirq-core/cirq/circuits/circuit_operation_test.py

-1
Original file line numberDiff line numberDiff line change
@@ -484,7 +484,6 @@ def test_json_dict():
484484
)
485485

486486
assert op._json_dict_() == {
487-
'cirq_type': 'CircuitOperation',
488487
'circuit': circuit,
489488
'repetitions': 1,
490489
'qubit_map': sorted([(k, v) for k, v in op.qubit_map.items()]),

cirq-core/cirq/circuits/circuit_test.py

-1
Original file line numberDiff line numberDiff line change
@@ -4212,7 +4212,6 @@ def test_json_dict(circuit_cls):
42124212
if circuit_cls == cirq.FrozenCircuit:
42134213
moments = tuple(moments)
42144214
assert c._json_dict_() == {
4215-
'cirq_type': circuit_cls.__name__,
42164215
'moments': moments,
42174216
'device': cirq.UNCONSTRAINED_DEVICE,
42184217
}

cirq-core/cirq/devices/device.py

-1
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,6 @@ def __repr__(self):
164164
def _json_dict_(self):
165165
return {
166166
'qids': sorted(self.qids),
167-
'cirq_type': self.__class__.__name__,
168167
}
169168

170169
@classmethod

cirq-core/cirq/devices/grid_qubit_test.py

-2
Original file line numberDiff line numberDiff line change
@@ -321,13 +321,11 @@ def test_neg():
321321

322322
def test_to_json():
323323
assert cirq.GridQubit(5, 6)._json_dict_() == {
324-
'cirq_type': 'GridQubit',
325324
'row': 5,
326325
'col': 6,
327326
}
328327

329328
assert cirq.GridQid(5, 6, dimension=3)._json_dict_() == {
330-
'cirq_type': 'GridQid',
331329
'row': 5,
332330
'col': 6,
333331
'dimension': 3,

cirq-core/cirq/devices/line_qubit_test.py

-2
Original file line numberDiff line numberDiff line change
@@ -214,11 +214,9 @@ def test_neg():
214214

215215
def test_json_dict():
216216
assert cirq.LineQubit(5)._json_dict_() == {
217-
'cirq_type': 'LineQubit',
218217
'x': 5,
219218
}
220219
assert cirq.LineQid(5, 3)._json_dict_() == {
221-
'cirq_type': 'LineQid',
222220
'x': 5,
223221
'dimension': 3,
224222
}

cirq-core/cirq/devices/named_topologies.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
# limitations under the License.
1414

1515
import abc
16-
import dataclasses
1716
import warnings
1817
from dataclasses import dataclass
1918
from typing import Dict, List, Tuple, Any, Sequence, Union, Iterable, TYPE_CHECKING
@@ -23,16 +22,12 @@
2322

2423
from cirq import _compat
2524
from cirq.devices import GridQubit, LineQubit
26-
from cirq.protocols.json_serialization import obj_to_dict_helper
25+
from cirq.protocols.json_serialization import dataclass_json_dict
2726

2827
if TYPE_CHECKING:
2928
import cirq
3029

3130

32-
def dataclass_json_dict(obj: Any, namespace: str = None) -> Dict[str, Any]:
33-
return obj_to_dict_helper(obj, [f.name for f in dataclasses.fields(obj)], namespace=namespace)
34-
35-
3631
class NamedTopology(metaclass=abc.ABCMeta):
3732
"""A topology (graph) with a name.
3833

cirq-core/cirq/experiments/cross_entropy_benchmarking.py

-1
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,6 @@ class CrossEntropyResultDict(Mapping[Tuple['cirq.Qid', ...], CrossEntropyResult]
253253

254254
def _json_dict_(self) -> Dict[str, Any]:
255255
return {
256-
'cirq_type': self.__class__.__name__,
257256
'results': list(self.results.items()),
258257
}
259258

cirq-core/cirq/experiments/single_qubit_readout_calibration.py

-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ class SingleQubitReadoutCalibrationResult:
4545

4646
def _json_dict_(self) -> Dict[str, Any]:
4747
return {
48-
'cirq_type': self.__class__.__name__,
4948
'zero_state_errors': list(self.zero_state_errors.items()),
5049
'one_state_errors': list(self.one_state_errors.items()),
5150
'repetitions': self.repetitions,

cirq-core/cirq/ops/boolean_hamiltonian.py

-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,6 @@ def _value_equality_values_(self):
9494

9595
def _json_dict_(self) -> Dict[str, Any]:
9696
return {
97-
'cirq_type': self.__class__.__name__,
9897
'qubit_map': self._qubit_map,
9998
'boolean_strs': self._boolean_strs,
10099
'theta': self._theta,

cirq-core/cirq/ops/clifford_gate.py

-1
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,6 @@ def _from_json_dict_(cls, n, rs, xs, zs, **kwargs):
488488

489489
def _json_dict_(self) -> Dict[str, Any]:
490490
json_dict = self._clifford_tableau._json_dict_()
491-
json_dict['cirq_type'] = self.__class__.__name__
492491
return json_dict
493492

494493
def _circuit_diagram_info_(

cirq-core/cirq/ops/common_gates.py

-3
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,6 @@ def __repr__(self) -> str:
318318

319319
def _json_dict_(self) -> Dict[str, Any]:
320320
return {
321-
'cirq_type': self.__class__.__name__,
322321
'rads': self._rads,
323322
}
324323

@@ -539,7 +538,6 @@ def __repr__(self) -> str:
539538

540539
def _json_dict_(self) -> Dict[str, Any]:
541540
return {
542-
'cirq_type': self.__class__.__name__,
543541
'rads': self._rads,
544542
}
545543

@@ -825,7 +823,6 @@ def __repr__(self) -> str:
825823

826824
def _json_dict_(self) -> Dict[str, Any]:
827825
return {
828-
'cirq_type': self.__class__.__name__,
829826
'rads': self._rads,
830827
}
831828

cirq-core/cirq/ops/controlled_gate.py

-1
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,6 @@ def __repr__(self) -> str:
260260

261261
def _json_dict_(self) -> Dict[str, Any]:
262262
return {
263-
'cirq_type': self.__class__.__name__,
264263
'control_values': self.control_values,
265264
'control_qid_shape': self.control_qid_shape,
266265
'sub_gate': self.sub_gate,

cirq-core/cirq/ops/controlled_operation.py

-1
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,6 @@ def get_symbol(vals):
254254

255255
def _json_dict_(self) -> Dict[str, Any]:
256256
return {
257-
'cirq_type': self.__class__.__name__,
258257
'controls': self.controls,
259258
'control_values': self.control_values,
260259
'sub_operation': self.sub_operation,

cirq-core/cirq/ops/fourier_transform.py

-2
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@ def __init__(self, num_qubits: int, *, without_reverse: bool = False):
4242

4343
def _json_dict_(self) -> Dict[str, Any]:
4444
return {
45-
'cirq_type': self.__class__.__name__,
4645
'num_qubits': self._num_qubits,
4746
'without_reverse': self._without_reverse,
4847
}
@@ -98,7 +97,6 @@ def __init__(self, *, num_qubits: int, exponent: Union[float, sympy.Basic]):
9897

9998
def _json_dict_(self) -> Dict[str, Any]:
10099
return {
101-
'cirq_type': self.__class__.__name__,
102100
'num_qubits': self._num_qubits,
103101
'exponent': self.exponent,
104102
}

cirq-core/cirq/ops/fsim_gate_test.py

-2
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,6 @@ def test_fsim_repr():
278278

279279
def test_fsim_json_dict():
280280
assert cirq.FSimGate(theta=0.123, phi=0.456)._json_dict_() == {
281-
'cirq_type': 'FSimGate',
282281
'theta': 0.123,
283282
'phi': 0.456,
284283
}
@@ -799,7 +798,6 @@ def test_phased_fsim_json_dict():
799798
assert cirq.PhasedFSimGate(
800799
theta=0.12, zeta=0.34, chi=0.56, gamma=0.78, phi=0.9
801800
)._json_dict_() == {
802-
'cirq_type': 'PhasedFSimGate',
803801
'theta': 0.12,
804802
'zeta': 0.34,
805803
'chi': 0.56,

cirq-core/cirq/ops/global_phase_op_test.py

-1
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,5 @@ def test_diagram():
268268

269269
def test_global_phase_op_json_dict():
270270
assert cirq.GlobalPhaseOperation(-1j)._json_dict_() == {
271-
'cirq_type': 'GlobalPhaseOperation',
272271
'coefficient': -1j,
273272
}

cirq-core/cirq/ops/identity.py

-1
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,6 @@ def _json_dict_(self) -> Dict[str, Any]:
115115
if not all(d == 2 for d in self._qid_shape):
116116
other['qid_shape'] = self._qid_shape
117117
return {
118-
'cirq_type': self.__class__.__name__,
119118
'num_qubits': len(self._qid_shape),
120119
**other,
121120
}

cirq-core/cirq/ops/linear_combinations.py

-1
Original file line numberDiff line numberDiff line change
@@ -783,7 +783,6 @@ def _json_dict_(self) -> Dict[str, Any]:
783783
key = [[k, v] for k, v in dict(projector_dict).items()]
784784
linear_dict.append([key, scalar])
785785
return {
786-
'cirq_type': self.__class__.__name__,
787786
'linear_dict': linear_dict,
788787
}
789788

cirq-core/cirq/ops/matrix_gates.py

-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,6 @@ def __init__(
8484

8585
def _json_dict_(self) -> Dict[str, Any]:
8686
return {
87-
'cirq_type': self.__class__.__name__,
8887
'matrix': self._matrix.tolist(),
8988
'qid_shape': self._qid_shape,
9089
}

cirq-core/cirq/ops/measurement_gate.py

-1
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,6 @@ def _json_dict_(self) -> Dict[str, Any]:
229229
if not all(d == 2 for d in self._qid_shape):
230230
other['qid_shape'] = self._qid_shape
231231
return {
232-
'cirq_type': self.__class__.__name__,
233232
'num_qubits': len(self._qid_shape),
234233
'key': self.key,
235234
'invert_mask': self.invert_mask,

cirq-core/cirq/ops/moment_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ def test_json_dict():
374374
a = cirq.NamedQubit('a')
375375
b = cirq.NamedQubit('b')
376376
mom = cirq.Moment([cirq.CZ(a, b)])
377-
assert mom._json_dict_() == {'cirq_type': 'Moment', 'operations': (cirq.CZ(a, b),)}
377+
assert mom._json_dict_() == {'operations': (cirq.CZ(a, b),)}
378378

379379

380380
def test_inverse():

cirq-core/cirq/ops/named_qubit_test.py

-2
Original file line numberDiff line numberDiff line change
@@ -136,12 +136,10 @@ def test_named_qid_range():
136136

137137
def test_to_json():
138138
assert cirq.NamedQubit('c')._json_dict_() == {
139-
'cirq_type': 'NamedQubit',
140139
'name': 'c',
141140
}
142141

143142
assert cirq.NamedQid('c', dimension=3)._json_dict_() == {
144-
'cirq_type': 'NamedQid',
145143
'name': 'c',
146144
'dimension': 3,
147145
}

cirq-core/cirq/ops/pauli_measurement_gate.py

-1
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,6 @@ def _value_equality_values_(self) -> Any:
149149

150150
def _json_dict_(self) -> Dict[str, Any]:
151151
return {
152-
'cirq_type': self.__class__.__name__,
153152
'observable': self._observable,
154153
'key': self.key,
155154
}

cirq-core/cirq/ops/pauli_string.py

-2
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,6 @@ def _value_equality_values_(self):
177177

178178
def _json_dict_(self) -> Dict[str, Any]:
179179
return {
180-
'cirq_type': self.__class__.__name__,
181180
# JSON requires mappings to have string keys.
182181
'qubit_pauli_map': list(self._qubit_pauli_map.items()),
183182
'coefficient': self.coefficient,
@@ -1294,7 +1293,6 @@ def inplace_left_multiply_by(
12941293

12951294
def _json_dict_(self) -> Dict[str, Any]:
12961295
return {
1297-
'cirq_type': self.__class__.__name__,
12981296
# JSON requires mappings to have string keys.
12991297
'pauli_int_dict': list(self.pauli_int_dict.items()),
13001298
'coefficient': self.coefficient,

cirq-core/cirq/ops/permutation_gate_test.py

-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,6 @@ def test_permutation_gate_diagram():
7171

7272
def test_permutation_gate_json_dict():
7373
assert cirq.QubitPermutationGate([0, 1, 2])._json_dict_() == {
74-
'cirq_type': 'QubitPermutationGate',
7574
'permutation': (0, 1, 2),
7675
}
7776

cirq-core/cirq/ops/phased_iswap_gate.py

-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,6 @@ def _num_qubits_(self) -> int:
7676

7777
def _json_dict_(self) -> Dict[str, Any]:
7878
return {
79-
'cirq_type': self.__class__.__name__,
8079
'phase_exponent': self._phase_exponent,
8180
'exponent': self._exponent,
8281
}

cirq-core/cirq/ops/projector.py

-1
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,6 @@ def __repr__(self) -> str:
148148

149149
def _json_dict_(self) -> Dict[str, Any]:
150150
return {
151-
'cirq_type': self.__class__.__name__,
152151
'projector_dict': list(self._projector_dict.items()),
153152
'coefficient': self._coefficient,
154153
}

cirq-core/cirq/ops/raw_types_test.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@ def test_wrapped_qid():
7373
assert str(ValidQubit('a').with_dimension(3)) == 'TQ_a (d=3)'
7474

7575
assert ValidQubit('zz').with_dimension(3)._json_dict_() == {
76-
'cirq_type': '_QubitAsQid',
7776
'qubit': ValidQubit('zz'),
7877
'dimension': 3,
7978
}
@@ -370,9 +369,7 @@ def _qid_shape_(self):
370369

371370
def test_gate_json_dict():
372371
g = cirq.CSWAP # not an eigen gate (which has its own _json_dict_)
373-
assert g._json_dict_() == {
374-
'cirq_type': 'CSwapGate',
375-
}
372+
assert g._json_dict_() == {}
376373

377374

378375
def test_inverse_composite_diagram_info():

cirq-core/cirq/ops/state_preparation_channel.py

-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ def _has_unitary_(self) -> bool:
6060
def _json_dict_(self) -> Dict[str, Any]:
6161
"""Converts the gate object into a serializable dictionary"""
6262
return {
63-
'cirq_type': self.__class__.__name__,
6463
'target_state': self._state.tolist(),
6564
'name': self._name,
6665
}

cirq-core/cirq/ops/tags.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,4 @@ def __repr__(self) -> str:
3333
return 'cirq.VirtualTag()'
3434

3535
def _json_dict_(self) -> Dict[str, str]:
36-
return {'cirq_type': self.__class__.__name__}
36+
return {}

0 commit comments

Comments
 (0)