Skip to content

Add JSON serialisations #7396

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

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
9a0f8f1
Add JSON serialisations
WingCode May 30, 2025
6c0d9bb
Add test JSON and fix tests
WingCode Jun 1, 2025
51d9035
Fix tests
WingCode Jun 1, 2025
bcc575c
Merge branch 'main' into add-ser-noise-models
pavoljuhas Jun 2, 2025
8da202f
Merge branch 'main' into add-ser-noise-models
mhucka Jun 6, 2025
0643e61
Fix pylint
WingCode Jun 6, 2025
e5fa84b
Add tests
WingCode Jun 6, 2025
4e98a55
Add tests
WingCode Jun 6, 2025
52f72cd
Fix tests
WingCode Jun 7, 2025
7d29cad
Fix lint
WingCode Jun 7, 2025
edb0c6d
Fix black
WingCode Jun 9, 2025
2e9bbd9
Merge branch 'main' into add-ser-noise-models
WingCode Jun 9, 2025
9b8b7fe
Merge branch 'main' into add-ser-noise-models
WingCode Jun 10, 2025
b867010
Fix lint
WingCode Jun 10, 2025
0f06ac3
Merge branch 'main' into add-ser-noise-models
mhucka Jun 11, 2025
555495e
Merge branch 'main' into add-ser-noise-models
WingCode Jun 14, 2025
a3b9ea4
Address review comments
WingCode Jun 14, 2025
e46ebfe
Fix lint
WingCode Jun 16, 2025
45942cd
Fix lint
WingCode Jun 16, 2025
6957dea
Fix tests
WingCode Jun 16, 2025
0f3aab9
Fix tests
WingCode Jun 16, 2025
c8d88a7
Fix tests
WingCode Jun 16, 2025
ec315f0
Fix tests
WingCode Jun 16, 2025
e03d267
Fix tests
WingCode Jun 16, 2025
c6d3059
Fix tests
WingCode Jun 16, 2025
9c02b87
Merge branch 'quantumlib:main' into add-ser-noise-models
WingCode Jun 16, 2025
2d2af5c
Update cirq-core/cirq/contrib/json_test_data/__init__.py
WingCode Jun 17, 2025
4bcbb8b
Update cirq-core/cirq/devices/thermal_noise_model_test.py
WingCode Jun 17, 2025
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
3 changes: 3 additions & 0 deletions cirq-core/cirq/contrib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,6 @@
from cirq.contrib.qcircuit import circuit_to_latex_using_qcircuit as circuit_to_latex_using_qcircuit
from cirq.contrib import json # noqa: F401
from cirq.contrib.circuitdag import CircuitDag as CircuitDag, Unique as Unique
from cirq.contrib.acquaintance import SwapPermutationGate as SwapPermutationGate
from cirq.contrib.bayesian_network import BayesianNetworkGate as BayesianNetworkGate
from cirq.contrib.quantum_volume import QuantumVolumeResult as QuantumVolumeResult
36 changes: 32 additions & 4 deletions cirq-core/cirq/contrib/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,46 @@

from __future__ import annotations

from cirq.protocols.json_serialization import DEFAULT_RESOLVERS
import functools
from typing import TYPE_CHECKING

from cirq.protocols.json_serialization import _register_resolver, DEFAULT_RESOLVERS

if TYPE_CHECKING: # pragma: no cover
from cirq.protocols.json_serialization import ObjectFactory


def contrib_class_resolver(cirq_type: str):
"""Extend cirq's JSON API with resolvers for cirq contrib classes."""
return _class_resolver_dictionary().get(cirq_type, None)


@functools.lru_cache()
def _class_resolver_dictionary() -> dict[str, ObjectFactory]:
from cirq.contrib.acquaintance import SwapPermutationGate
from cirq.contrib.bayesian_network import BayesianNetworkGate
from cirq.contrib.noise_models import (
DampedReadoutNoiseModel,
DepolarizingNoiseModel,
DepolarizingWithDampedReadoutNoiseModel,
DepolarizingWithReadoutNoiseModel,
ReadoutNoiseModel,
)
from cirq.contrib.quantum_volume import QuantumVolumeResult

