|
| 1 | +# Copyright 2022 The Cirq Developers |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import abc |
| 15 | +from typing import Union, Tuple, List, TYPE_CHECKING, Any, Dict, Generator, cast, Iterator |
| 16 | +from dataclasses import dataclass |
| 17 | + |
| 18 | +import itertools |
| 19 | + |
| 20 | +if TYPE_CHECKING: |
| 21 | + import cirq |
| 22 | + |
| 23 | + |
| 24 | +class AbstractControlValues(abc.ABC): |
| 25 | + """Abstract base class defining the API for control values. |
| 26 | +
|
| 27 | + `AbstractControlValues` is an abstract class that defines the API for control values |
| 28 | + and implements functions common to all implementations (e.g. comparison). |
| 29 | +
|
| 30 | + `cirq.ControlledGate` and `cirq.ControlledOperation` are useful to augment |
| 31 | + existing gates and operations to have one or more control qubits. For every |
| 32 | + control qubit, the set of integer values for which the control should be enabled |
| 33 | + is represented by one of the implementations of `cirq.AbstractControlValues`. |
| 34 | +
|
| 35 | + Implementations of `cirq.AbstractControlValues` can use different internal |
| 36 | + representations to store control values, but they must satisfy the public API |
| 37 | + defined here and be immutable. |
| 38 | + """ |
| 39 | + |
| 40 | + @abc.abstractmethod |
| 41 | + def __and__(self, other: 'AbstractControlValues') -> 'AbstractControlValues': |
| 42 | + """Sets self to be the cartesian product of all combinations in self x other. |
| 43 | +
|
| 44 | + Args: |
| 45 | + other: An object that implements AbstractControlValues. |
| 46 | +
|
| 47 | + Returns: |
| 48 | + An object that represents the cartesian product of the two inputs. |
| 49 | + """ |
| 50 | + |
| 51 | + @abc.abstractmethod |
| 52 | + def _expand(self) -> Iterator[Tuple[int, ...]]: |
| 53 | + """Expands the (possibly compressed) internal representation into a sum of products representation.""" # pylint: disable=line-too-long |
| 54 | + |
| 55 | + @abc.abstractmethod |
| 56 | + def diagram_repr(self) -> str: |
| 57 | + """Returns a string representation to be used in circuit diagrams.""" |
| 58 | + |
| 59 | + @abc.abstractmethod |
| 60 | + def _number_variables(self) -> int: |
| 61 | + """Returns the number of variables controlled by the object.""" |
| 62 | + |
| 63 | + @abc.abstractmethod |
| 64 | + def __len__(self) -> int: |
| 65 | + pass |
| 66 | + |
| 67 | + @abc.abstractmethod |
| 68 | + def _identifier(self) -> Any: |
| 69 | + """Returns the internal representation of the object.""" |
| 70 | + |
| 71 | + @abc.abstractmethod |
| 72 | + def __hash__(self) -> int: |
| 73 | + pass |
| 74 | + |
| 75 | + @abc.abstractmethod |
| 76 | + def __repr__(self) -> str: |
| 77 | + pass |
| 78 | + |
| 79 | + @abc.abstractmethod |
| 80 | + def validate(self, qid_shapes: Union[Tuple[int, ...], List[int]]) -> None: |
| 81 | + """Validates control values |
| 82 | +
|
| 83 | + Validate that control values are in the half closed interval |
| 84 | + [0, qid_shapes) for each qubit. |
| 85 | + """ |
| 86 | + |
| 87 | + @abc.abstractmethod |
| 88 | + def _are_ones(self) -> bool: |
| 89 | + """Checks whether all control values are equal to 1.""" |
| 90 | + |
| 91 | + @abc.abstractmethod |
| 92 | + def _json_dict_(self) -> Dict[str, Any]: |
| 93 | + pass |
| 94 | + |
| 95 | + @abc.abstractmethod |
| 96 | + def __getitem__( |
| 97 | + self, key: Union[slice, int] |
| 98 | + ) -> Union['AbstractControlValues', Tuple[int, ...]]: |
| 99 | + pass |
| 100 | + |
| 101 | + def __iter__(self) -> Generator[Tuple[int, ...], None, None]: |
| 102 | + for assignment in self._expand(): |
| 103 | + yield assignment |
| 104 | + |
| 105 | + def __eq__(self, other) -> bool: |
| 106 | + """Returns True iff self and other represent the same configurations. |
| 107 | +
|
| 108 | + Args: |
| 109 | + other: A AbstractControlValues object. |
| 110 | +
|
| 111 | + Returns: |
| 112 | + boolean whether the two objects are equivalent or not. |
| 113 | + """ |
| 114 | + if not isinstance(other, AbstractControlValues): |
| 115 | + other = ProductOfSums(other) |
| 116 | + return sorted(v for v in self) == sorted(v for v in other) |
| 117 | + |
| 118 | + |
| 119 | +@dataclass(frozen=True, eq=False) |
| 120 | +class ProductOfSums(AbstractControlValues): |
| 121 | + """ProductOfSums represents control values in a form of a cartesian product of tuples.""" |
| 122 | + |
| 123 | + _internal_representation: Tuple[Tuple[int, ...], ...] |
| 124 | + |
| 125 | + def _identifier(self) -> Tuple[Tuple[int, ...], ...]: |
| 126 | + return self._internal_representation |
| 127 | + |
| 128 | + def _expand(self) -> Iterator[Tuple[int, ...]]: |
| 129 | + """Returns the combinations tracked by the object.""" |
| 130 | + self = cast('ProductOfSums', self) |
| 131 | + return itertools.product(*self._internal_representation) |
| 132 | + |
| 133 | + def __repr__(self) -> str: |
| 134 | + return f'cirq.ProductOfSums({str(self._identifier())})' |
| 135 | + |
| 136 | + def _number_variables(self) -> int: |
| 137 | + return len(self._internal_representation) |
| 138 | + |
| 139 | + def __len__(self) -> int: |
| 140 | + return self._number_variables() |
| 141 | + |
| 142 | + def __hash__(self) -> int: |
| 143 | + return hash(self._internal_representation) |
| 144 | + |
| 145 | + def validate(self, qid_shapes: Union[Tuple[int, ...], List[int]]) -> None: |
| 146 | + for i, (vals, shape) in enumerate(zip(self._internal_representation, qid_shapes)): |
| 147 | + if not all(0 <= v < shape for v in vals): |
| 148 | + message = ( |
| 149 | + f'Control values <{vals!r}> outside of range for control qubit ' |
| 150 | + f'number <{i}>.' |
| 151 | + ) |
| 152 | + raise ValueError(message) |
| 153 | + |
| 154 | + def _are_ones(self) -> bool: |
| 155 | + return frozenset(self._internal_representation) == {(1,)} |
| 156 | + |
| 157 | + def diagram_repr(self) -> str: |
| 158 | + if self._are_ones(): |
| 159 | + return 'C' * self._number_variables() |
| 160 | + |
| 161 | + def get_prefix(control_vals): |
| 162 | + control_vals_str = ''.join(map(str, sorted(control_vals))) |
| 163 | + return f'C{control_vals_str}' |
| 164 | + |
| 165 | + return ''.join(map(get_prefix, self._internal_representation)) |
| 166 | + |
| 167 | + def __getitem__( |
| 168 | + self, key: Union[int, slice] |
| 169 | + ) -> Union['AbstractControlValues', Tuple[int, ...]]: |
| 170 | + if isinstance(key, slice): |
| 171 | + return ProductOfSums(self._internal_representation[key]) |
| 172 | + return self._internal_representation[key] |
| 173 | + |
| 174 | + def _json_dict_(self) -> Dict[str, Any]: |
| 175 | + return {'_internal_representation': self._internal_representation} |
| 176 | + |
| 177 | + def __and__(self, other: AbstractControlValues) -> 'ProductOfSums': |
| 178 | + if not isinstance(other, ProductOfSums): |
| 179 | + raise TypeError( |
| 180 | + f'And operation not supported between types ProductOfSums and {type(other)}' |
| 181 | + ) |
| 182 | + return type(self)(self._internal_representation + other._internal_representation) |
0 commit comments