|
| 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 |
| 16 | +from dataclasses import dataclass |
| 17 | + |
| 18 | +import itertools |
| 19 | + |
| 20 | +if TYPE_CHECKING: |
| 21 | + import cirq |
| 22 | + |
| 23 | + |
| 24 | +@dataclass(frozen=True, eq=False) # type: ignore |
| 25 | +class AbstractControlValues(abc.ABC): |
| 26 | + """AbstractControlValues is an abstract immutable data class. |
| 27 | +
|
| 28 | + AbstractControlValues defines an API for control values and implements |
| 29 | + functions common to all implementations (e.g. comparison). |
| 30 | + """ |
| 31 | + |
| 32 | + _internal_representation: Any |
| 33 | + |
| 34 | + def __and__(self, other: 'AbstractControlValues') -> 'AbstractControlValues': |
| 35 | + """Sets self to be the cartesian product of all combinations in self x other. |
| 36 | +
|
| 37 | + Args: |
| 38 | + other: An object that implements AbstractControlValues. |
| 39 | +
|
| 40 | + Returns: |
| 41 | + An object that represents the cartesian product of the two inputs. |
| 42 | + """ |
| 43 | + return type(self)(self._internal_representation + other._internal_representation) |
| 44 | + |
| 45 | + def _iterator(self): |
| 46 | + return self._expand() |
| 47 | + |
| 48 | + @abc.abstractmethod |
| 49 | + def _expand(self): |
| 50 | + """Returns the control values tracked by the object.""" |
| 51 | + |
| 52 | + @abc.abstractmethod |
| 53 | + def diagram_repr(self) -> str: |
| 54 | + """Returns a string representation to be used in circuit diagrams.""" |
| 55 | + |
| 56 | + @abc.abstractmethod |
| 57 | + def _number_variables(self): |
| 58 | + """Returns the control values tracked by the object.""" |
| 59 | + |
| 60 | + @abc.abstractmethod |
| 61 | + def __len__(self): |
| 62 | + pass |
| 63 | + |
| 64 | + @abc.abstractmethod |
| 65 | + def identifier(self) -> Tuple[Any]: |
| 66 | + """Returns an identifier from which the object can be rebuilt.""" |
| 67 | + |
| 68 | + @abc.abstractmethod |
| 69 | + def __hash__(self): |
| 70 | + pass |
| 71 | + |
| 72 | + @abc.abstractmethod |
| 73 | + def __repr__(self) -> str: |
| 74 | + pass |
| 75 | + |
| 76 | + @abc.abstractmethod |
| 77 | + def _validate(self, qid_shapes: Union[Tuple[int, ...], List[int]]) -> None: |
| 78 | + """Validates control values |
| 79 | +
|
| 80 | + Validate that control values are in the half closed interval |
| 81 | + [0, qid_shapes) for each qubit. |
| 82 | + """ |
| 83 | + |
| 84 | + @abc.abstractmethod |
| 85 | + def _are_ones(self) -> bool: |
| 86 | + """Checks whether all control values are equal to 1.""" |
| 87 | + |
| 88 | + @abc.abstractmethod |
| 89 | + def _json_dict_(self) -> Dict[str, Any]: |
| 90 | + pass |
| 91 | + |
| 92 | + @abc.abstractmethod |
| 93 | + def __getitem__(self, key): |
| 94 | + pass |
| 95 | + |
| 96 | + def __iter__(self): |
| 97 | + for assignment in self._iterator(): |
| 98 | + yield assignment |
| 99 | + |
| 100 | + def __eq__(self, other): |
| 101 | + """Returns True iff self and other represent the same configurations. |
| 102 | +
|
| 103 | + Args: |
| 104 | + other: A AbstractControlValues object. |
| 105 | +
|
| 106 | + Returns: |
| 107 | + boolean whether the two objects are equivalent or not. |
| 108 | + """ |
| 109 | + if not isinstance(other, AbstractControlValues): |
| 110 | + other = ProductOfSums(other) |
| 111 | + return sorted(v for v in self) == sorted(v for v in other) |
| 112 | + |
| 113 | + |
| 114 | +@AbstractControlValues.register |
| 115 | +class ProductOfSums(AbstractControlValues): |
| 116 | + """ProductOfSums represents control values in a form of a cartesian product of tuples.""" |
| 117 | + |
| 118 | + _internal_representation: Tuple[Tuple[int, ...]] |
| 119 | + |
| 120 | + def identifier(self): |
| 121 | + return self._internal_representation |
| 122 | + |
| 123 | + def _expand(self): |
| 124 | + """Returns the combinations tracked by the object.""" |
| 125 | + return itertools.product(*self._internal_representation) |
| 126 | + |
| 127 | + def __repr__(self): |
| 128 | + return f'cirq.ProductOfSums({str(self.identifier())})' |
| 129 | + |
| 130 | + def _number_variables(self) -> int: |
| 131 | + return len(self._internal_representation) |
| 132 | + |
| 133 | + def __len__(self): |
| 134 | + return self._number_variables() |
| 135 | + |
| 136 | + def __hash__(self): |
| 137 | + return hash(self._internal_representation) |
| 138 | + |
| 139 | + def _validate(self, qid_shapes: Union[Tuple[int, ...], List[int]]) -> None: |
| 140 | + for i, (vals, shape) in enumerate(zip(self._internal_representation, qid_shapes)): |
| 141 | + if not all(0 <= v < shape for v in vals): |
| 142 | + message = ( |
| 143 | + f'Control values <{vals!r}> outside of range for control qubit ' |
| 144 | + f'number <{i}>.' |
| 145 | + ) |
| 146 | + raise ValueError(message) |
| 147 | + |
| 148 | + def _are_ones(self) -> bool: |
| 149 | + return frozenset(self._internal_representation) == {(1,)} |
| 150 | + |
| 151 | + def diagram_repr(self) -> str: |
| 152 | + if self._are_ones(): |
| 153 | + return 'C' * self._number_variables() |
| 154 | + |
| 155 | + def get_prefix(control_vals): |
| 156 | + control_vals_str = ''.join(map(str, sorted(control_vals))) |
| 157 | + return f'C{control_vals_str}' |
| 158 | + |
| 159 | + return ''.join(map(get_prefix, self._internal_representation)) |
| 160 | + |
| 161 | + def __getitem__(self, key): |
| 162 | + if isinstance(key, slice): |
| 163 | + return ProductOfSums(self._internal_representation[key]) |
| 164 | + return self._internal_representation[key] |
| 165 | + |
| 166 | + def _json_dict_(self) -> Dict[str, Any]: |
| 167 | + return { |
| 168 | + '_internal_representation': self._internal_representation, |
| 169 | + 'cirq_type': 'ProductOfSums', |
| 170 | + } |
0 commit comments