Skip to content

dataclass_json_dict #4391

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cirq-core/cirq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,7 @@
is_parameterized,
JsonResolver,
json_serializable_dataclass,
dataclass_json_dict,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: sort imports

kraus,
measurement_key,
measurement_key_name,
Expand Down
20 changes: 8 additions & 12 deletions cirq-core/cirq/experiments/xeb_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Estimation of fidelity associated with experimental circuit executions."""
import dataclasses
from abc import abstractmethod, ABC
from dataclasses import dataclass
from typing import (
List,
Optional,
Expand All @@ -29,20 +29,14 @@
import scipy.optimize
import scipy.stats
import sympy

from cirq import ops
from cirq import ops, protocols
from cirq.circuits import Circuit
from cirq.experiments.xeb_simulation import simulate_2q_xeb_circuits

if TYPE_CHECKING:
import cirq
import multiprocessing

# Workaround for mypy custom dataclasses (python/mypy#5406)
from dataclasses import dataclass as json_serializable_dataclass
else:
from cirq.protocols import json_serializable_dataclass

THETA_SYMBOL, ZETA_SYMBOL, CHI_SYMBOL, GAMMA_SYMBOL, PHI_SYMBOL = sympy.symbols(
'theta zeta chi gamma phi'
)
Expand Down Expand Up @@ -191,8 +185,7 @@ def phased_fsim_angles_from_gate(gate: 'cirq.Gate') -> Dict[str, float]:
raise ValueError(f"Unknown default angles for {gate}.")


# mypy issue: https://github.com/python/mypy/issues/5374
@json_serializable_dataclass(frozen=True) # type: ignore
@dataclasses.dataclass(frozen=True)
class XEBPhasedFSimCharacterizationOptions(XEBCharacterizationOptions):
"""Options for calibrating a PhasedFSim-like gate using XEB.

Expand Down Expand Up @@ -320,6 +313,9 @@ def with_defaults_from_gate(
**gate_to_angles_func(gate),
)

def _json_dict_(self):
return protocols.dataclass_json_dict(self)


def SqrtISwapXEBOptions(*args, **kwargs):
"""Options for calibrating a sqrt(ISWAP) gate using XEB."""
Expand All @@ -346,7 +342,7 @@ def parameterize_circuit(
QPair_T = Tuple['cirq.Qid', 'cirq.Qid']


@dataclass(frozen=True)
@dataclasses.dataclass(frozen=True)
class XEBCharacterizationResult:
"""The result of `characterize_phased_fsim_parameters_with_xeb`.

Expand Down Expand Up @@ -437,7 +433,7 @@ def _mean_infidelity(angles):
)


@dataclass(frozen=True)
@dataclasses.dataclass(frozen=True)
class _CharacterizePhasedFsimParametersWithXebClosure:
"""A closure object to wrap `characterize_phased_fsim_parameters_with_xeb` for use in
multiprocessing."""
Expand Down
1 change: 1 addition & 0 deletions cirq-core/cirq/protocols/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
to_json,
read_json,
obj_to_dict_helper,
dataclass_json_dict,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was going to say sort imports, but it looks like we haven't been doing that consistently. Really needs to be automated...

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Craig and I are in solidarity that we won't manually sort imports

SerializableByKey,
SupportsJSON,
)
Expand Down
22 changes: 22 additions & 0 deletions cirq-core/cirq/protocols/json_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,13 @@ def json_serializable_dataclass(
the ``_json_dict_`` protocol method which automatically determines
the appropriate fields from the dataclass.

Dataclasses are implemented with somewhat complex metaprogramming, and
tooling (PyCharm, mypy) have special cases for dealing with classes
decorated with @dataclass. There is very little support (and no plans for
support) for decorators that wrap @dataclass like this. Consider explicitly
defining `_json_dict_` on your dataclasses which simply
`return dataclass_json_dict(self)`.

Args:
namespace: An optional prefix to the value associated with the
key "cirq_type". The namespace name will be joined with the
Expand Down Expand Up @@ -209,6 +216,21 @@ def wrap(cls):
# pylint: enable=redefined-builtin


def dataclass_json_dict(obj: Any, namespace: str = None) -> Dict[str, Any]:
"""Return a dictionary suitable for _json_dict_ from a dataclass.

Dataclasses keep track of their relevant fields, so we can automatically generate these.

Dataclasses are implemented with somewhat complex metaprogramming, and tooling (PyCharm, mypy)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This paragraph is largely duplicated in the module docstring above. I'd suggest removing it here and relying on the module docstring.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what do you mean module docstring? do you mean the docstring for json_serializable_dataclass? I think it's relevant to both functions. Especially if we remove json_serializable_dataclass

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah sorry, I thought other occurence of this text was in the json_serialization.py module docstring. Agree it's fine to have on json_serializable_dataclass.

have special cases for dealing with classes decorated with @dataclass. There is very little
support (and no plans for support) for decorators that wrap @dataclass (like
@cirq.json_serializable_dataclass) or combining additional decorators with @dataclass.
Although not as elegant, you may want to consider explicitly defining `_json_dict_` on your
dataclasses which simply `return dataclass_json_dict(self)`.
"""
return obj_to_dict_helper(obj, [f.name for f in dataclasses.fields(obj)], namespace=namespace)


class CirqEncoder(json.JSONEncoder):
"""Extend json.JSONEncoder to support Cirq objects.

Expand Down
18 changes: 18 additions & 0 deletions cirq-core/cirq/protocols/json_serialization_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,24 @@ def custom_resolver(name):
assert_json_roundtrip_works(my_dc, 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_json_serializable_dataclass_namespace():
@cirq.json_serializable_dataclass(namespace='cirq.experiments')
class QuantumVolumeParams:
Expand Down