Skip to content

Commit

Permalink
Re-enable doctest (quantumlib#5742)
Browse files Browse the repository at this point in the history
  • Loading branch information
dabacon authored and rht committed May 1, 2023
1 parent 2433771 commit 4b39772
Show file tree
Hide file tree
Showing 16 changed files with 203 additions and 147 deletions.
15 changes: 10 additions & 5 deletions cirq-core/cirq/devices/grid_device_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,16 +153,21 @@ def gate_durations(self) -> Optional[Mapping['cirq.GateFamily', 'cirq.Duration']
To look up the duration of a specific gate instance / gate type / operation which is part of
the device's gateset, you can search for its corresponding GateFamily. For example:
>>> my_op = cirq.Z
>>> gateset = cirq.Gateset(cirq.ZPowGate)
>>> durations = {cirq.GateFamily(cirq.ZPowGate): cirq.Duration(nanos=1)}
>>> grid_device_metadata = cirq.GridDeviceMetadata((), gateset, durations)
>>>
>>> my_gate = cirq.Z
>>> gate_durations = grid_device_metadata.gate_durations
>>> op_duration = None
>>> gate_duration = None
>>> for gate_family in gate_durations:
... if my_op in gate_family:
... op_duration = gate_durations[gate_family]
... if my_gate in gate_family:
... gate_duration = gate_durations[gate_family]
...
>>> print(op_duration)
>>> print(gate_duration)
1 ns
"""

return self._gate_durations

def _value_equality_values_(self):
Expand Down
22 changes: 12 additions & 10 deletions cirq-core/cirq/ops/arithmetic_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,21 @@ class ArithmeticGate(Gate, metaclass=abc.ABCMeta):
>>> class Add(cirq.ArithmeticGate):
... def __init__(
... self,
... target_register: [int, Sequence[int]],
... input_register: Union[int, Sequence[int]],
... target_register: '[int, Sequence[int]]',
... input_register: 'Union[int, Sequence[int]]',
... ):
... self.target_register = target_register
... self.input_register = input_register
...
... def registers(self) -> Sequence[Union[int, Sequence[int]]]:
... def registers(self) -> 'Sequence[Union[int, Sequence[int]]]':
... return self.target_register, self.input_register
...
... def with_registers(self, *new_registers: Union[int, Sequence[int]]) -> TSelfGate:
... def with_registers(
... self, *new_registers: 'Union[int, Sequence[int]]'
... ) -> 'TSelfGate':
... return Add(*new_registers)
...
... def apply(self, *register_values: int) -> Union[int, Iterable[int]]:
... def apply(self, *register_values: int) -> 'Union[int, Iterable[int]]':
... return sum(register_values)
>>> cirq.unitary(
... Add(target_register=[2, 2],
Expand All @@ -71,17 +73,17 @@ class ArithmeticGate(Gate, metaclass=abc.ABCMeta):
... cirq.X(cirq.LineQubit(3)),
... cirq.X(cirq.LineQubit(2)),
... cirq.X(cirq.LineQubit(6)),
... cirq.measure(*cirq.LineQubit.range(4, 8), key='before:in'),
... cirq.measure(*cirq.LineQubit.range(4), key='before:out'),
... cirq.measure(*cirq.LineQubit.range(4, 8), key='before_in'),
... cirq.measure(*cirq.LineQubit.range(4), key='before_out'),
...
... Add(target_register=[2] * 4,
... input_register=[2] * 4).on(*cirq.LineQubit.range(8)),
...
... cirq.measure(*cirq.LineQubit.range(4, 8), key='after:in'),
... cirq.measure(*cirq.LineQubit.range(4), key='after:out'),
... cirq.measure(*cirq.LineQubit.range(4, 8), key='after_in'),
... cirq.measure(*cirq.LineQubit.range(4), key='after_out'),
... )
>>> cirq.sample(c).data
before:in before:out after:in after:out
before_in before_out after_in after_out
0 2 3 2 5
```
Expand Down
20 changes: 5 additions & 15 deletions cirq-core/cirq/ops/linear_combinations.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,24 +379,16 @@ class PauliSum:
... cirq.PauliString(0.5, cirq.Y(a), cirq.Y(b))
... ])
>>> print(psum)
-1.000*X(q(0))*Y(q(1))+2.000*Z(q(0))*Z(q(1))+0.500*Y(q(0))*Y(q(1))
-1.000*X(q(0, 0))*Y(q(0, 1))+2.000*Z(q(0, 0))*Z(q(0, 1))+0.500*Y(q(0, 0))*Y(q(0, 1))
or implicitly:
>>> a, b = cirq.GridQubit.rect(1, 2)
>>> psum = cirq.X(a) * cirq.X(b) + 3.0 * cirq.Y(a)
>>> psum
cirq.PauliSum(
cirq.LinearDict({
frozenset({
(cirq.GridQubit(0, 0), cirq.X), (cirq.GridQubit(0, 1), cirq.X)}): (1+0j),
frozenset({
(cirq.GridQubit(0, 0), cirq.Y)}): (3+0j)}
)
)
>>> print(psum)
1.000*X(q(0, 0))*X(q(0, 1))+3.000*Y(q(0, 0))
basic arithmetic and expectation operations are supported as well:
Expand All @@ -413,10 +405,8 @@ class PauliSum:
... np.array([0.707106, 0, 0, 0.707106], dtype=complex),
... qubit_map={a: 0, b: 1}
... )
>>> expectation
4.0
>>> print(f'{expectation:.1f}')
4.0+0.0j
"""

def __init__(self, linear_dict: Optional[value.LinearDict[UnitPauliStringT]] = None):
Expand Down
18 changes: 9 additions & 9 deletions cirq-core/cirq/ops/pauli_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,20 +146,20 @@ class PauliString(raw_types.Operation, Generic[TKey]):
I
>>> print(cirq.PauliString(-1, cirq.X(a), cirq.Y(b), cirq.Z(c)))
-X(0)*Y(1)*Z(2)
-X(q(0))*Y(q(1))*Z(q(2))
>>> -1 * cirq.X(a) * cirq.Y(b) * cirq.Z(c)
-X(0) * Y(1) * Z(2)
>>> print(-1 * cirq.X(a) * cirq.Y(b) * cirq.Z(c))
-X(q(0))*Y(q(1))*Z(q(2))
>>> print(cirq.PauliString({a: cirq.X}, [-2, 3, cirq.Y(a)]))
-6j*Z(0)
-6j*Z(q(0))
>>> print(cirq.PauliString({a: cirq.I, b: cirq.X}))
X(1)
X(q(1))
>>> print(cirq.PauliString({a: cirq.Y},
... qubit_pauli_map={a: cirq.X}))
1j*Z(0)
1j*Z(q(0))
Note that `cirq.PauliString`s are immutable objects. If you need a mutable version
of pauli strings, see `cirq.MutablePauliString`.
Expand Down Expand Up @@ -975,11 +975,11 @@ def conjugated_by(self, clifford: 'cirq.OP_TREE') -> 'PauliString':
Examples:
>>> a, b = cirq.LineQubit.range(2)
>>> print(cirq.X(a).conjugated_by(cirq.CZ(a, b)))
X(0)*Z(1)
X(q(0))*Z(q(1))
>>> print(cirq.X(a).conjugated_by(cirq.S(a)))
-Y(0)
-Y(q(0))
>>> print(cirq.X(a).conjugated_by([cirq.H(a), cirq.CNOT(a, b)]))
Z(0)*X(1)
Z(q(0))*X(q(1))
Returns:
The Pauli string conjugated by the given Clifford operation.
Expand Down
3 changes: 3 additions & 0 deletions cirq-core/cirq/ops/qid_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,11 @@ def q(*args: Union[int, str]) -> Union['cirq.LineQubit', 'cirq.GridQubit', 'cirq
This is shorthand for constructing qubit ids of common types:
>>> cirq.q(1) == cirq.LineQubit(1)
True
>>> cirq.q(1, 2) == cirq.GridQubit(1, 2)
True
>>> cirq.q("foo") == cirq.NamedQubit("foo")
True
Note that arguments should be treated as positional only, even
though this is only enforceable in python 3.8 or later.
Expand Down
14 changes: 7 additions & 7 deletions cirq-core/cirq/sim/clifford/stabilizer_simulation_state_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from unittest.mock import Mock, call
import unittest.mock as mock

import numpy as np
import sympy
Expand All @@ -22,7 +22,7 @@

def test_apply_gate():
q0, q1 = cirq.LineQubit.range(2)
state = Mock()
state = mock.Mock()
args = cirq.StabilizerSimulationState(state=state, qubits=[q0, q1])

assert args._strat_apply_gate(cirq.X, [q0]) is True
Expand Down Expand Up @@ -78,11 +78,11 @@ def test_apply_gate():

state.reset_mock()
assert args._strat_apply_gate(cirq.SWAP, [q0, q1]) is True
state.apply_cx.assert_has_calls([call(0, 1), call(1, 0, 1.0, 0.0), call(0, 1)])
state.apply_cx.assert_has_calls([mock.call(0, 1), mock.call(1, 0, 1.0, 0.0), mock.call(0, 1)])

state.reset_mock()
assert args._strat_apply_gate(cirq.SwapPowGate(exponent=2, global_shift=1.3), [q0, q1]) is True
state.apply_cx.assert_has_calls([call(0, 1), call(1, 0, 2.0, 1.3), call(0, 1)])
state.apply_cx.assert_has_calls([mock.call(0, 1), mock.call(1, 0, 2.0, 1.3), mock.call(0, 1)])

state.reset_mock()
assert args._strat_apply_gate(cirq.BitFlipChannel(0.5), [q0]) == NotImplemented
Expand All @@ -91,7 +91,7 @@ def test_apply_gate():

def test_apply_mixture():
q0 = cirq.LineQubit(0)
state = Mock()
state = mock.Mock()
args = cirq.StabilizerSimulationState(state=state, qubits=[q0])

for _ in range(100):
Expand All @@ -102,7 +102,7 @@ def test_apply_mixture():

def test_act_from_single_qubit_decompose():
q0 = cirq.LineQubit(0)
state = Mock()
state = mock.Mock()
args = cirq.StabilizerSimulationState(state=state, qubits=[q0])
assert (
args._strat_act_from_single_qubit_decompose(
Expand All @@ -122,7 +122,7 @@ def _qid_shape_(self):
pass

q0 = cirq.LineQubit(0)
state = Mock()
state = mock.Mock()
args = cirq.StabilizerSimulationState(state=state, qubits=[q0])
assert args._strat_decompose(XContainer(), [q0]) is True
state.apply_x.assert_called_with(0, 1.0, 0.0)
7 changes: 4 additions & 3 deletions cirq-core/cirq/testing/repr_pretty_tester.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ class FakePrinter:
Can be used in tests to test a classes `_repr_pretty_` method:
>>> p = FakePrinter()
>>> s = object_under_test._repr_pretty(p, cycle=False)
>>> p = cirq.testing.FakePrinter()
>>> object_under_test = cirq.ResultDict(params=None, measurements={'x': np.array([[0, 1]] )})
>>> s = object_under_test._repr_pretty_(p, cycle=False)
>>> p.text_pretty
'my pretty_text'
'x=0, 1'
Prefer to use `assert_repr_pretty` below.
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,10 @@
from typing import Optional, List, Hashable, TYPE_CHECKING
import abc

from cirq import circuits, ops, protocols, _import
from cirq import circuits, ops, protocols, transformers
from cirq.protocols.decompose_protocol import DecomposeResult
from cirq.transformers import merge_k_qubit_gates, merge_single_qubit_gates

drop_empty_moments = _import.LazyLoader('drop_empty_moments', globals(), 'cirq.transformers')
drop_negligible = _import.LazyLoader('drop_negligible_operations', globals(), 'cirq.transformers')
expand_composite = _import.LazyLoader('expand_composite', globals(), 'cirq.transformers')

if TYPE_CHECKING:
import cirq
Expand All @@ -37,16 +34,18 @@ def create_transformer_with_kwargs(transformer: 'cirq.TRANSFORMER', **kwargs) ->
capture keyword arguments of a transformer before passing them as an argument to an API that
expects `cirq.TRANSFORMER`. For example:
>>> def run_transformers(transformers: List[cirq.TRANSFORMER]):
>>> for transformer in transformers:
>>> transformer(circuit, context=context)
>>>
>>> transformers: List[cirq.TRANSFORMER] = []
>>> def run_transformers(transformers: 'List[cirq.TRANSFORMER]'):
... circuit = cirq.Circuit(cirq.X(cirq.q(0)))
... context = cirq.TransformerContext()
... for transformer in transformers:
... transformer(circuit, context=context)
...
>>> transformers: 'List[cirq.TRANSFORMER]' = []
>>> transformers.append(
>>> cirq.create_transformer_with_kwargs(
>>> cirq.expand_composite, no_decomp=lambda op: cirq.num_qubits(op) <= 2
>>> )
>>> )
... cirq.create_transformer_with_kwargs(
... cirq.expand_composite, no_decomp=lambda op: cirq.num_qubits(op) <= 2
... )
... )
>>> transformers.append(cirq.create_transformer_with_kwargs(cirq.merge_k_qubit_unitaries, k=2))
>>> run_transformers(transformers)
Expand Down Expand Up @@ -132,7 +131,7 @@ def preprocess_transformers(self) -> List['cirq.TRANSFORMER']:
"""List of transformers which should be run before decomposing individual operations."""
return [
create_transformer_with_kwargs(
expand_composite.expand_composite,
transformers.expand_composite,
no_decomp=lambda op: protocols.num_qubits(op) <= self.num_qubits,
),
create_transformer_with_kwargs(
Expand All @@ -147,8 +146,8 @@ def postprocess_transformers(self) -> List['cirq.TRANSFORMER']:
"""List of transformers which should be run after decomposing individual operations."""
return [
merge_single_qubit_gates.merge_single_qubit_moments_to_phxz,
drop_negligible.drop_negligible_operations,
drop_empty_moments.drop_empty_moments,
transformers.drop_negligible_operations,
transformers.drop_empty_moments,
]


Expand Down
Loading

0 comments on commit 4b39772

Please sign in to comment.