classes = [BayesianNetworkGate, QuantumVolumeResult, SwapPermutationGate]
d = {cls.__name__: cls for cls in classes}
return d.get(cirq_type, None)
classes = [
BayesianNetworkGate,
QuantumVolumeResult,
SwapPermutationGate,
DepolarizingNoiseModel,
ReadoutNoiseModel,
DampedReadoutNoiseModel,
DepolarizingWithReadoutNoiseModel,
DepolarizingWithDampedReadoutNoiseModel,
]
return {cls.__name__: cls for cls in classes}


DEFAULT_CONTRIB_RESOLVERS = [contrib_class_resolver] + DEFAULT_RESOLVERS

_register_resolver(_class_resolver_dictionary)
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"cirq_type": "DampedReadoutNoiseModel",
"decay_prob": 0.3,
"prepend": true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
cirq.contrib.noise_models.DampedReadoutNoiseModel(0.3, prepend=True)
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"cirq_type": "DepolarizingNoiseModel",
"depol_prob": 0.1,
"prepend": false
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
cirq.contrib.noise_models.DepolarizingNoiseModel(0.1, prepend=False)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"cirq_type": "DepolarizingWithDampedReadoutNoiseModel",
"depol_prob": 0.1,
"bitflip_prob": 0.2,
"decay_prob": 0.3
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
cirq.contrib.noise_models.DepolarizingWithDampedReadoutNoiseModel(0.1, 0.2, 0.3)
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"cirq_type": "DepolarizingWithReadoutNoiseModel",
"depol_prob": 0.1,
"bitflip_prob": 0.2
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
cirq.contrib.noise_models.DepolarizingWithReadoutNoiseModel(0.1, 0.2)
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"cirq_type": "ReadoutNoiseModel",
"bitflip_prob": 0.2,
"prepend": true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
cirq.contrib.noise_models.ReadoutNoiseModel(0.2, prepend=True)
17 changes: 17 additions & 0 deletions cirq-core/cirq/contrib/json_test_data/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Copyright 2025 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# 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.

"""Test data for JSON serialization of :mod:`cirq.contrib` objects."""

from cirq.contrib.json_test_data.spec import TestSpec as TestSpec
35 changes: 35 additions & 0 deletions cirq-core/cirq/contrib/json_test_data/spec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# pylint: disable=wrong-or-nonexistent-copyright-notice
Copy link
Collaborator

Choose a reason for hiding this comment

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

Please replace with the actual copyright statement as in __init__.py.

from __future__ import annotations

import pathlib

import cirq
from cirq.contrib.json import _class_resolver_dictionary
from cirq.testing.json import ModuleJsonTestSpec

TestSpec = ModuleJsonTestSpec(
name="cirq.contrib",
packages=[cirq.contrib],
test_data_path=pathlib.Path(__file__).parent,
not_yet_serializable=[],
should_not_be_serialized=[
"QuantumVolumeResult",
"SwapPermutationGate",
"BayesianNetworkGate",
Comment on lines +16 to +18
Copy link
Collaborator

@pavoljuhas pavoljuhas Jun 17, 2025

Choose a reason for hiding this comment

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

The first 3 classes are serializable and should NOT be listed here.

Please add the corresponding .repr and .json files instead.

After that you can replace the dictionary filtering below with

resolver_cache=_class_resolver_dictionary(),

"Unique",
"CircuitDag",
],
resolver_cache={
k: v
for k, v in _class_resolver_dictionary().items()
if k
not in {
"QuantumVolumeResult",
"SwapPermutationGate",
"BayesianNetworkGate",
"Unique",
"CircuitDag",
}
},
deprecated={},
)
99 changes: 99 additions & 0 deletions cirq-core/cirq/contrib/noise_models/noise_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import cirq


@value.value_equality()
class DepolarizingNoiseModel(devices.NoiseModel):
"""Applies depolarizing noise to each qubit individually at the end of
every moment.
Expand All @@ -39,9 +40,20 @@ def __init__(self, depol_prob: float, prepend: bool = False):
prepend: If True, put noise before affected gates. Default: False.
"""
value.validate_probability(depol_prob, 'depol prob')
self.depol_prob = depol_prob
self.qubit_noise_gate = ops.DepolarizingChannel(depol_prob)
self._prepend = prepend

