Skip to content

Commit

Permalink
Add examples for transform_qubits function (#6915)
Browse files Browse the repository at this point in the history
* Add examples for transform_qubits function

- Adds a simple example for Circuit.transform_qubits
and Operation.transform_qubits

Fixes: #4014

* Fix Doc test.
  • Loading branch information
dstrain115 authored Jan 4, 2025
1 parent c5d29fe commit 83a8e0e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
18 changes: 18 additions & 0 deletions cirq-core/cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -2010,6 +2010,24 @@ def transform_qubits(
) -> 'cirq.Circuit':
"""Returns the same circuit, but with different qubits.
This function will return a new `Circuit` with the same gates but
with qubits mapped according to the argument.
For example, the following will translate LineQubits to GridQubits:
>>> grid_qubits = cirq.GridQubit.square(2)
>>> line_qubits = cirq.LineQubit.range(4)
>>> circuit = cirq.Circuit([cirq.H(q) for q in line_qubits])
>>> circuit.transform_qubits(lambda q : grid_qubits[q.x])
cirq.Circuit([
cirq.Moment(
cirq.H(cirq.GridQubit(0, 0)),
cirq.H(cirq.GridQubit(0, 1)),
cirq.H(cirq.GridQubit(1, 0)),
cirq.H(cirq.GridQubit(1, 1)),
),
])
Args:
qubit_map: A function or a dict mapping each current qubit into a desired
new qubit.
Expand Down
20 changes: 20 additions & 0 deletions cirq-core/cirq/ops/raw_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,26 @@ def transform_qubits(
) -> Self:
"""Returns the same operation, but with different qubits.
This function will return a new operation with the same gate but
with qubits mapped according to the argument.
For example, the following will translate LineQubits to GridQubits
using a grid with 4 columns:
>>> op = cirq.CZ(cirq.LineQubit(5), cirq.LineQubit(9))
>>> op.transform_qubits(lambda q: cirq.GridQubit(q.x // 4, q.x % 4))
cirq.CZ(cirq.GridQubit(1, 1), cirq.GridQubit(2, 1))
This can also be used with a dictionary that has a mapping, such
as the following which maps named qubits to line qubits:
>>> a = cirq.NamedQubit('alice')
>>> b = cirq.NamedQubit('bob')
>>> d = {a: cirq.LineQubit(4), b: cirq.LineQubit(5)}
>>> op = cirq.CNOT(a, b)
>>> op.transform_qubits(d)
cirq.CNOT(cirq.LineQubit(4), cirq.LineQubit(5))
Args:
qubit_map: A function or a dict mapping each current qubit into a desired
new qubit.
Expand Down

0 comments on commit 83a8e0e

Please sign in to comment.