# Copyright 2019-2024 Cambridge Quantum Computing## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.fromcollections.abcimportCallablefrompytket.circuitimportCircuitfrom.._tket.passesimportBasePass
[docs]classPassSelector:""" Collection of pytket compilation passes which are all applied to the same circuit. The result of the compilation is the best circuit as selected by a given metric. """
[docs]def__init__(self,passlist:list[BasePass],score_func:Callable[[Circuit],int],):""" Constructs a PassSelector :param passlist: list of pytket compilation passes :param score_func: function to score the results of the compilation (lower scores are preferred) """self._passlist=passlistself._score_func=score_funciflen(self._passlist)<1:raiseValueError("passlist needs to contain at least one pass")
[docs]defapply(self,circ:Circuit)->Circuit:""" Compiles the given circuit with the best of the given passes. :param circ: Circuit that should be compiled :return: compiled circuit """circ_list=[circ.copy()for_inself._passlist]self._scores:list[int|None]=[]forp,cinzip(self._passlist,circ_list):try:p.apply(c)self._scores.append(self._score_func(c))except:# noqa: E722# in case of any error the pass should be ignoredself._scores.append(None)try:returncirc_list[self._scores.index(min(xforxinself._scoresifxisnotNone))]exceptValueError:raiseRuntimeError("No passes have successfully run on this circuit")
[docs]defget_scores(self)->list[int|None]:""" :return: scores of the circuit after compiling for each of the compilations passes """returnself._scores