def _value_equality_values_(self):
return self.depol_prob, self._prepend

def __repr__(self) -> str:
p = self.depol_prob
return (
f'cirq.contrib.noise_models.DepolarizingNoiseModel('
f'{p!r}, prepend={self._prepend!r})'
)

def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]):
if validate_all_measurements(moment) or self.is_virtual_moment(moment): # pragma: no cover
return moment
Expand All @@ -54,7 +66,15 @@ def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]):
]
return output[::-1] if self._prepend else output

def _json_dict_(self) -> dict[str, object]:
return {'depol_prob': self.depol_prob, 'prepend': self._prepend}

@classmethod
def _from_json_dict_(cls, depol_prob, prepend, **kwargs):
return cls(depol_prob, prepend=prepend)
Comment on lines +72 to +74
Copy link
Collaborator

Choose a reason for hiding this comment

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

When _json_dict_ provides all __init__ arguments, the _from_json_dict_ method is redundant. Please remove here and in other similar instances in this PR.

Suggested change
@classmethod
def _from_json_dict_(cls, depol_prob, prepend, **kwargs):
return cls(depol_prob, prepend=prepend)



@value.value_equality()
class ReadoutNoiseModel(devices.NoiseModel):
"""NoiseModel with probabilistic bit flips preceding measurement.

Expand All @@ -75,9 +95,17 @@ def __init__(self, bitflip_prob: float, prepend: bool = True):
prepend: If True, put noise before affected gates. Default: True.
"""
value.validate_probability(bitflip_prob, 'bitflip prob')
self.bitflip_prob = bitflip_prob
self.readout_noise_gate = ops.BitFlipChannel(bitflip_prob)
self._prepend = prepend

def _value_equality_values_(self):
return self.bitflip_prob, self._prepend

def __repr__(self) -> str:
p = self.bitflip_prob
return f'cirq.contrib.noise_models.ReadoutNoiseModel(' f'{p!r}, prepend={self._prepend!r})'

def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]):
if self.is_virtual_moment(moment):
return moment
Expand All @@ -91,7 +119,15 @@ def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]):
return output if self._prepend else output[::-1]
return moment

def _json_dict_(self) -> dict[str, object]:
return {'bitflip_prob': self.bitflip_prob, 'prepend': self._prepend}

@classmethod
def _from_json_dict_(cls, bitflip_prob, prepend, **kwargs):
return cls(bitflip_prob, prepend=prepend)


@value.value_equality()
class DampedReadoutNoiseModel(devices.NoiseModel):
"""NoiseModel with T1 decay preceding measurement.

Expand All @@ -112,9 +148,20 @@ def __init__(self, decay_prob: float, prepend: bool = True):
prepend: If True, put noise before affected gates. Default: True.
"""
value.validate_probability(decay_prob, 'decay_prob')
self.decay_prob = decay_prob
self.readout_decay_gate = ops.AmplitudeDampingChannel(decay_prob)
self._prepend = prepend

def _value_equality_values_(self):
return self.decay_prob, self._prepend

def __repr__(self) -> str:
p = self.decay_prob
return (
f'cirq.contrib.noise_models.DampedReadoutNoiseModel('
f'{p!r}, prepend={self._prepend!r})'
)

def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]):
if self.is_virtual_moment(moment):
return moment
Expand All @@ -128,7 +175,15 @@ def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]):
return output if self._prepend else output[::-1]
return moment

def _json_dict_(self) -> dict[str, object]:
return {'decay_prob': self.decay_prob, 'prepend': self._prepend}

@classmethod
def _from_json_dict_(cls, decay_prob, prepend, **kwargs):
return cls(decay_prob, prepend=prepend)


@value.value_equality()
class DepolarizingWithReadoutNoiseModel(devices.NoiseModel):
"""DepolarizingNoiseModel with probabilistic bit flips preceding
measurement.
Expand All @@ -145,15 +200,33 @@ def __init__(self, depol_prob: float, bitflip_prob: float):
"""
value.validate_probability(depol_prob, 'depol prob')
value.validate_probability(bitflip_prob, 'bitflip prob')
self.depol_prob = depol_prob
self.bitflip_prob = bitflip_prob
self.qubit_noise_gate = ops.DepolarizingChannel(depol_prob)
self.readout_noise_gate = ops.BitFlipChannel(bitflip_prob)

