def test_json_serializable_dataclass(): @cirq.json_serializable_dataclass class MyDC: q: cirq.LineQubit desc: str my_dc = MyDC(cirq.LineQubit(4), 'hi mom') def custom_resolver(name): if name == 'MyDC': return MyDC assert_json_roundtrip_works( my_dc, text_should_be="\n".join([ '{', ' "cirq_type": "MyDC",', ' "q": {', ' "cirq_type": "LineQubit",', ' "x": 4', ' },', ' "desc": "hi mom"', '}', ]), resolvers=[custom_resolver] + cirq.DEFAULT_RESOLVERS, )
def test_deprecated_cirq_type_in_json_dict(): class HasOldJsonDict: # Required for testing serialization of non-cirq objects. __module__ = 'test.noncirq.namespace' # type: ignore def __eq__(self, other): return isinstance(other, HasOldJsonDict) def _json_dict_(self): return {'cirq_type': 'test.noncirq.namespace.HasOldJsonDict'} @classmethod def _from_json_dict_(cls, **kwargs): return cls() with pytest.raises(ValueError, match='not a Cirq type'): _ = cirq.json_cirq_type(HasOldJsonDict) def custom_resolver(name): if name == 'test.noncirq.namespace.HasOldJsonDict': return HasOldJsonDict test_resolvers = [custom_resolver] + cirq.DEFAULT_RESOLVERS with cirq.testing.assert_deprecated("Found 'cirq_type'", deadline='v0.15'): assert_json_roundtrip_works(HasOldJsonDict(), resolvers=test_resolvers)
def test_deprecated_dataclass_json_dict_namespace(): @dataclasses.dataclass class HasOldJsonDict: # Required for testing serialization of non-cirq objects. __module__: ClassVar = 'test.noncirq.namespace' # type: ignore x: int def _json_dict_(self): return json_serialization.dataclass_json_dict( self, namespace='test.noncirq.namespace') @classmethod def _from_json_dict_(cls, x, **kwargs): return cls(x) with pytest.raises(ValueError, match='not a Cirq type'): _ = cirq.json_cirq_type(HasOldJsonDict) def custom_resolver(name): if name == 'test.noncirq.namespace.HasOldJsonDict': return HasOldJsonDict test_resolvers = [custom_resolver] + cirq.DEFAULT_RESOLVERS with cirq.testing.assert_deprecated("Found 'cirq_type'", 'Define obj._json_namespace_', deadline='v0.15', count=5): assert_json_roundtrip_works(HasOldJsonDict(1), resolvers=test_resolvers)
def test_deprecated_obj_to_dict_helper_namespace(): class HasOldJsonDict: # Required for testing serialization of non-cirq objects. __module__ = 'test.noncirq.namespace' # type: ignore def __init__(self, x): self.x = x def __eq__(self, other): return isinstance(other, HasOldJsonDict) and other.x == self.x def _json_dict_(self): return json_serialization.obj_to_dict_helper( self, ['x'], namespace='test.noncirq.namespace') @classmethod def _from_json_dict_(cls, x, **kwargs): return cls(x) with pytest.raises(ValueError, match='not a Cirq type'): _ = cirq.json_cirq_type(HasOldJsonDict) def custom_resolver(name): if name == 'test.noncirq.namespace.HasOldJsonDict': return HasOldJsonDict test_resolvers = [custom_resolver] + cirq.DEFAULT_RESOLVERS with cirq.testing.assert_deprecated("Found 'cirq_type'", 'Define obj._json_namespace_', deadline='v0.15', count=3): assert_json_roundtrip_works(HasOldJsonDict(1), resolvers=test_resolvers)
def test_type_serialization(mod_spec: ModuleJsonTestSpec, cirq_obj_name: str, cls): if cirq_obj_name in mod_spec.tested_elsewhere: pytest.skip("Tested elsewhere.") if cirq_obj_name in mod_spec.not_yet_serializable: return pytest.xfail(reason="Not serializable (yet)") if cls is None: pytest.skip(f'No serialization for None-mapped type: {cirq_obj_name}') try: typename = cirq.json_cirq_type(cls) except ValueError as e: pytest.skip(f'No serialization for non-Cirq type: {str(e)}') def custom_resolver(name): if name == 'SerializableTypeObject': return SerializableTypeObject sto = SerializableTypeObject(cls) test_resolvers = [custom_resolver] + cirq.DEFAULT_RESOLVERS expected_json = (f'{{\n "cirq_type": "SerializableTypeObject",\n' f' "test_type": "{typename}"\n}}') assert cirq.to_json(sto) == expected_json assert cirq.read_json(json_text=expected_json, resolvers=test_resolvers) == sto assert_json_roundtrip_works(sto, resolvers=test_resolvers)
def test_json_serializable_dataclass(): with cirq.testing.assert_deprecated( "Implement _json_dict_ using cirq.dataclass_json_dict()", deadline="v0.15"): @cirq.json_serializable_dataclass class MyDC: q: cirq.LineQubit desc: str my_dc = MyDC(cirq.LineQubit(4), 'hi mom') def custom_resolver(name): if name == 'MyDC': return MyDC assert_json_roundtrip_works( my_dc, text_should_be="\n".join([ '{', ' "cirq_type": "MyDC",', ' "q": {', ' "cirq_type": "LineQubit",', ' "x": 4', ' },', ' "desc": "hi mom"', '}', ]), resolvers=[custom_resolver] + cirq.DEFAULT_RESOLVERS, )
def test_line_qubit_roundtrip(): q1 = cirq.LineQubit(12) assert_json_roundtrip_works( q1, text_should_be="""{ "cirq_type": "LineQubit", "x": 12 }""", )
def test_gridqubit_roundtrip(): q = cirq.GridQubit(15, 18) assert_json_roundtrip_works( q, text_should_be="""{ "cirq_type": "GridQubit", "row": 15, "col": 18 }""", )
def test_json_serializable_dataclass_parenthesis(): @cirq.json_serializable_dataclass() class MyDC: q: cirq.LineQubit desc: str def custom_resolver(name): if name == 'MyDC': return MyDC my_dc = MyDC(cirq.LineQubit(4), 'hi mom') assert_json_roundtrip_works(my_dc, resolvers=[custom_resolver] + cirq.DEFAULT_RESOLVERS)
def test_json_serializable_dataclass_namespace(): @cirq.json_serializable_dataclass(namespace='cirq.experiments') class QuantumVolumeParams: width: int depth: int circuit_i: int qvp = QuantumVolumeParams(width=5, depth=5, circuit_i=0) def custom_resolver(name): if name == 'cirq.experiments.QuantumVolumeParams': return QuantumVolumeParams assert_json_roundtrip_works(qvp, resolvers=[custom_resolver] + cirq.DEFAULT_RESOLVERS)
def test_dataclass_json_dict(): @dataclasses.dataclass(frozen=True) class MyDC: q: cirq.LineQubit desc: str def _json_dict_(self): return cirq.dataclass_json_dict(self) def custom_resolver(name): if name == 'MyDC': return MyDC my_dc = MyDC(cirq.LineQubit(4), 'hi mom') assert_json_roundtrip_works( my_dc, resolvers=[custom_resolver, *cirq.DEFAULT_RESOLVERS])
def test_builtins(): assert_json_roundtrip_works(True) assert_json_roundtrip_works(1) assert_json_roundtrip_works(1 + 2j) assert_json_roundtrip_works({ 'test': [123, 5.5], 'key2': 'asdf', '3': None, '0.0': [], })
def test_op_roundtrip(): q = cirq.LineQubit(5) op1 = cirq.rx(0.123).on(q) assert_json_roundtrip_works( op1, text_should_be="""{ "cirq_type": "GateOperation", "gate": { "cirq_type": "Rx", "rads": 0.123 }, "qubits": [ { "cirq_type": "LineQubit", "x": 5 } ] }""", )
def test_json_serializable_dataclass_parenthesis(): with cirq.testing.assert_deprecated( "Implement _json_dict_ using cirq.dataclass_json_dict()", deadline="v0.15"): @cirq.json_serializable_dataclass() class MyDC: q: cirq.LineQubit desc: str def custom_resolver(name): if name == 'MyDC': return MyDC my_dc = MyDC(cirq.LineQubit(4), 'hi mom') assert_json_roundtrip_works(my_dc, resolvers=[custom_resolver] + cirq.DEFAULT_RESOLVERS)
def test_json_serializable_dataclass_namespace(): with cirq.testing.assert_deprecated( "Implement _json_dict_ using cirq.dataclass_json_dict()", deadline="v0.15"): @cirq.json_serializable_dataclass(namespace='cirq.experiments') class QuantumVolumeParams: width: int depth: int circuit_i: int qvp = QuantumVolumeParams(width=5, depth=5, circuit_i=0) def custom_resolver(name): if name == 'cirq.experiments.QuantumVolumeParams': return QuantumVolumeParams assert_json_roundtrip_works(qvp, resolvers=[custom_resolver] + cirq.DEFAULT_RESOLVERS)
def test_pandas(): assert_json_roundtrip_works( pd.DataFrame(data=[[1, 2, 3], [4, 5, 6]], columns=['x', 'y', 'z'], index=[2, 5])) assert_json_roundtrip_works(pd.Index([1, 2, 3], name='test')) assert_json_roundtrip_works( pd.MultiIndex.from_tuples([(1, 2), (3, 4), (5, 6)], names=['alice', 'bob'])) assert_json_roundtrip_works( pd.DataFrame( index=pd.Index([1, 2, 3], name='test'), data=[[11, 21.0], [12, 22.0], [13, 23.0]], columns=['a', 'b'], )) assert_json_roundtrip_works( pd.DataFrame( index=pd.MultiIndex.from_tuples([(1, 2), (2, 3), (3, 4)], names=['x', 'y']), data=[[11, 21.0], [12, 22.0], [13, 23.0]], columns=pd.Index(['a', 'b'], name='c'), ))
def test_numpy(): x = np.ones(1)[0] assert_json_roundtrip_works(x.astype(np.int8)) assert_json_roundtrip_works(x.astype(np.int16)) assert_json_roundtrip_works(x.astype(np.int32)) assert_json_roundtrip_works(x.astype(np.int64)) assert_json_roundtrip_works(x.astype(np.uint8)) assert_json_roundtrip_works(x.astype(np.uint16)) assert_json_roundtrip_works(x.astype(np.uint32)) assert_json_roundtrip_works(x.astype(np.uint64)) assert_json_roundtrip_works(x.astype(np.float32)) assert_json_roundtrip_works(x.astype(np.float64)) assert_json_roundtrip_works(x.astype(np.complex64)) assert_json_roundtrip_works(x.astype(np.complex128)) assert_json_roundtrip_works(np.ones((11, 5))) assert_json_roundtrip_works(np.arange(3))
def test_context_serialization(): def custom_resolver(name): if name == 'SBKImpl': return SBKImpl test_resolvers = [custom_resolver] + cirq.DEFAULT_RESOLVERS sbki_empty = SBKImpl('sbki_empty') assert_json_roundtrip_works(sbki_empty, resolvers=test_resolvers) sbki_list = SBKImpl('sbki_list', data_list=[sbki_empty, sbki_empty]) assert_json_roundtrip_works(sbki_list, resolvers=test_resolvers) sbki_tuple = SBKImpl('sbki_tuple', data_tuple=(sbki_list, sbki_list)) assert_json_roundtrip_works(sbki_tuple, resolvers=test_resolvers) sbki_dict = SBKImpl('sbki_dict', data_dict={ 'a': sbki_tuple, 'b': sbki_tuple }) assert_json_roundtrip_works(sbki_dict, resolvers=test_resolvers) sbki_json = str(cirq.to_json(sbki_dict)) # There should be exactly one context item for each previous SBKImpl. assert sbki_json.count('"cirq_type": "_SerializedContext"') == 4 # There should be exactly two key items for each of sbki_(empty|list|tuple), # plus one for the top-level sbki_dict. assert sbki_json.count('"cirq_type": "_SerializedKey"') == 7 # The final object should be a _SerializedKey for sbki_dict. final_obj_idx = sbki_json.rfind('{') final_obj = sbki_json[final_obj_idx:sbki_json.find('}', final_obj_idx) + 1] assert (final_obj == """{ "cirq_type": "_SerializedKey", "key": 4 }""") list_sbki = [sbki_dict] assert_json_roundtrip_works(list_sbki, resolvers=test_resolvers) dict_sbki = {'a': sbki_dict} assert_json_roundtrip_works(dict_sbki, resolvers=test_resolvers) assert sbki_list != json_serialization._SerializedKey(sbki_list) # Serialization keys have unique suffixes. sbki_other_list = SBKImpl('sbki_list', data_list=[sbki_list]) assert_json_roundtrip_works(sbki_other_list, resolvers=test_resolvers)
def test_sympy(): # Raw values. assert_json_roundtrip_works(sympy.Symbol('theta')) assert_json_roundtrip_works(sympy.Integer(5)) assert_json_roundtrip_works(sympy.Rational(2, 3)) assert_json_roundtrip_works(sympy.Float(1.1)) # Basic operations. s = sympy.Symbol('s') t = sympy.Symbol('t') assert_json_roundtrip_works(t + s) assert_json_roundtrip_works(t * s) assert_json_roundtrip_works(t / s) assert_json_roundtrip_works(t - s) assert_json_roundtrip_works(t**s) # Linear combinations. assert_json_roundtrip_works(t * 2) assert_json_roundtrip_works(4 * t + 3 * s + 2) assert_json_roundtrip_works(sympy.pi) assert_json_roundtrip_works(sympy.E) assert_json_roundtrip_works(sympy.EulerGamma)