|
| 1 | +# Copyright 2024 Google LLC |
| 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 | +from typing import Any, Sequence, Set, Tuple |
| 15 | + |
| 16 | +from attrs import field, frozen |
| 17 | + |
| 18 | +from qualtran import Bloq, Signature |
| 19 | +from qualtran.resource_counting import BloqCountT, CostKey, SympySymbolAllocator |
| 20 | + |
| 21 | + |
| 22 | +def _convert_callees(callees: Sequence[BloqCountT]) -> Tuple[BloqCountT, ...]: |
| 23 | + # Convert to tuples in a type-checked way. |
| 24 | + return tuple(callees) |
| 25 | + |
| 26 | + |
| 27 | +@frozen |
| 28 | +class CostingBloq(Bloq): |
| 29 | + """A bloq that lets you set the costs via attributes.""" |
| 30 | + |
| 31 | + name: str |
| 32 | + num_qubits: int |
| 33 | + callees: Sequence[BloqCountT] = field(converter=_convert_callees, factory=tuple) |
| 34 | + static_costs: Sequence[Tuple[CostKey, Any]] = field(converter=tuple, factory=tuple) |
| 35 | + |
| 36 | + @property |
| 37 | + def signature(self) -> 'Signature': |
| 38 | + return Signature.build(register=self.num_qubits) |
| 39 | + |
| 40 | + def build_call_graph(self, ssa: 'SympySymbolAllocator') -> Set['BloqCountT']: |
| 41 | + return set(self.callees) |
| 42 | + |
| 43 | + def my_static_costs(self, cost_key: 'CostKey'): |
| 44 | + return dict(self.static_costs).get(cost_key, NotImplemented) |
| 45 | + |
| 46 | + def pretty_name(self): |
| 47 | + return self.name |
| 48 | + |
| 49 | + def __str__(self): |
| 50 | + return self.name |
| 51 | + |
| 52 | + |
| 53 | +def make_example_costing_bloqs(): |
| 54 | + from qualtran.bloqs.basic_gates import Hadamard, TGate, Toffoli |
| 55 | + |
| 56 | + func1 = CostingBloq( |
| 57 | + 'Func1', num_qubits=10, callees=[(TGate(), 10), (TGate().adjoint(), 10), (Hadamard(), 10)] |
| 58 | + ) |
| 59 | + func2 = CostingBloq('Func2', num_qubits=3, callees=[(Toffoli(), 100)]) |
| 60 | + algo = CostingBloq('Algo', num_qubits=100, callees=[(func1, 1), (func2, 1)]) |
| 61 | + return algo |
0 commit comments