# Copyright Quantinuum## 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.fromtypingimportCallablefrompytket.circuitimportBit,Circuitfrompytket.unit_idimport_TEMP_BIT_NAMEfrom.._tket.passesimportBasePass,CustomPassMAX_C_REG_WIDTH=32def_is_scratch(bit:Bit)->bool:reg_name=bit.reg_namereturnbool(reg_name==_TEMP_BIT_NAME)orreg_name.startswith(f"{_TEMP_BIT_NAME}_")def_gen_scratch_transformation(max_size:int)->Callable[[Circuit],Circuit]:deft(circuit:Circuit)->Circuit:# Find all scratch bitsscratch_bits=list(filter(_is_scratch,circuit.bits))# If the total number of scratch bits exceeds the max width, rename themiflen(scratch_bits)>max_size:bits_map={}fori,bitinenumerate(scratch_bits):bits_map[bit]=Bit(f"{_TEMP_BIT_NAME}_{i//max_size}",i%max_size)circuit.rename_units(bits_map)# type: ignorereturncircuitreturnt
[docs]defscratch_reg_resize_pass(max_size:int=MAX_C_REG_WIDTH)->BasePass:"""Create a pass that breaks up the internal scratch bit registers into smaller registers. :param max_size: desired maximum size of scratch bit registers :return: a pass to break up the scratch registers """returnCustomPass(_gen_scratch_transformation(max_size),label="resize scratch bits")