Coverage for src/hypra/hpl/reduction.py: 87.50%

84 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-26 22:12 +0000

1"""Exact shuffle extraction of endpoint logarithms, without branch changes.""" 

2 

3from __future__ import annotations 

4 

5from functools import lru_cache 

6 

7import sympy as s 

8 

9from .._typing import IntegerWord 

10from ..errors import UnsupportedExpressionError 

11from ..symbolic import HPL, reduce_known_hpl 

12from .algebra import _word, shuffle_words 

13 

14 

15@lru_cache(maxsize=4096) 

16def _extract(word, z, leading, trailing): 

17 if not word: 17 ↛ 18line 17 didn't jump to line 18 because the condition on line 17 was never true

18 return s.S.One 

19 if len(set(word)) == 1: 

20 return HPL((word[0],), z) ** len(word) / s.factorial(len(word)) 

21 if trailing and word[-1] == 0: 

22 prefix = word[:-1] 

23 terms = shuffle_words(prefix, (0,)) 

24 count = terms.pop(word) 

25 return ( 

26 _extract(prefix, z, leading, trailing) * HPL((0,), z) 

27 - sum(n * _extract(w, z, leading, trailing) for w, n in terms.items()) 

28 ) / count 

29 if leading and word[0] == 1: 

30 tail = word[1:] 

31 terms = shuffle_words((1,), tail) 

32 count = terms.pop(word) 

33 return ( 

34 HPL((1,), z) * _extract(tail, z, leading, trailing) 

35 - sum(n * _extract(w, z, leading, trailing) for w, n in terms.items()) 

36 ) / count 

37 return HPL(word, z) 

38 

39 

40def extract_hpl_logs( 

41 expression: s.Expr, 

42 *, 

43 leading_ones: bool = True, 

44 trailing_zeros: bool = True, 

45) -> s.Expr: 

46 """Remove leading 1 / trailing 0 letters by exact shuffle identities. 

47 

48 Products of log(z) and -log(1-z) remain explicit; other HPL words retain 

49 their original arguments. No complex branch or endpoint limit is chosen. 

50 Plus/minus notation is expanded into ordinary HPL letters first. 

51 This is not a minimal-basis reduction or an endpoint evaluator. 

52 

53 Args: 

54 expression: Exact expression containing HPL atoms. 

55 leading_ones: Extract factors of H_1. 

56 trailing_zeros: Extract factors of H_0. 

57 """ 

58 if not isinstance(expression, s.Expr): 

59 raise TypeError("expression must be a SymPy expression") 

60 if type(leading_ones) is not bool or type(trailing_zeros) is not bool: 60 ↛ 61line 60 didn't jump to line 61 because the condition on line 60 was never true

61 raise TypeError("Log extraction flags must be booleans") 

62 if expression.has(s.Float, s.nan, s.zoo, s.oo, -s.oo): 62 ↛ 63line 62 didn't jump to line 63 because the condition on line 62 was never true

63 raise UnsupportedExpressionError("Log extraction requires exact finite input") 

64 expression = expression.rewrite(HPL) 

65 replacements = {} 

66 for atom in expression.atoms(HPL): 

67 word = _word(atom.word) 

68 replacements[atom] = _extract(word, atom.argument, leading_ones, trailing_zeros) 

69 return reduce_known_hpl(s.expand(expression.xreplace(replacements))) 

70 

71 

72def lyndon_factors(word: IntegerWord) -> tuple[tuple[int, ...], ...]: 

73 """Chen--Fox--Lyndon factorization, with alphabet order -1 < 0 < 1. 

74 

75 Args: 

76 word: Expanded ternary word. 

77 

78 Returns: 

79 Lyndon words in nonincreasing lexicographic order. 

80 """ 

81 word = _word(word) 

82 factors, i = [], 0 

83 while i < len(word): 

84 j, k = i + 1, i 

85 while j < len(word) and word[k] <= word[j]: 

86 k = i if word[k] < word[j] else k + 1 

87 j += 1 

88 length = j - k 

89 while i <= k: 

90 factors.append(word[i : i + length]) 

91 i += length 

92 return tuple(factors) 

93 

94 

95@lru_cache(maxsize=4096) 

96def _lyndon(word, z): 

97 if not word: 97 ↛ 98line 97 didn't jump to line 98 because the condition on line 97 was never true

98 return s.S.One 

99 factors = lyndon_factors(word) 

100 if len(factors) == 1: 

101 return HPL(word, z) 

102 counts = {(): 1} 

103 for factor in factors: 

104 merged = {} 

105 for left, multiplicity in counts.items(): 

106 for right, coefficient in shuffle_words(left, factor).items(): 

107 merged[right] = merged.get(right, 0) + multiplicity * coefficient 

108 counts = merged 

109 if len(counts) > 16384: 109 ↛ 110line 109 didn't jump to line 110 because the condition on line 109 was never true

110 raise UnsupportedExpressionError("Lyndon reduction exceeds the word budget") 

111 diagonal = counts.pop(word) 

112 if any(other >= word for other in counts): 112 ↛ 113line 112 didn't jump to line 113 because the condition on line 112 was never true

113 raise UnsupportedExpressionError("Lyndon shuffle triangularity check failed") 

114 product = s.prod(HPL(factor, z) for factor in factors) 

115 return s.expand( 

116 (product - sum(count * _lyndon(other, z) for other, count in counts.items())) / diagonal 

117 ) 

118 

119 

120def lyndon_reduce(expression: s.Expr) -> s.Expr: 

121 """Reduce HPL words to a shuffle-algebra Lyndon basis through weight eight. 

122 

123 This uses exact triangular shuffle factorization, not precomputed tables. 

124 It is a shuffle basis only, not a claim of algebraic independence after 

125 argument transformations or evaluation at special points. 

126 

127 Args: 

128 expression: Exact expression containing HPL atoms. 

129 """ 

130 if not isinstance(expression, s.Expr): 130 ↛ 131line 130 didn't jump to line 131 because the condition on line 130 was never true

131 raise TypeError("expression must be a SymPy expression") 

132 if expression.has(s.Float, s.nan, s.zoo, s.oo, -s.oo): 132 ↛ 133line 132 didn't jump to line 133 because the condition on line 132 was never true

133 raise UnsupportedExpressionError("Lyndon reduction requires exact finite input") 

134 expression = expression.rewrite(HPL) 

135 replacements = {} 

136 for atom in expression.atoms(HPL): 

137 word = _word(atom.word) 

138 if len(word) > 8: 

139 raise UnsupportedExpressionError( 

140 "Lyndon reduction currently supports weight at most eight" 

141 ) 

142 replacements[atom] = _lyndon(word, atom.argument) 

143 return s.expand(expression.xreplace(replacements))