Coverage for /home/runner/work/tket/tket/pytket/pytket/passes/resizeregpass.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-04-17 10:53 +0000

1# Copyright Quantinuum 

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# http://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 

15from typing import Callable 

16 

17from pytket.circuit import Bit, Circuit 

18from pytket.unit_id import _TEMP_BIT_NAME 

19 

20from .._tket.passes import BasePass, CustomPass 

21 

22MAX_C_REG_WIDTH = 32 

23 

24 

25def _is_scratch(bit: Bit) -> bool: 

26 reg_name = bit.reg_name 

27 return bool(reg_name == _TEMP_BIT_NAME) or reg_name.startswith(f"{_TEMP_BIT_NAME}_") 

28 

29 

30def _gen_scratch_transformation(max_size: int) -> Callable[[Circuit], Circuit]: 

31 def t(circuit: Circuit) -> Circuit: 

32 # Find all scratch bits 

33 scratch_bits = list(filter(_is_scratch, circuit.bits)) 

34 # If the total number of scratch bits exceeds the max width, rename them 

35 if len(scratch_bits) > max_size: 

36 bits_map = {} 

37 for i, bit in enumerate(scratch_bits): 

38 bits_map[bit] = Bit(f"{_TEMP_BIT_NAME}_{i//max_size}", i % max_size) 

39 circuit.rename_units(bits_map) # type: ignore 

40 return circuit 

41 

42 return t 

43 

44 

45def scratch_reg_resize_pass(max_size: int = MAX_C_REG_WIDTH) -> BasePass: 

46 """Create a pass that breaks up the internal scratch bit registers into smaller 

47 registers. 

48 

49 :param max_size: desired maximum size of scratch bit registers 

50 :return: a pass to break up the scratch registers 

51 """ 

52 return CustomPass( 

53 _gen_scratch_transformation(max_size), label="resize scratch bits" 

54 )