Coverage for src/hypra/hpl/notation.py: 82.35%

102 statements  

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

1"""Exact HPL index and plus/minus kernel notation conversions.""" 

2 

3from itertools import product 

4from typing import Literal, Self, cast 

5 

6import sympy as s 

7from sympy.core.function import ArgumentIndexError 

8from sympy.core.symbol import Str 

9 

10from .._typing import IntegerWord, as_integer_tuple 

11from ..errors import UnsupportedExpressionError 

12from ..symbolic import HPL 

13from .algebra import _word 

14 

15type PMLetter = Literal[0, "plus", "minus"] 

16type PMWord = tuple[PMLetter, ...] | list[PMLetter] | s.Tuple 

17_PM_LETTERS: dict[int, PMLetter] = {-1: "minus", 0: 0, 1: "plus"} 

18 

19 

20def _pm_indices(word: PMWord) -> tuple[int, ...]: 

21 if not isinstance(word, (tuple, list, s.Tuple)): 21 ↛ 22line 21 didn't jump to line 22 because the condition on line 21 was never true

22 raise TypeError("Plus/minus word must be a sequence") 

23 indices = [] 

24 for letter in word: 

25 if isinstance(letter, Str): 

26 letter = str(letter) 

27 if (type(letter) is int or isinstance(letter, s.Integer)) and letter == 0: 

28 indices.append(0) 

29 elif letter == "plus": 

30 indices.append(1) 

31 elif letter == "minus": 

32 indices.append(-1) 

33 else: 

34 raise ValueError("Use zero, 'plus', or 'minus' as kernel letters") 

35 return tuple(indices) 

36 

37 

38class HPLPM(s.Function): 

39 """An HPL whose word retains the plus/minus kernel notation.""" 

40 

41 nargs = 2 

42 

43 def _eval_is_commutative(self): 

44 return self.argument.is_commutative 

45 

46 def __new__(cls, word: PMWord, argument: s.Expr, **options: object) -> Self: 

47 letters = _pm_indices(word) 

48 encoded = s.Tuple(*(Str(str(_PM_LETTERS[i])) if i else s.S.Zero for i in letters)) 

49 return cast(Self, super().__new__(cls, encoded, argument, **options)) 

50 

51 @classmethod 

52 def from_indices(cls, indices: tuple[int, ...], argument: s.Expr) -> Self: 

53 """Construct from indices -1, 0, 1 representing minus, zero, plus.""" 

54 return cls(tuple(_PM_LETTERS[index] for index in indices), argument) 

55 

56 @property 

57 def word(self) -> s.Tuple: 

58 return cast(s.Tuple, self.args[0]) 

59 

60 @property 

61 def argument(self) -> s.Expr: 

62 return cast(s.Expr, self.args[1]) 

63 

64 def _eval_rewrite_as_HPL(self, word, argument, **hints): 

65 return hpl_pm(word, argument) 

66 

67 def _eval_evalf(self, prec): 

68 if self.argument == s.I and len(self.word) <= 6: 

69 from sympy.core.evalf import prec_to_dps 

70 

71 from .special import _pm_at_i_raw 

72 

73 # Exact reduction retains a small HPLPM basis at i. Evaluate its 

74 # convergent raw representation directly, without invoking that 

75 # reducer again and recursing back to the same basis atom. 

76 return _pm_at_i_raw(_pm_indices(self.word)).evalf(prec_to_dps(prec) + 10) 

77 return self.rewrite(HPL)._eval_evalf(prec) 

78 

79 def _eval_nseries(self, x, n, logx, cdir=0): 

80 # The word is discrete notation, not a differentiable Function 

81 # argument. Reuse the ordinary-letter germ and its remainder checks. 

82 return self.rewrite(HPL)._eval_nseries(x, n, logx, cdir=cdir) 

83 

84 def _eval_derivative(self, s): 

85 return self.fdiff() * self.argument.diff(s) 

86 

87 def fdiff(self, argindex=2): 

88 if argindex != 2: 

89 raise ArgumentIndexError(self, argindex) 

90 indices = _pm_indices(self.word) 

91 if not indices: 

92 return s.S.Zero 

93 z = self.argument 

94 first, *rest = indices 

95 kernel = {-1: 2 * z / (1 - z**2), 0: 1 / z, 1: 2 / (1 - z**2)}[first] 

