Coverage for deeponnxcustom/tools/math_helper.py: 100%

21 statements  

« prev     ^ index     » next       coverage.py v6.4.1, created at 2022-06-06 02:28 +0200

1""" 

2@file 

3@brief Mathemical functions. 

4""" 

5 

6 

7def decompose_permutation(perm): 

8 """ 

9 Decomposes a permutation into transitions. 

10 

11 :param perm: permutation (integers) 

12 :return: list of tuples 

13 

14 .. note:: 

15 The function does not check *perm* is a permutation. 

16 If the input value is wrong, the execution could 

17 end up in an infinite loop. 

18 

19 .. runpython:: 

20 :showcode: 

21 

22 import pprint 

23 from deeponnxcustom.tools.math_helper import decompose_permutation 

24 

25 pprint.pprint(decompose_permutation((1, 0))) 

26 pprint.pprint(decompose_permutation((2, 0, 1))) 

27 pprint.pprint(decompose_permutation((1, 4, 2, 3, 0))) 

28 

29 Function @see fn apply_transitions applies this series 

30 of transitions. 

31 """ 

32 perm = list(perm) 

33 transitions = [] 

34 while True: 

35 index = -1 

36 for i, p in enumerate(perm): 

37 if p != i: 

38 index = i 

39 break 

40 if index == -1: 

41 break 

42 while perm[index] != index: 

43 a, b = index, perm[index] 

44 transitions.append((b, a)) 

45 perm[a], perm[b] = perm[b], perm[a] 

46 index = b 

47 

48 return list(reversed(transitions)) 

49 

50 

51def apply_transitions(n, transitions): 

52 """ 

53 Applies a list of transitions (permutations of two elements) 

54 on the first *n* integers. 

55 

56 :param n: number of elements in the permutation 

57 :param transitions: list of transitions 

58 :return: permuted ensemble 

59 """ 

60 ens = list(range(n)) 

61 for a, b in transitions: 

62 ens[a], ens[b] = ens[b], ens[a] 

63 return ens