def _value_equality_values_(self):
return self.depol_prob, self.bitflip_prob

def __repr__(self) -> str:
p = self.depol_prob
b = self.bitflip_prob
return 'cirq.contrib.noise_models.DepolarizingWithReadoutNoiseModel(' f'{p!r}, {b!r})'

def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]):
if validate_all_measurements(moment):
return [circuits.Moment(self.readout_noise_gate(q) for q in system_qubits), moment]
return [moment, circuits.Moment(self.qubit_noise_gate(q) for q in system_qubits)]

def _json_dict_(self) -> dict[str, object]:
return {'depol_prob': self.depol_prob, 'bitflip_prob': self.bitflip_prob}

@classmethod
def _from_json_dict_(cls, depol_prob, bitflip_prob, **kwargs):
return cls(depol_prob, bitflip_prob)


@value.value_equality()
class DepolarizingWithDampedReadoutNoiseModel(devices.NoiseModel):
"""DepolarizingWithReadoutNoiseModel with T1 decay preceding
measurement.
Expand All @@ -174,10 +247,25 @@ def __init__(self, depol_prob: float, bitflip_prob: float, decay_prob: float):
value.validate_probability(depol_prob, 'depol prob')
value.validate_probability(bitflip_prob, 'bitflip prob')
value.validate_probability(decay_prob, 'decay_prob')
self.depol_prob = depol_prob
self.bitflip_prob = bitflip_prob
self.decay_prob = decay_prob
self.qubit_noise_gate = ops.DepolarizingChannel(depol_prob)
self.readout_noise_gate = ops.BitFlipChannel(bitflip_prob)
self.readout_decay_gate = ops.AmplitudeDampingChannel(decay_prob)

def _value_equality_values_(self):
return self.depol_prob, self.bitflip_prob, self.decay_prob

def __repr__(self) -> str:
p = self.depol_prob
b = self.bitflip_prob
d = self.decay_prob
return (
'cirq.contrib.noise_models.DepolarizingWithDampedReadoutNoiseModel('
f'{p!r}, {b!r}, {d!r})'
)

def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]):
if validate_all_measurements(moment):
return [
Expand All @@ -187,3 +275,14 @@ def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]):
]
else:
return [moment, circuits.Moment(self.qubit_noise_gate(q) for q in system_qubits)]

def _json_dict_(self) -> dict[str, object]:
return {
'depol_prob': self.depol_prob,
'bitflip_prob': self.bitflip_prob,
'decay_prob': self.decay_prob,
}

@classmethod
def _from_json_dict_(cls, depol_prob, bitflip_prob, decay_prob, **kwargs):
return cls(depol_prob, bitflip_prob, decay_prob)
18 changes: 18 additions & 0 deletions cirq-core/cirq/contrib/noise_models/noise_models_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

from __future__ import annotations

import pytest

import cirq
import cirq.contrib.noise_models as ccn
from cirq import ops
Expand Down Expand Up @@ -94,6 +96,22 @@ def test_readout_noise_after_moment() -> None:
assert_equivalent_op_tree(true_noisy_program, noisy_circuit)


@pytest.mark.parametrize(
'model',
[
ccn.DepolarizingNoiseModel(0.1),
ccn.ReadoutNoiseModel(0.2),
ccn.DampedReadoutNoiseModel(0.3),
ccn.DepolarizingWithReadoutNoiseModel(0.1, 0.2),
ccn.DepolarizingWithDampedReadoutNoiseModel(0.1, 0.2, 0.3),
],
)
def test_repr_and_json_roundtrip(model) -> None:
assert model == eval(repr(model))
json_text = cirq.to_json(model)
assert cirq.read_json(json_text=json_text) == model


def test_readout_noise_no_prepend() -> None:
noise_model = ccn.ReadoutNoiseModel(bitflip_prob=0.005, prepend=False)
qubits = cirq.LineQubit.range(2)
Expand Down
Loading