|
| 1 | +# Copyright 2021 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 | +"""Represents Boolean functions as a series of CNOT and rotation gates. The Boolean functions are |
| 15 | +passed as Sympy expressions and then turned into an optimized set of gates. |
| 16 | +
|
| 17 | +References: |
| 18 | +[1] On the representation of Boolean and real functions as Hamiltonians for quantum computing |
| 19 | + by Stuart Hadfield, https://arxiv.org/pdf/1804.09130.pdf |
| 20 | +[2] https://www.youtube.com/watch?v=AOKM9BkweVU is a useful intro |
| 21 | +[3] https://github.com/rsln-s/IEEE_QW_2020/blob/master/Slides.pdf |
| 22 | +""" |
| 23 | + |
| 24 | +from typing import cast, Any, Dict, Generator, List, Sequence, Tuple |
| 25 | + |
| 26 | +import sympy.parsing.sympy_parser as sympy_parser |
| 27 | + |
| 28 | +import cirq |
| 29 | +from cirq import value |
| 30 | +from cirq.ops import raw_types |
| 31 | +from cirq.ops.linear_combinations import PauliSum, PauliString |
| 32 | + |
| 33 | + |
| 34 | +@value.value_equality |
| 35 | +class BooleanHamiltonian(raw_types.Operation): |
| 36 | + """An operation that represents a Hamiltonian from a set of Boolean functions.""" |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, |
| 40 | + qubit_map: Dict[str, 'cirq.Qid'], |
| 41 | + boolean_strs: Sequence[str], |
| 42 | + theta: float, |
| 43 | + ): |
| 44 | + """Builds a BooleanHamiltonian. |
| 45 | +
|
| 46 | + For each element of a sequence of Boolean expressions, the code first transforms it into a |
| 47 | + polynomial of Pauli Zs that represent that particular expression. Then, we sum all the |
| 48 | + polynomials, thus making a function that goes from a series to Boolean inputs to an integer |
| 49 | + that is the number of Boolean expressions that are true. |
| 50 | +
|
| 51 | + For example, if we were using this gate for the unweighted max-cut problem that is typically |
| 52 | + used to demonstrate the QAOA algorithm, there would be one Boolean expression per edge. Each |
| 53 | + Boolean expression would be true iff the vertices on that are in different cuts (i.e. it's) |
| 54 | + an XOR. |
| 55 | +
|
| 56 | + Then, we compute exp(-j * theta * polynomial), which is unitary because the polynomial is |
| 57 | + Hermitian. |
| 58 | +
|
| 59 | + Args: |
| 60 | + boolean_strs: The list of Sympy-parsable Boolean expressions. |
| 61 | + qubit_map: map of string (boolean variable name) to qubit. |
| 62 | + theta: The evolution time (angle) for the Hamiltonian |
| 63 | + """ |
| 64 | + self._qubit_map: Dict[str, 'cirq.Qid'] = qubit_map |
| 65 | + self._boolean_strs: Sequence[str] = boolean_strs |
| 66 | + self._theta: float = theta |
| 67 | + |
| 68 | + def with_qubits(self, *new_qubits: 'cirq.Qid') -> 'BooleanHamiltonian': |
| 69 | + return BooleanHamiltonian( |
| 70 | + {cast(cirq.NamedQubit, q).name: q for q in new_qubits}, |
| 71 | + self._boolean_strs, |
| 72 | + self._theta, |
| 73 | + ) |
| 74 | + |
| 75 | + @property |
| 76 | + def qubits(self) -> Tuple[raw_types.Qid, ...]: |
| 77 | + return tuple(self._qubit_map.values()) |
| 78 | + |
| 79 | + def num_qubits(self) -> int: |
| 80 | + return len(self._qubit_map) |
| 81 | + |
| 82 | + def _value_equality_values_(self): |
| 83 | + return self._qubit_map, self._boolean_strs, self._theta |
| 84 | + |
| 85 | + def _json_dict_(self) -> Dict[str, Any]: |
| 86 | + return { |
| 87 | + 'cirq_type': self.__class__.__name__, |
| 88 | + 'qubit_map': self._qubit_map, |
| 89 | + 'boolean_strs': self._boolean_strs, |
| 90 | + 'theta': self._theta, |
| 91 | + } |
| 92 | + |
| 93 | + @classmethod |
| 94 | + def _from_json_dict_(cls, qubit_map, boolean_strs, theta, **kwargs): |
| 95 | + return cls(qubit_map, boolean_strs, theta) |
| 96 | + |
| 97 | + def _decompose_(self): |
| 98 | + boolean_exprs = [sympy_parser.parse_expr(boolean_str) for boolean_str in self._boolean_strs] |
| 99 | + hamiltonian_polynomial_list = [ |
| 100 | + PauliSum.from_boolean_expression(boolean_expr, self._qubit_map) |
| 101 | + for boolean_expr in boolean_exprs |
| 102 | + ] |
| 103 | + |
| 104 | + return _get_gates_from_hamiltonians( |
| 105 | + hamiltonian_polynomial_list, self._qubit_map, self._theta |
| 106 | + ) |
| 107 | + |
| 108 | + |
| 109 | +def _get_gates_from_hamiltonians( |
| 110 | + hamiltonian_polynomial_list: List['cirq.PauliSum'], |
| 111 | + qubit_map: Dict[str, 'cirq.Qid'], |
| 112 | + theta: float, |
| 113 | +) -> Generator['cirq.Operation', None, None]: |
| 114 | + """Builds a circuit according to [1]. |
| 115 | +
|
| 116 | + Args: |
| 117 | + hamiltonian_polynomial_list: the list of Hamiltonians, typically built by calling |
| 118 | + PauliSum.from_boolean_expression(). |
| 119 | + qubit_map: map of string (boolean variable name) to qubit. |
| 120 | + theta: A single float scaling the rotations. |
| 121 | + Yields: |
| 122 | + Gates that are the decomposition of the Hamiltonian. |
| 123 | + """ |
| 124 | + combined = sum(hamiltonian_polynomial_list, PauliSum.from_pauli_strings(PauliString({}))) |
| 125 | + |
| 126 | + qubit_names = sorted(qubit_map.keys()) |
| 127 | + qubits = [qubit_map[name] for name in qubit_names] |
| 128 | + qubit_indices = {qubit: i for i, qubit in enumerate(qubits)} |
| 129 | + |
| 130 | + hamiltonians = {} |
| 131 | + for pauli_string in combined: |
| 132 | + w = pauli_string.coefficient.real |
| 133 | + qubit_idx = tuple(sorted(qubit_indices[qubit] for qubit in pauli_string.qubits)) |
| 134 | + hamiltonians[qubit_idx] = w |
| 135 | + |
| 136 | + def _apply_cnots(prevh: Tuple[int, ...], currh: Tuple[int, ...]): |
| 137 | + cnots: List[Tuple[int, int]] = [] |
| 138 | + |
| 139 | + cnots.extend((prevh[i], prevh[-1]) for i in range(len(prevh) - 1)) |
| 140 | + cnots.extend((currh[i], currh[-1]) for i in range(len(currh) - 1)) |
| 141 | + |
| 142 | + # TODO(tonybruguier): At this point, some CNOT gates can be cancelled out according to: |
| 143 | + # "Efficient quantum circuits for diagonal unitaries without ancillas" by Jonathan Welch, |
| 144 | + # Daniel Greenbaum, Sarah Mostame, Alán Aspuru-Guzik |
| 145 | + # https://arxiv.org/abs/1306.3991 |
| 146 | + |
| 147 | + for gate in (cirq.CNOT(qubits[c], qubits[t]) for c, t in cnots): |
| 148 | + yield gate |
| 149 | + |
| 150 | + previous_h: Tuple[int, ...] = () |
| 151 | + for h, w in hamiltonians.items(): |
| 152 | + yield _apply_cnots(previous_h, h) |
| 153 | + |
| 154 | + if len(h) >= 1: |
| 155 | + yield cirq.Rz(rads=(theta * w)).on(qubits[h[-1]]) |
| 156 | + |
| 157 | + previous_h = h |
| 158 | + |
| 159 | + # Flush the last CNOTs. |
| 160 | + yield _apply_cnots(previous_h, ()) |
0 commit comments