Coverage for src/hypra/expansion_library.py: 84.31%
80 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 22:12 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 22:12 +0000
1"""Persistent native expansions indexed by integer hypergeometric bases."""
3from __future__ import annotations
5import json
6import sqlite3
7from collections.abc import Iterable
8from contextlib import closing
9from pathlib import Path
10from typing import cast
12import sympy as s
14from .errors import IncompleteExpansionError, UnsupportedExpressionError
15from .serialization import decode_expr, encode_expr
18def _partition(bases: Iterable[int | s.Integer]) -> tuple[int, ...]:
19 values = tuple(bases)
20 if any(type(value) is not int and not isinstance(value, s.Integer) for value in values): 20 ↛ 21line 20 didn't jump to line 21 because the condition on line 20 was never true
21 raise TypeError("Expansion library bases must be exact integers")
22 return tuple(sorted(map(int, values)))
25def _family(upper, lower):
26 a, b = _partition(upper), _partition(lower)
27 if len(a) != len(b) + 1: 27 ↛ 28line 27 didn't jump to line 28 because the condition on line 27 was never true
28 raise ValueError("Expansion library requires p upper and p-1 lower bases")
29 return a, b
32def _check_order(through: int) -> None:
33 if type(through) is not int or through < 0: 33 ↛ 34line 33 didn't jump to line 34 because the condition on line 33 was never true
34 raise ValueError("Expansion library order must be a nonnegative integer")
37def _template_symbols(a, b):
38 return (
39 s.Symbol("libraryArgument", positive=True),
40 s.Symbol("libraryEpsilon"),
41 tuple(s.Symbol(f"libraryUpper{i}") for i in range(len(a))),
42 tuple(
43 s.Symbol(f"libraryLower{i}", nonzero=True)
44 if base <= 0
45 else s.Symbol(f"libraryLower{i}")
46 for i, base in enumerate(b)
47 ),
48 )
51class ExpansionLibrary:
52 """An on-disk library of exact symbolic regulator expansions.
54 Upper and lower bases are sorted separately. Each entry records the largest
55 inclusive order registered for the family, with independent symbolic slopes.
56 Pass the same SQLite file to NativeConfig(expansion_library=...) to reuse it.
57 """
59 def __init__(self, path: str | Path) -> None:
60 self.path = Path(path).expanduser()
62 def _entry(self, key: str, through: int, *, polynomial: bool = False):
63 if not self.path.exists():
64 return None
65 fields = "polynomial" if polynomial else "1"
66 with closing(sqlite3.connect(self.path.resolve().as_uri() + "?mode=ro", uri=True)) as db:
67 if ( 67 ↛ 73line 67 didn't jump to line 73 because the condition on line 67 was never true
68 db.execute(
69 "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'expansions'"
70 ).fetchone()
71 is None
72 ):
73 return None
74 return db.execute(
75 f"SELECT {fields} FROM expansions WHERE family = ? AND known_order >= ?",
76 (key, through),
77 ).fetchone()
79 def is_known_to_order(
80 self,
81 upper: Iterable[int | s.Integer],
82 lower: Iterable[int | s.Integer],
83 through: int,
84 ) -> bool:
85 """Return whether this family is registered through the requested order."""
86 _check_order(through)
87 return self._entry(json.dumps(_family(upper, lower)), through) is not None
89 def add_to_lib(
90 self,
91 upper: Iterable[int | s.Integer],
92 lower: Iterable[int | s.Integer],
93 through: int,
94 ) -> None:
95 """Compute and persist a family's expansion if the requested order is new."""
96 from .api import expand_epsilon
97 from .native import NativeConfig
99 _check_order(through)
100 a, b = _family(upper, lower)
101 key = json.dumps((a, b))
102 if self._entry(key, through) is not None: 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true
103 return
104 if any(abs(base) >= 10 for base in (*a, *b)): 104 ↛ 105line 104 didn't jump to line 105 because the condition on line 104 was never true
105 raise ValueError("Expansion library requires absolute base values below ten")
106 z, epsilon, upper_slopes, lower_slopes = _template_symbols(a, b)
107 h = s.hyper(
108 [base + slope * epsilon for base, slope in zip(a, upper_slopes, strict=True)],
109 [base + slope * epsilon for base, slope in zip(b, lower_slopes, strict=True)],
110 z,
111 evaluate=False,
112 )
113 expansion = expand_epsilon(h, epsilon, through, z < 1, config=NativeConfig(use_cache=False))
114 payload = json.dumps(encode_expr(expansion.polynomial))
115 self.path.parent.mkdir(parents=True, exist_ok=True)
116 with closing(sqlite3.connect(self.path)) as db, db:
117 db.execute(
118 """CREATE TABLE IF NOT EXISTS expansions (
119 family TEXT PRIMARY KEY, known_order INTEGER NOT NULL, polynomial TEXT NOT NULL
120 )"""
121 )
122 db.execute(
123 """INSERT INTO expansions VALUES (?, ?, ?)
124 ON CONFLICT(family) DO UPDATE SET
125 known_order = excluded.known_order, polynomial = excluded.polynomial
126 WHERE excluded.known_order > expansions.known_order""",
127 (key, through, payload),
128 )
130 def _lookup_atom(self, h: s.hyper, epsilon: s.Symbol, through: int) -> s.Expr | None:
131 from .native.planning import _affine_rational, laurent_coefficient
133 # Templates are an optional optimization. Requests outside their domain
134 # must still reach the native dispatcher, which also handles elementary
135 # regulator-independent functions with other rational bases.
136 if len(h.ap) != len(h.bq) + 1: 136 ↛ 137line 136 didn't jump to line 137 because the condition on line 136 was never true
137 return None
138 try:
139 upper = sorted((_affine_rational(p, epsilon) for p in h.ap), key=lambda pair: pair[0])
140 lower = sorted((_affine_rational(p, epsilon) for p in h.bq), key=lambda pair: pair[0])
141 except UnsupportedExpressionError:
142 return None
143 if any(not base.is_Integer for base, _ in (*upper, *lower)):
144 return None
145 a, b = _family((base for base, _ in upper), (base for base, _ in lower))
146 row = self._entry(json.dumps((a, b)), through, polynomial=True)
147 if row is None:
148 return None
149 stored = decode_expr(json.loads(row[0]))
150 if not isinstance(stored, s.Expr) or stored.has(s.hyper): 150 ↛ 151line 150 didn't jump to line 151 because the condition on line 150 was never true
151 raise IncompleteExpansionError("Invalid stored hypergeometric expansion")
152 z, regulator, upper_slopes, lower_slopes = _template_symbols(a, b)
153 poles = sum(base <= 0 for base in b)
154 polynomial = s.Add(
155 *(
156 laurent_coefficient(stored, regulator, power) * regulator**power
157 for power in range(-poles, through + 1)
158 )
159 )
160 replacements = dict(
161 zip(upper_slopes + lower_slopes, (slope for _, slope in (*upper, *lower)), strict=True)
162 )
163 return cast(s.Expr, polynomial.xreplace(replacements | {z: h.argument, regulator: epsilon}))