# How to add noise to existing gates in Cirq?

I would like to add noise to existing gates in Cirq, i.e. to define something like

NewGate = cirq.Gate(qubit)


followed by

cirq.DepolarizingChannel(p).on(qubit)


How can I do this?

One simple way to do it is by defining a composite gate, like this:

class MyGateThenDepolarize(cirq.SingleQubitGate):
def _decompose_(self, qubits):
q = qubits
return [MyGate.on(q), cirq.depolarize(p).on(q)]


If you want a depolarizing gate on every qubit at the end of every moment, you can do a noisy simulation:

cirq.sample(circuit, noise=cirq.depolarize(p))


Or get a noisy version of the circuit:

circuit = circuit.with_noise(cirq.depolarize(p))


If you specifically want a noise model that depolarizes the one gate, you can define a custom noise model that does that:

class MyGateDepolarizingNoiseModel(cirq.NoiseModel):
def noisy_operation(self, op):
if isinstance(op.gate, MyGate):
return [op, cirq.depolarize(p).on(op.qubits)]
return op


And here's a test confirming that it works:

import cirq

def test_custom_noise_model():
p = 0.1

class MyGate(cirq.Gate):
def _num_qubits_(self):
return 1
def _decompose_(self, qubits):
return cirq.X(*qubits)

class MyGateDepolarizingNoiseModel(cirq.NoiseModel):
def noisy_operation(self, op):
if isinstance(op.gate, MyGate):
return [op, cirq.depolarize(p).on(op.qubits)]
return op

a, b = cirq.LineQubit.range(2)
c = cirq.Circuit(
MyGate().on(a),
cirq.X.on(b),
cirq.measure(a, key='a'),
cirq.measure(b, key='b'),
)
results = cirq.sample(
c,
noise=MyGateDepolarizingNoiseModel(),
repetitions=1000)
assert sum(results.data['a']) < 1000  # yes depolarized
assert sum(results.data['b']) == 1000  # not depolarized

print(results.data['a'].value_counts())
# 1    942
# 0     58
# Name: a, dtype: int64

print(results.data['b'].value_counts())
# 1    1000
# Name: b, dtype: int64