96 return kernel * (self.from_indices(tuple(rest), z) if rest else s.S.One) 

97 

98 

99def expand_indices(indices: IntegerWord) -> tuple[int, ...]: 

100 """Expand signed compressed indices. 

101 

102 Args: 

103 indices: Each nonzero index becomes `abs(index) - 1` zero letters 

104 followed by its sign. A standalone zero stays a zero. 

105 

106 Returns: 

107 Expanded letters in their original order. 

108 """ 

109 if not isinstance(indices, (tuple, list, s.Tuple)) or any( 109 ↛ 112line 109 didn't jump to line 112 because the condition on line 109 was never true

110 isinstance(n, bool) or not isinstance(n, (int, s.Integer)) for n in indices 

111 ): 

112 raise TypeError("Compressed indices must be exact integers") 

113 indices = as_integer_tuple(indices) 

114 if sum(max(1, abs(n)) for n in indices) > 24: 114 ↛ 115line 114 didn't jump to line 115 because the condition on line 114 was never true

115 raise UnsupportedExpressionError("Index conversion weight exceeds24") 

116 return tuple( 

117 letter 

118 for n in indices 

119 for letter in ((0,) if n == 0 else (0,) * (abs(n) - 1) + (int(s.sign(n)),)) 

120 ) 

121 

122 

123def compress_indices(word: IntegerWord) -> tuple[int, ...]: 

124 """Compress an expanded word into signed indices. 

125 

126 Args: 

127 word: Expanded letters. Zero runs attach to the next nonzero letter. 

128 

129 Returns: 

130 Compressed indices with any final zero letters retained. 

131 """ 

132 word = _word(word) 

133 result, zeros = [], 0 

134 for letter in word: 

135 if letter == 0: 

136 zeros += 1 

137 else: 

138 result.append(letter * (zeros + 1)) 

139 zeros = 0 

140 return tuple(result) + (0,) * zeros 

141 

142 

143def _linear_choices(choices): 

144 choices = tuple(choices) 

145 if len(choices) > 12: 145 ↛ 146line 145 didn't jump to line 146 because the condition on line 145 was never true

146 raise UnsupportedExpressionError("Plus/minus conversion weight exceeds12") 

147 result = {} 

148 for terms in product(*choices): 

149 word = tuple(letter for letter, _ in terms) 

150 result[word] = s.prod(coefficient for _, coefficient in terms) 

151 return result 

152 

153 

154def pm_to_letters(word: PMWord) -> dict[tuple[int, ...], s.Expr]: 

155 """Expand the kernels `f_plus=f_1+f_-1` and `f_minus=f_1-f_-1`. 

156 

157 Args: 

158 word: Sequence containing zero, `"plus"`, or `"minus"`. 

159 

160 Returns: 

161 Coefficients indexed by expanded HPL words. 

162 """ 

163 return _linear_choices( 

164 ((0, s.S.One),) if not letter else ((1, s.S.One), (-1, s.Integer(letter))) 

165 for letter in _pm_indices(word) 

166 ) 

167 

168 

169def letters_to_pm(word: IntegerWord) -> dict[tuple[PMLetter, ...], s.Expr]: 

170 """Expand the kernels `f_±1=(f_plus ± f_minus)/2`. 

171 

172 Args: 

173 word: Expanded HPL letters. 

174 

175 Returns: 

176 Coefficients indexed by plus/minus words. 

177 """ 

178 choices = [] 

179 for letter in _word(word): 

180 choices.append( 

181 ((0, s.S.One),) 

182 if letter == 0 

183 else (("plus", s.S.Half), ("minus", s.Rational(letter, 2))) 

184 ) 

185 return _linear_choices(choices) 

186 

187 

188def hpl_pm(word: PMWord, argument: s.Expr) -> s.Expr: 

189 """Construct plus/minus notation as an exact sum of ordinary HPL objects. 

190 

191 Args: 

192 word: Sequence containing zero, `"plus"`, or `"minus"`. 

193 argument: SymPy argument of each HPL in the sum. 

194 """ 

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

196 raise TypeError("Argument must be a SymPy expression") 

197 return sum( 

198 ( 

199 coefficient * (HPL(letters, argument) if letters else s.S.One) 

200 for letters, coefficient in pm_to_letters(word).items() 

201 ), 

202 s.S.Zero, 

203 )