Skip to content
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

Json serialize MSGate #4605

Merged
merged 10 commits into from
Oct 29, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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
10 changes: 9 additions & 1 deletion cirq-core/cirq/ion/ion_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

"""Operations native to iontrap systems."""

from typing import Union, TYPE_CHECKING
from typing import Any, Dict, Union, TYPE_CHECKING
import numpy as np

from cirq import ops, value
Expand All @@ -39,6 +39,7 @@ class MSGate(ops.XXPowGate):

def __init__(self, *, rads: float): # Forces keyword args.
ops.XXPowGate.__init__(self, exponent=rads * 2 / np.pi, global_shift=-0.5)
self.rads = rads

def _with_exponent(self: 'MSGate', exponent: value.TParamVal) -> 'MSGate':
return type(self)(rads=exponent * np.pi / 2)
Expand All @@ -60,6 +61,13 @@ def __repr__(self) -> str:
return 'cirq.ms(np.pi/2)'
return f'cirq.ms({self._exponent!r}*np.pi/2)'

def _json_dict_(self) -> Dict[str, Any]:
return protocols.obj_to_dict_helper(self, ["rads"])

@classmethod
def _from_json_dict_(cls, rads: float, **kwargs: Any) -> Any:
vtomole marked this conversation as resolved.
Show resolved Hide resolved
return cls(rads=rads)


# TODO(#3388) Add summary line to docstring.
# pylint: disable=docstring-first-line-empty
Expand Down
11 changes: 10 additions & 1 deletion cirq-core/cirq/ion/ion_gates_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Callable, Union
import numpy as np

import cirq
Expand Down Expand Up @@ -66,3 +66,12 @@ def test_ms_diagrams():
b: ───×───────────MS(π)───
""",
)


def test_json_serialization():
def custom_resolver(cirq_type: str) -> Union[Callable[..., cirq.Gate], None]:
return cirq.ion.ion_gates.MSGate
vtomole marked this conversation as resolved.
Show resolved Hide resolved

assert cirq.read_json(
json_text=cirq.to_json(cirq.ms(np.pi / 2)), resolvers=[custom_resolver]
) == cirq.ms(np.pi / 2)