tla-ts 0.0.4-dev.0be9567 → 0.0.4-dev.43f28be

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (311) hide show
  1. package/README.md +27 -141
  2. package/dist/deciders.cjs +366 -0
  3. package/dist/deciders.js +366 -0
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +35 -1
  6. package/dist/index.d.ts +35 -1
  7. package/dist/index.js +1 -1
  8. package/dist/parallel-worker.cjs +1 -4
  9. package/dist/parallel-worker.js +1 -4
  10. package/dist/prove-worker.cjs +9 -0
  11. package/dist/prove-worker.d.cts +9 -0
  12. package/dist/prove-worker.d.ts +9 -0
  13. package/dist/prove-worker.js +9 -0
  14. package/dist/prove.cjs +996 -0
  15. package/dist/prove.js +996 -0
  16. package/dist/run-cli.cjs +517 -47
  17. package/dist/run-cli.js +517 -47
  18. package/dist/tlapm.cjs +10 -0
  19. package/dist/tlapm.js +10 -0
  20. package/dist/transfer.cjs +38 -44
  21. package/dist/transfer.js +38 -44
  22. package/dist/worker.cjs +21 -0
  23. package/dist/worker.js +21 -0
  24. package/package.json +21 -12
  25. package/src/check.ts +1 -0
  26. package/src/errors.ts +86 -0
  27. package/src/evaluate.ts +54 -19
  28. package/src/index.ts +10 -0
  29. package/src/{obligation-action.ts → obligations/action.ts} +258 -37
  30. package/src/{obligation-anon.ts → obligations/anon.ts} +13 -7
  31. package/src/obligations/ctx.ts +64 -0
  32. package/src/{obligation-deref.ts → obligations/deref.ts} +2 -2
  33. package/src/{obligation-expression.ts → obligations/expression.ts} +54 -8
  34. package/src/{obligation-format.ts → obligations/format.ts} +6 -5
  35. package/src/{obligation-generate.ts → obligations/generate.ts} +134 -61
  36. package/src/{obligations.ts → obligations/index.ts} +28 -12
  37. package/src/{obligation-levels.ts → obligations/levels.ts} +12 -2
  38. package/src/{obligation-module.ts → obligations/module.ts} +46 -20
  39. package/src/obligations/pickle.ts +100 -0
  40. package/src/obligations/pragma.ts +189 -0
  41. package/src/{obligation-printer.ts → obligations/printer.ts} +9 -63
  42. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -1
  43. package/src/{obligation-source.ts → obligations/source.ts} +91 -35
  44. package/src/obligations/temporal.ts +319 -0
  45. package/src/{obligation-tuples.ts → obligations/tuples.ts} +1 -1
  46. package/src/ocaml-marshal.ts +166 -0
  47. package/src/parallel-worker.ts +2 -18
  48. package/src/parallel.ts +10 -43
  49. package/src/prove/decide-pool.ts +100 -0
  50. package/src/prove/deciders.ts +33 -0
  51. package/src/prove/isabelle/LICENSE +36 -0
  52. package/src/prove/isabelle/LICENSE-tlapm +26 -0
  53. package/src/prove/isabelle/decide.ts +47 -0
  54. package/src/prove/isabelle/encode.ts +508 -0
  55. package/src/prove/isabelle/isar/inner-syntax.ts +579 -0
  56. package/src/prove/isabelle/isar/method.ts +367 -0
  57. package/src/prove/isabelle/isar/proof.ts +28 -0
  58. package/src/prove/isabelle/isar/statement.ts +57 -0
  59. package/src/prove/isabelle/isar/theory.ts +192 -0
  60. package/src/prove/isabelle/isar/type-check.ts +278 -0
  61. package/src/prove/isabelle/provers/blast/blast.ts +258 -0
  62. package/src/prove/isabelle/provers/blast/branch.ts +322 -0
  63. package/src/prove/isabelle/provers/blast/prove.ts +347 -0
  64. package/src/prove/isabelle/provers/blast/rules.ts +330 -0
  65. package/src/prove/isabelle/provers/blast/state.ts +180 -0
  66. package/src/prove/isabelle/provers/blast/term.ts +547 -0
  67. package/src/prove/isabelle/provers/clasimp.ts +150 -0
  68. package/src/prove/isabelle/provers/classical.ts +389 -0
  69. package/src/prove/isabelle/provers/hypsubst.ts +441 -0
  70. package/src/prove/isabelle/pure/bicompose.ts +174 -0
  71. package/src/prove/isabelle/pure/consts.ts +32 -0
  72. package/src/prove/isabelle/pure/conv.ts +79 -0
  73. package/src/prove/isabelle/pure/drule.ts +264 -0
  74. package/src/prove/isabelle/pure/envir.ts +363 -0
  75. package/src/prove/isabelle/pure/goal.ts +53 -0
  76. package/src/prove/isabelle/pure/interrupt.ts +16 -0
  77. package/src/prove/isabelle/pure/list.ts +12 -0
  78. package/src/prove/isabelle/pure/logic.ts +402 -0
  79. package/src/prove/isabelle/pure/name.ts +110 -0
  80. package/src/prove/isabelle/pure/net.ts +262 -0
  81. package/src/prove/isabelle/pure/object-logic.ts +41 -0
  82. package/src/prove/isabelle/pure/pattern.ts +650 -0
  83. package/src/prove/isabelle/pure/raw-simplifier.ts +353 -0
  84. package/src/prove/isabelle/pure/rewriter.ts +602 -0
  85. package/src/prove/isabelle/pure/search.ts +68 -0
  86. package/src/prove/isabelle/pure/seq.ts +156 -0
  87. package/src/prove/isabelle/pure/simplifier.ts +112 -0
  88. package/src/prove/isabelle/pure/table.ts +208 -0
  89. package/src/prove/isabelle/pure/tactic.ts +276 -0
  90. package/src/prove/isabelle/pure/tactical.ts +347 -0
  91. package/src/prove/isabelle/pure/term-ord.ts +159 -0
  92. package/src/prove/isabelle/pure/term.ts +808 -0
  93. package/src/prove/isabelle/pure/thm.ts +806 -0
  94. package/src/prove/isabelle/pure/type.ts +133 -0
  95. package/src/prove/isabelle/pure/unify.ts +753 -0
  96. package/src/prove/isabelle/pure/variable.ts +25 -0
  97. package/src/prove/isabelle/tla/classical-setup.ts +101 -0
  98. package/src/prove/isabelle/tla/context.ts +74 -0
  99. package/src/prove/isabelle/tla/logic-data.ts +5 -0
  100. package/src/prove/isabelle/tla/logic.ts +215 -0
  101. package/src/prove/isabelle/tla/simpdata.ts +241 -0
  102. package/src/prove/isabelle/tools/intuitionistic.ts +132 -0
  103. package/src/prove/ocaml.ts +22 -0
  104. package/src/prove/prep/action.ts +520 -0
  105. package/src/prove/prep/defs.ts +33 -0
  106. package/src/prove/prep/elab.ts +156 -0
  107. package/src/prove/prep/enabled-axioms.ts +189 -0
  108. package/src/prove/prep/enabled.ts +43 -0
  109. package/src/prove/prep/fingerprint.ts +388 -0
  110. package/src/prove/prep/flatten.ts +70 -0
  111. package/src/prove/prep/level-comparison.ts +552 -0
  112. package/src/prove/prep/md5.ts +67 -0
  113. package/src/prove/prep/pragma.ts +221 -0
  114. package/src/prove/prep/trivial.ts +22 -0
  115. package/src/prove/prove-worker.ts +27 -0
  116. package/src/prove/prove.ts +518 -0
  117. package/src/prove/ptl/decide.ts +68 -0
  118. package/src/prove/ptl/encode.ts +256 -0
  119. package/src/prove/ptl/sat.ts +151 -0
  120. package/src/prove/ptl/tableau.ts +276 -0
  121. package/src/prove/smt/axiomatize.ts +69 -0
  122. package/src/prove/smt/axioms.ts +210 -0
  123. package/src/prove/smt/context.ts +108 -0
  124. package/src/prove/smt/data.ts +665 -0
  125. package/src/prove/smt/encode.ts +169 -0
  126. package/src/prove/smt/extensionality.ts +63 -0
  127. package/src/prove/smt/flatten.ts +127 -0
  128. package/src/prove/smt/format.ts +143 -0
  129. package/src/prove/smt/instances.ts +182 -0
  130. package/src/prove/smt/rewrite.ts +784 -0
  131. package/src/prove/smt/simplify.ts +57 -0
  132. package/src/prove/smt/solver/act-cache.ts +265 -0
  133. package/src/prove/smt/solver/arith-rewriter.ts +962 -0
  134. package/src/prove/smt/solver/array.ts +22 -0
  135. package/src/prove/smt/solver/asserted-formulas.ts +469 -0
  136. package/src/prove/smt/solver/ast-lt.ts +157 -0
  137. package/src/prove/smt/solver/ast-util.ts +147 -0
  138. package/src/prove/smt/solver/ast.ts +1315 -0
  139. package/src/prove/smt/solver/auf-solver.ts +572 -0
  140. package/src/prove/smt/solver/case-split-queue.ts +178 -0
  141. package/src/prove/smt/solver/cg-table.ts +175 -0
  142. package/src/prove/smt/solver/clause.ts +276 -0
  143. package/src/prove/smt/solver/conflict-resolution.ts +343 -0
  144. package/src/prove/smt/solver/context.ts +1292 -0
  145. package/src/prove/smt/solver/ctx-simplify.ts +334 -0
  146. package/src/prove/smt/solver/der.ts +224 -0
  147. package/src/prove/smt/solver/dyn-ack.ts +141 -0
  148. package/src/prove/smt/solver/e-matching.ts +659 -0
  149. package/src/prove/smt/solver/enode.ts +259 -0
  150. package/src/prove/smt/solver/expr-ref.ts +21 -0
  151. package/src/prove/smt/solver/expr-safe-replace.ts +172 -0
  152. package/src/prove/smt/solver/fingerprints.ts +92 -0
  153. package/src/prove/smt/solver/flat-literals.ts +51 -0
  154. package/src/prove/smt/solver/goal.ts +138 -0
  155. package/src/prove/smt/solver/hash.ts +173 -0
  156. package/src/prove/smt/solver/hashtable.ts +166 -0
  157. package/src/prove/smt/solver/internalizer.ts +1381 -0
  158. package/src/prove/smt/solver/lbool.ts +5 -0
  159. package/src/prove/smt/solver/literal.ts +24 -0
  160. package/src/prove/smt/solver/lp/bound-propagator.ts +391 -0
  161. package/src/prove/smt/solver/lp/constraints.ts +78 -0
  162. package/src/prove/smt/solver/lp/containers.ts +296 -0
  163. package/src/prove/smt/solver/lp/core-solver.ts +504 -0
  164. package/src/prove/smt/solver/lp/cross-nested.ts +224 -0
  165. package/src/prove/smt/solver/lp/dep-intervals.ts +656 -0
  166. package/src/prove/smt/solver/lp/dependency.ts +51 -0
  167. package/src/prove/smt/solver/lp/dioph-eq.ts +1181 -0
  168. package/src/prove/smt/solver/lp/explanation.ts +46 -0
  169. package/src/prove/smt/solver/lp/gomory.ts +255 -0
  170. package/src/prove/smt/solver/lp/hnf-cutter.ts +125 -0
  171. package/src/prove/smt/solver/lp/hnf.ts +281 -0
  172. package/src/prove/smt/solver/lp/int-cube.ts +295 -0
  173. package/src/prove/smt/solver/lp/int-solver.ts +514 -0
  174. package/src/prove/smt/solver/lp/lar-solver.ts +816 -0
  175. package/src/prove/smt/solver/lp/lar-term.ts +62 -0
  176. package/src/prove/smt/solver/lp/lp-settings.ts +91 -0
  177. package/src/prove/smt/solver/lp/maximize-term.ts +347 -0
  178. package/src/prove/smt/solver/lp/nex-creator.ts +381 -0
  179. package/src/prove/smt/solver/lp/nex.ts +120 -0
  180. package/src/prove/smt/solver/lp/nla-backoff.ts +43 -0
  181. package/src/prove/smt/solver/lp/nla-basics.ts +398 -0
  182. package/src/prove/smt/solver/lp/nla-core.ts +968 -0
  183. package/src/prove/smt/solver/lp/nla-divisions.ts +332 -0
  184. package/src/prove/smt/solver/lp/nla-emonics.ts +373 -0
  185. package/src/prove/smt/solver/lp/nla-factorization.ts +30 -0
  186. package/src/prove/smt/solver/lp/nla-grobner.ts +904 -0
  187. package/src/prove/smt/solver/lp/nla-horner.ts +126 -0
  188. package/src/prove/smt/solver/lp/nla-intervals.ts +265 -0
  189. package/src/prove/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  190. package/src/prove/smt/solver/lp/nla-monotone.ts +59 -0
  191. package/src/prove/smt/solver/lp/nla-order.ts +307 -0
  192. package/src/prove/smt/solver/lp/nla-patcher.ts +112 -0
  193. package/src/prove/smt/solver/lp/nla-tangents.ts +251 -0
  194. package/src/prove/smt/solver/lp/nla-throttle.ts +85 -0
  195. package/src/prove/smt/solver/lp/nla-types.ts +124 -0
  196. package/src/prove/smt/solver/lp/nla-var-eqs.ts +141 -0
  197. package/src/prove/smt/solver/lp/nra-solver.ts +440 -0
  198. package/src/prove/smt/solver/lp/numeric-pair.ts +65 -0
  199. package/src/prove/smt/solver/lp/pdd-interval.ts +31 -0
  200. package/src/prove/smt/solver/lp/pdd-simplifier.ts +184 -0
  201. package/src/prove/smt/solver/lp/pdd-solver.ts +408 -0
  202. package/src/prove/smt/solver/lp/pdd.ts +971 -0
  203. package/src/prove/smt/solver/lp/random-updater.ts +138 -0
  204. package/src/prove/smt/solver/lp/static-matrix.ts +246 -0
  205. package/src/prove/smt/solver/lp/union-find.ts +96 -0
  206. package/src/prove/smt/solver/mam-compiler.ts +847 -0
  207. package/src/prove/smt/solver/mam-interpreter.ts +400 -0
  208. package/src/prove/smt/solver/maximize-ac-sharing.ts +118 -0
  209. package/src/prove/smt/solver/model-checker.ts +347 -0
  210. package/src/prove/smt/solver/model-evaluator.ts +262 -0
  211. package/src/prove/smt/solver/model-finder.ts +155 -0
  212. package/src/prove/smt/solver/model-generator.ts +97 -0
  213. package/src/prove/smt/solver/model-macro-solver.ts +728 -0
  214. package/src/prove/smt/solver/nlsat/algebraic.ts +1161 -0
  215. package/src/prove/smt/solver/nlsat/atoms.ts +238 -0
  216. package/src/prove/smt/solver/nlsat/evaluator.ts +303 -0
  217. package/src/prove/smt/solver/nlsat/explain.ts +607 -0
  218. package/src/prove/smt/solver/nlsat/interval-set.ts +351 -0
  219. package/src/prove/smt/solver/nlsat/levelwise.ts +740 -0
  220. package/src/prove/smt/solver/nlsat/mpbq.ts +161 -0
  221. package/src/prove/smt/solver/nlsat/polynomial.ts +1722 -0
  222. package/src/prove/smt/solver/nlsat/solver.ts +911 -0
  223. package/src/prove/smt/solver/nlsat/types.ts +43 -0
  224. package/src/prove/smt/solver/nlsat/upolynomial-factorization.ts +648 -0
  225. package/src/prove/smt/solver/nlsat/upolynomial.ts +996 -0
  226. package/src/prove/smt/solver/nnf.ts +469 -0
  227. package/src/prove/smt/solver/pattern-inference.ts +351 -0
  228. package/src/prove/smt/solver/poly-rewriter.ts +477 -0
  229. package/src/prove/smt/solver/propagate-values.ts +83 -0
  230. package/src/prove/smt/solver/proto-model.ts +551 -0
  231. package/src/prove/smt/solver/pull-quant.ts +139 -0
  232. package/src/prove/smt/solver/qe-lite-der.ts +526 -0
  233. package/src/prove/smt/solver/qe-lite-fm.ts +576 -0
  234. package/src/prove/smt/solver/qe-lite.ts +381 -0
  235. package/src/prove/smt/solver/qi-queue.ts +362 -0
  236. package/src/prove/smt/solver/quant-tactics.ts +117 -0
  237. package/src/prove/smt/solver/quantifier-analyzer.ts +562 -0
  238. package/src/prove/smt/solver/quantifier-manager.ts +186 -0
  239. package/src/prove/smt/solver/random-gen.ts +10 -0
  240. package/src/prove/smt/solver/rational.ts +165 -0
  241. package/src/prove/smt/solver/ref-vector.ts +62 -0
  242. package/src/prove/smt/solver/relevancy.ts +247 -0
  243. package/src/prove/smt/solver/rewriter-tpl.ts +1159 -0
  244. package/src/prove/smt/solver/rewriter.ts +843 -0
  245. package/src/prove/smt/solver/rlimit.ts +79 -0
  246. package/src/prove/smt/solver/smtlib-parser.ts +526 -0
  247. package/src/prove/smt/solver/solver.ts +71 -0
  248. package/src/prove/smt/solver/sort.ts +35 -0
  249. package/src/prove/smt/solver/sticky-generations.ts +69 -0
  250. package/src/prove/smt/solver/theory-lra-axioms.ts +340 -0
  251. package/src/prove/smt/solver/theory-lra-bounds.ts +226 -0
  252. package/src/prove/smt/solver/theory-lra-final-check.ts +252 -0
  253. package/src/prove/smt/solver/theory-lra-internalize.ts +476 -0
  254. package/src/prove/smt/solver/theory-lra-model.ts +243 -0
  255. package/src/prove/smt/solver/theory-lra-propagate.ts +405 -0
  256. package/src/prove/smt/solver/theory-lra-state.ts +43 -0
  257. package/src/prove/smt/solver/theory-lra.ts +56 -0
  258. package/src/prove/smt/solver/var-subst.ts +258 -0
  259. package/src/prove/smt/solver/z3-license.txt +10 -0
  260. package/src/prove/smt/table.ts +170 -0
  261. package/src/prove/tlapm/tlapm.ts +97 -0
  262. package/src/prove/tlaps-module.ts +510 -0
  263. package/src/prove/verdict.ts +18 -0
  264. package/src/prove/zenon/LICENSE +32 -0
  265. package/src/prove/zenon/check/check.ts +105 -0
  266. package/src/prove/zenon/check/definitions.ts +144 -0
  267. package/src/prove/zenon/check/equality.ts +182 -0
  268. package/src/prove/zenon/check/functions.ts +62 -0
  269. package/src/prove/zenon/check/keys.ts +125 -0
  270. package/src/prove/zenon/check/propositional.ts +104 -0
  271. package/src/prove/zenon/check/records.ts +188 -0
  272. package/src/prove/zenon/check/relations.ts +121 -0
  273. package/src/prove/zenon/check/rewrites.ts +224 -0
  274. package/src/prove/zenon/check/sets.ts +302 -0
  275. package/src/prove/zenon/check/terms.ts +127 -0
  276. package/src/prove/zenon/check/tla.ts +126 -0
  277. package/src/prove/zenon/decide.ts +113 -0
  278. package/src/prove/zenon/encode.ts +444 -0
  279. package/src/prove/zenon/eqrel.ts +300 -0
  280. package/src/prove/zenon/equality-rules.ts +435 -0
  281. package/src/prove/zenon/expr.ts +551 -0
  282. package/src/prove/zenon/index-table.ts +350 -0
  283. package/src/prove/zenon/isar-case.ts +513 -0
  284. package/src/prove/zenon/isar.ts +1249 -0
  285. package/src/prove/zenon/limits.ts +15 -0
  286. package/src/prove/zenon/llproof.ts +173 -0
  287. package/src/prove/zenon/mltoll.ts +1566 -0
  288. package/src/prove/zenon/node.ts +297 -0
  289. package/src/prove/zenon/ocaml.ts +169 -0
  290. package/src/prove/zenon/parse.ts +247 -0
  291. package/src/prove/zenon/phrase.ts +191 -0
  292. package/src/prove/zenon/proof.ts +198 -0
  293. package/src/prove/zenon/propositional-rules.ts +387 -0
  294. package/src/prove/zenon/rules.ts +94 -0
  295. package/src/prove/zenon/search.ts +288 -0
  296. package/src/prove/zenon/tla/functions.ts +151 -0
  297. package/src/prove/zenon/tla/llproof.ts +480 -0
  298. package/src/prove/zenon/tla/records.ts +225 -0
  299. package/src/prove/zenon/tla/rewrites.ts +447 -0
  300. package/src/prove/zenon/tla/sets.ts +304 -0
  301. package/src/prove/zenon/tla/terms.ts +181 -0
  302. package/src/prove/zenon/tla/tla.ts +506 -0
  303. package/src/run-cli.ts +338 -62
  304. package/src/successors.ts +24 -5
  305. package/src/tlapm-cache.ts +244 -0
  306. package/src/tlc-random.ts +55 -32
  307. package/src/tlc-version.ts +8 -7
  308. package/src/values.ts +47 -4
  309. package/src/worker.ts +65 -0
  310. package/dist/parallel.cjs +0 -12
  311. package/dist/parallel.js +0 -12
@@ -0,0 +1,1722 @@
1
+ // Ported from Z3 (src/math/polynomial/polynomial.{h,cpp}, src/math/polynomial/polynomial_cache.cpp),
2
+ // MIT license, see z3-license.txt. Multivariate polynomials over the integers for nlsat, with
3
+ // Z3's factorization: univariate through upolynomial-factorization, quadratics through the square
4
+ // root of the discriminant, and higher degrees through bivariate Hensel lifting. A polynomial keeps its monomials in the order Z3's som buffers
5
+ // produce, with a monomial of maximal degree in the maximal variable first, because factorization
6
+ // breaks ties on the order in which variables occur.
7
+ //
8
+ // Deviations from Z3, which only change the order of equal results:
9
+ // - gcd computes with Z3's subresultant PRS (gcd_prs), not its modular algorithms (mod_gcd,
10
+ // uni_mod_gcd). Both return the same polynomial, normalized to a positive leading coefficient,
11
+ // but its monomials may come out in another order. Z3's modular gcd can also return a constant
12
+ // other than 1 for coprime primitive polynomials, gcd(2x - 3, 2x - 1) = 2
13
+ // (polynomial.cpp:4815), where this port returns 1. The callers in scope only test whether
14
+ // the gcd is constant.
15
+ // - Polynomial ids count up from zero. Z3 recycles the ids of deleted polynomials, so where nlsat
16
+ // breaks a tie between two root functions on their ids it may pick the other one. Matching Z3
17
+ // would take explicit reference counts at its roughly 490 polynomial_ref sites in polynomial,
18
+ // algebraic_numbers, explain, levelwise and nra, and every pm routine allocating the same
19
+ // temporaries as Z3's, not just returning the same result. Random differential tests hit such a
20
+ // tie in about 1 of 300 levelwise and 1 of 3,000 explain programs, and no corpus trace yet.
21
+ import { SmtInvariantError } from "../../../../errors";
22
+ import { getGcd, Rational } from "../rational";
23
+ import { UpolynomialManager } from "./upolynomial";
24
+ import {
25
+ DEFAULT_FACTOR_PARAMS,
26
+ factorSquareFree,
27
+ getExactSquareRoot,
28
+ type UpolynomialFactors,
29
+ } from "./upolynomial-factorization";
30
+
31
+ export const NULL_VAR = -1;
32
+
33
+ // s_factor_eval_values and s_factor_primes: the points multivariate factorization evaluates the
34
+ // other variables at, and the primes it lifts modulo.
35
+ const FACTOR_EVAL_VALUES = [0n, 1n, -1n, 2n, -2n, 3n, -3n];
36
+ const FACTOR_PRIMES = [39103n, 104729n, 1000003n, 100000007n];
37
+
38
+ // mpz div: rounds toward minus infinity.
39
+ const floorDiv = (dividend: bigint, divisor: bigint) => {
40
+ const quotient = dividend / divisor;
41
+ return dividend % divisor !== 0n && dividend < 0n !== divisor < 0n ? quotient - 1n : quotient;
42
+ };
43
+
44
+ // Input outside what the port of nlsat supports so far: subresultants of polynomials of degree 2
45
+ // or more in the variable being projected. The nra solver answers unknown on it, which is always
46
+ // sound.
47
+ // The arithmetic t_eval evaluates in: rationals, intervals or algebraic numbers.
48
+ export interface ValueOps<T> {
49
+ fromInteger(value: bigint): T;
50
+ add(first: T, second: T): T;
51
+ mul(first: T, second: T): T;
52
+ power(base: T, exponent: number): T;
53
+ }
54
+
55
+ const RATIONAL_OPS: ValueOps<Rational> = {
56
+ fromInteger: (value) => Rational.of(value),
57
+ add: (first, second) => first.add(second),
58
+ mul: (first, second) => first.mul(second),
59
+ power: (base, exponent) => base.pow(exponent),
60
+ };
61
+
62
+ const getMonomialKey = (vars: readonly number[], degrees: readonly number[]) =>
63
+ vars.map((variable, index) => `${variable}^${degrees[index]}`).join(",");
64
+
65
+ export class Monomial {
66
+ readonly totalDegree: number;
67
+
68
+ // vars and degrees change only when the manager renames the variables.
69
+ constructor(
70
+ readonly id: number,
71
+ public vars: readonly number[],
72
+ public degrees: readonly number[],
73
+ ) {
74
+ let total = 0;
75
+ for (const degree of degrees) total += degree;
76
+ this.totalDegree = total;
77
+ }
78
+
79
+ get size() {
80
+ return this.vars.length;
81
+ }
82
+
83
+ get maxVar() {
84
+ return this.vars.length === 0 ? NULL_VAR : this.vars[this.vars.length - 1];
85
+ }
86
+
87
+ get maxVarDegree() {
88
+ return this.vars.length === 0 ? 0 : this.degrees[this.degrees.length - 1];
89
+ }
90
+
91
+ degreeOf(variable: number) {
92
+ const index = this.vars.indexOf(variable);
93
+ return index === -1 ? 0 : this.degrees[index];
94
+ }
95
+
96
+ // max_smaller_than: the largest variable of the monomial below x.
97
+ maxSmallerThan(variable: number) {
98
+ let result = NULL_VAR;
99
+ for (const current of this.vars) if (current < variable) result = current;
100
+ return result;
101
+ }
102
+ }
103
+
104
+ // lex_compare: the biggest variable dominates, then its degree.
105
+ export const lexCompare = (first: Monomial, second: Monomial) => {
106
+ if (first === second) return 0;
107
+ let firstIndex = first.size - 1;
108
+ let secondIndex = second.size - 1;
109
+ while (firstIndex >= 0 && secondIndex >= 0) {
110
+ const firstVar = first.vars[firstIndex];
111
+ const secondVar = second.vars[secondIndex];
112
+ if (firstVar === secondVar) {
113
+ const firstDegree = first.degrees[firstIndex];
114
+ const secondDegree = second.degrees[secondIndex];
115
+ if (firstDegree === secondDegree) {
116
+ firstIndex--;
117
+ secondIndex--;
118
+ continue;
119
+ }
120
+ return firstDegree < secondDegree ? -1 : 1;
121
+ }
122
+ return firstVar > secondVar ? 1 : -1;
123
+ }
124
+ return firstIndex < 0 ? -1 : 1;
125
+ };
126
+
127
+ export const gradedLexCompare = (first: Monomial, second: Monomial) =>
128
+ first.totalDegree === second.totalDegree
129
+ ? lexCompare(first, second)
130
+ : first.totalDegree < second.totalDegree
131
+ ? -1
132
+ : 1;
133
+
134
+ // po_gt: the order that puts a monomial with the maximal variable at its maximal degree first.
135
+ const isPoGreater = (first: Monomial, second: Monomial) => {
136
+ if (first.size === 0) return false;
137
+ if (second.size === 0) return true;
138
+ if (first.maxVar !== second.maxVar) return first.maxVar > second.maxVar;
139
+ return first.maxVarDegree > second.maxVarDegree;
140
+ };
141
+
142
+ export class Polynomial {
143
+ isLexSorted = false;
144
+
145
+ constructor(
146
+ readonly id: number,
147
+ readonly as: bigint[],
148
+ readonly ms: Monomial[],
149
+ ) {
150
+ this.makeFirstMaximal();
151
+ }
152
+
153
+ // make_first_maximal: a monomial with the maximal variable at its maximal degree first.
154
+ makeFirstMaximal() {
155
+ if (this.ms.length <= 1) return;
156
+ let maxPos = 0;
157
+ for (let index = 1; index < this.ms.length; index++)
158
+ if (isPoGreater(this.ms[index], this.ms[maxPos])) maxPos = index;
159
+ this.swapFirst(maxPos);
160
+ this.isLexSorted = false;
161
+ }
162
+
163
+ get size() {
164
+ return this.ms.length;
165
+ }
166
+
167
+ private swapFirst(position: number) {
168
+ if (position === 0) return;
169
+ const coeff = this.as[0];
170
+ this.as[0] = this.as[position];
171
+ this.as[position] = coeff;
172
+ const monomial = this.ms[0];
173
+ this.ms[0] = this.ms[position];
174
+ this.ms[position] = monomial;
175
+ }
176
+
177
+ // lex_sort: puts the monomials in decreasing lexicographic order, which Z3 does in place whenever it
178
+ // hashes the polynomial.
179
+ lexSort() {
180
+ if (this.isLexSorted) return;
181
+ this.isLexSorted = true;
182
+ if (this.ms.length <= 1) return;
183
+ const order = this.ms.map((_monomial, index) => index);
184
+ order.sort((first, second) => lexCompare(this.ms[second], this.ms[first]));
185
+ const as = order.map((index) => this.as[index]);
186
+ const ms = order.map((index) => this.ms[index]);
187
+ for (let index = 0; index < order.length; index++) {
188
+ this.as[index] = as[index];
189
+ this.ms[index] = ms[index];
190
+ }
191
+ }
192
+
193
+ // graded_lex_max_pos
194
+ getGradedLexMaxPos() {
195
+ if (this.ms.length === 0) return -1;
196
+ let maxPos = 0;
197
+ for (let index = 1; index < this.ms.length; index++)
198
+ if (gradedLexCompare(this.ms[index], this.ms[maxPos]) > 0) maxPos = index;
199
+ return maxPos;
200
+ }
201
+
202
+ toString() {
203
+ if (this.ms.length === 0) return "0";
204
+ return this.ms
205
+ .map((monomial, index) => {
206
+ const powers = monomial.vars.map((variable, power) =>
207
+ monomial.degrees[power] === 1
208
+ ? `x${variable}`
209
+ : `x${variable}^${monomial.degrees[power]}`,
210
+ );
211
+ return [`${this.as[index]}`, ...powers].join("*");
212
+ })
213
+ .join(" + ");
214
+ }
215
+ }
216
+
217
+ // som_buffer: a sum of monomials, each kept at the position where it first appeared. Zero entries
218
+ // stay until mk removes them.
219
+ class SomBuffer {
220
+ as: bigint[] = [];
221
+ ms: Monomial[] = [];
222
+ private positions = new Map<number, number>();
223
+
224
+ constructor(private manager: PolynomialManager) {}
225
+
226
+ reset() {
227
+ this.as = [];
228
+ this.ms = [];
229
+ this.positions.clear();
230
+ }
231
+
232
+ addTerm(coeff: bigint, monomial: Monomial) {
233
+ if (coeff === 0n) return;
234
+ const position = this.positions.get(monomial.id);
235
+ if (position === undefined) {
236
+ this.positions.set(monomial.id, this.ms.length);
237
+ this.ms.push(monomial);
238
+ this.as.push(coeff);
239
+ return;
240
+ }
241
+ this.as[position] += coeff;
242
+ }
243
+
244
+ add(polynomial: Polynomial) {
245
+ for (let index = 0; index < polynomial.size; index++) {
246
+ const monomial = polynomial.ms[index];
247
+ const position = this.positions.get(monomial.id);
248
+ if (position === undefined) {
249
+ this.positions.set(monomial.id, this.ms.length);
250
+ this.ms.push(monomial);
251
+ this.as.push(polynomial.as[index]);
252
+ } else this.as[position] += polynomial.as[index];
253
+ }
254
+ }
255
+
256
+ // addmul: adds a*m*p.
257
+ addmul(coeff: bigint, monomial: Monomial, polynomial: Polynomial) {
258
+ if (coeff === 0n) return;
259
+ for (let index = 0; index < polynomial.size; index++) {
260
+ const product = this.manager.mulMonomials(monomial, polynomial.ms[index]);
261
+ const position = this.positions.get(product.id);
262
+ if (position === undefined) {
263
+ this.positions.set(product.id, this.ms.length);
264
+ this.ms.push(product);
265
+ this.as.push(coeff * polynomial.as[index]);
266
+ } else this.as[position] += coeff * polynomial.as[index];
267
+ }
268
+ }
269
+
270
+ // addmul(a, m, buffer): adds a*m times each entry of another buffer, zero entries included,
271
+ // which keeps their monomials at new positions as Z3 does.
272
+ addmulBuffer(coeff: bigint, monomial: Monomial, buffer: SomBuffer) {
273
+ if (coeff === 0n) return;
274
+ for (let index = 0; index < buffer.ms.length; index++) {
275
+ const product = this.manager.mulMonomials(monomial, buffer.ms[index]);
276
+ const position = this.positions.get(product.id);
277
+ if (position === undefined) {
278
+ this.positions.set(product.id, this.ms.length);
279
+ this.ms.push(product);
280
+ this.as.push(coeff * buffer.as[index]);
281
+ } else this.as[position] += coeff * buffer.as[index];
282
+ }
283
+ }
284
+
285
+ getGradedLexMaxPos() {
286
+ let maxPos = -1;
287
+ for (let index = 0; index < this.as.length; index++) {
288
+ if (this.as[index] === 0n) continue;
289
+ if (maxPos === -1 || gradedLexCompare(this.ms[index], this.ms[maxPos]) > 0) maxPos = index;
290
+ }
291
+ return maxPos;
292
+ }
293
+
294
+ // mk(normalize): the nonzero entries, divided by the gcd of their coefficients when normalizing.
295
+ mk(isNormalized = false) {
296
+ const as: bigint[] = [];
297
+ const ms: Monomial[] = [];
298
+ for (let index = 0; index < this.as.length; index++) {
299
+ if (this.as[index] === 0n) continue;
300
+ as.push(this.as[index]);
301
+ ms.push(this.ms[index]);
302
+ }
303
+ this.reset();
304
+ const gcd = isNormalized ? as.reduce((current, coeff) => getGcd(current, coeff), 0n) : 1n;
305
+ return this.manager.mkPolynomialCore(gcd > 1n ? as.map((coeff) => coeff / gcd) : as, ms);
306
+ }
307
+ }
308
+
309
+ // cheap_som_buffer: each monomial is added at most once, so it needs no position map.
310
+ class CheapSomBuffer {
311
+ private as: bigint[] = [];
312
+ private ms: Monomial[] = [];
313
+
314
+ constructor(private manager: PolynomialManager) {}
315
+
316
+ add(coeff: bigint, monomial: Monomial) {
317
+ if (coeff === 0n) return;
318
+ this.as.push(coeff);
319
+ this.ms.push(monomial);
320
+ }
321
+
322
+ addmul(coeff: bigint, monomial: Monomial, polynomial: Polynomial) {
323
+ if (coeff === 0n) return;
324
+ for (let index = 0; index < polynomial.size; index++) {
325
+ this.as.push(coeff * polynomial.as[index]);
326
+ this.ms.push(this.manager.mulMonomials(monomial, polynomial.ms[index]));
327
+ }
328
+ }
329
+
330
+ mk() {
331
+ const result = this.manager.mkPolynomialCore(this.as, this.ms);
332
+ this.as = [];
333
+ this.ms = [];
334
+ return result;
335
+ }
336
+ }
337
+
338
+ export interface Factors {
339
+ constant: bigint;
340
+ factors: Polynomial[];
341
+ degrees: number[];
342
+ }
343
+
344
+ export class PolynomialManager {
345
+ private monomials = new Map<string, Monomial>();
346
+ private nextPolynomialId = 0;
347
+ readonly unit: Monomial;
348
+ readonly zero: Polynomial;
349
+ readonly one: Polynomial;
350
+ private um = new UpolynomialManager();
351
+ private som = new SomBuffer(this);
352
+ private som2 = new SomBuffer(this);
353
+ private cheap = new CheapSomBuffer(this);
354
+
355
+ constructor() {
356
+ this.unit = this.mkMonomial([], []);
357
+ this.zero = this.mkPolynomialCore([], []);
358
+ this.one = this.mkPolynomialCore([1n], [this.unit]);
359
+ }
360
+
361
+ // Monomials.
362
+
363
+ mkMonomial(vars: readonly number[], degrees: readonly number[]) {
364
+ const key = getMonomialKey(vars, degrees);
365
+ const existing = this.monomials.get(key);
366
+ if (existing !== undefined) return existing;
367
+ const monomial = new Monomial(this.monomials.size, vars, degrees);
368
+ this.monomials.set(key, monomial);
369
+ return monomial;
370
+ }
371
+
372
+ // rename: every variable x becomes permutation[x], in place in every monomial, as Z3 renames its
373
+ // monomial table. Z3 then moves a maximal monomial first in every live polynomial. Here that is
374
+ // the given polynomials, the ones nlsat keeps in its atoms. Others keep their order, which
375
+ // matches again once the order is restored.
376
+ rename(permutation: readonly number[], polynomials: Iterable<Polynomial>) {
377
+ const monomials = new Map<string, Monomial>();
378
+ for (const monomial of this.monomials.values()) {
379
+ const order = monomial.vars
380
+ .map((_variable, index) => index)
381
+ .sort(
382
+ (first, second) => permutation[monomial.vars[first]] - permutation[monomial.vars[second]],
383
+ );
384
+ const degrees = monomial.degrees;
385
+ monomial.degrees = order.map((index) => degrees[index]);
386
+ monomial.vars = order.map((index) => permutation[monomial.vars[index]]);
387
+ monomials.set(getMonomialKey(monomial.vars, monomial.degrees), monomial);
388
+ }
389
+ this.monomials = monomials;
390
+ for (const polynomial of polynomials) polynomial.makeFirstMaximal();
391
+ }
392
+
393
+ // mk_monomial(x, k): x^k, the unit for k = 0.
394
+ mkPower(variable: number, power: number) {
395
+ return power === 0 ? this.unit : this.mkMonomial([variable], [power]);
396
+ }
397
+
398
+ mulMonomials(first: Monomial, second: Monomial) {
399
+ if (first.size === 0) return second;
400
+ if (second.size === 0) return first;
401
+ const vars: number[] = [];
402
+ const degrees: number[] = [];
403
+ let firstIndex = 0;
404
+ let secondIndex = 0;
405
+ while (firstIndex < first.size || secondIndex < second.size) {
406
+ const firstVar = firstIndex < first.size ? first.vars[firstIndex] : Infinity;
407
+ const secondVar = secondIndex < second.size ? second.vars[secondIndex] : Infinity;
408
+ if (firstVar === secondVar) {
409
+ vars.push(firstVar);
410
+ degrees.push(first.degrees[firstIndex++] + second.degrees[secondIndex++]);
411
+ } else if (firstVar < secondVar) {
412
+ vars.push(firstVar);
413
+ degrees.push(first.degrees[firstIndex++]);
414
+ } else {
415
+ vars.push(secondVar);
416
+ degrees.push(second.degrees[secondIndex++]);
417
+ }
418
+ }
419
+ return this.mkMonomial(vars, degrees);
420
+ }
421
+
422
+ // div: m1/m2, or null when m2 does not divide m1.
423
+ divMonomials(first: Monomial, second: Monomial) {
424
+ const vars: number[] = [];
425
+ const degrees: number[] = [];
426
+ let secondIndex = 0;
427
+ for (let index = 0; index < first.size; index++) {
428
+ const variable = first.vars[index];
429
+ let degree = first.degrees[index];
430
+ if (secondIndex < second.size && second.vars[secondIndex] === variable) {
431
+ degree -= second.degrees[secondIndex++];
432
+ if (degree < 0) return null;
433
+ } else if (secondIndex < second.size && second.vars[secondIndex] < variable) return null;
434
+ if (degree > 0) {
435
+ vars.push(variable);
436
+ degrees.push(degree);
437
+ }
438
+ }
439
+ return secondIndex < second.size ? null : this.mkMonomial(vars, degrees);
440
+ }
441
+
442
+ // div_x_k: m/x^k.
443
+ private divXk(monomial: Monomial, variable: number, power: number) {
444
+ const vars: number[] = [];
445
+ const degrees: number[] = [];
446
+ for (let index = 0; index < monomial.size; index++) {
447
+ const degree =
448
+ monomial.vars[index] === variable
449
+ ? monomial.degrees[index] - power
450
+ : monomial.degrees[index];
451
+ if (degree === 0) continue;
452
+ vars.push(monomial.vars[index]);
453
+ degrees.push(degree);
454
+ }
455
+ return this.mkMonomial(vars, degrees);
456
+ }
457
+
458
+ // div_x: m with x removed.
459
+ private divX(monomial: Monomial, variable: number) {
460
+ return this.divXk(monomial, variable, monomial.degreeOf(variable));
461
+ }
462
+
463
+ // Construction.
464
+
465
+ mkPolynomialCore(as: bigint[], ms: Monomial[]) {
466
+ return new Polynomial(this.nextPolynomialId++, as, ms);
467
+ }
468
+
469
+ mkConst(value: bigint) {
470
+ if (value === 0n) return this.zero;
471
+ if (value === 1n) return this.one;
472
+ return this.mkPolynomialCore([value], [this.unit]);
473
+ }
474
+
475
+ mkVar(variable: number, degree = 1) {
476
+ return this.mkPolynomialCore([1n], [this.mkMonomial([variable], [degree])]);
477
+ }
478
+
479
+ mkPolynomial(as: readonly bigint[], ms: readonly Monomial[]) {
480
+ this.som.reset();
481
+ for (let index = 0; index < as.length; index++) this.som.addTerm(as[index], ms[index]);
482
+ return this.som.mk();
483
+ }
484
+
485
+ // mk_linear: sum of as[i]*xs[i] plus c.
486
+ mkLinear(as: readonly bigint[], vars: readonly number[], constant: bigint) {
487
+ const coeffs: bigint[] = [];
488
+ const ms: Monomial[] = [];
489
+ for (let index = 0; index < as.length; index++) {
490
+ if (as[index] === 0n) continue;
491
+ coeffs.push(as[index]);
492
+ ms.push(this.mkMonomial([vars[index]], [1]));
493
+ }
494
+ if (constant !== 0n) {
495
+ coeffs.push(constant);
496
+ ms.push(this.unit);
497
+ }
498
+ return this.mkPolynomial(coeffs, ms);
499
+ }
500
+
501
+ // Queries.
502
+
503
+ isZero(polynomial: Polynomial) {
504
+ return polynomial.size === 0;
505
+ }
506
+
507
+ isConst(polynomial: Polynomial) {
508
+ return polynomial.size === 0 || (polynomial.size === 1 && polynomial.ms[0].size === 0);
509
+ }
510
+
511
+ isUnivariate(polynomial: Polynomial) {
512
+ if (this.isConst(polynomial)) return true;
513
+ const maxVar = this.maxVar(polynomial);
514
+ for (const monomial of polynomial.ms)
515
+ if (monomial.size > 1 || (monomial.size === 1 && monomial.vars[0] !== maxVar)) return false;
516
+ return true;
517
+ }
518
+
519
+ maxVar(polynomial: Polynomial) {
520
+ return polynomial.size === 0 ? NULL_VAR : polynomial.ms[0].maxVar;
521
+ }
522
+
523
+ degree(polynomial: Polynomial, variable: number) {
524
+ let result = 0;
525
+ for (const monomial of polynomial.ms) result = Math.max(result, monomial.degreeOf(variable));
526
+ return result;
527
+ }
528
+
529
+ totalDegree(polynomial: Polynomial) {
530
+ let result = 0;
531
+ for (const monomial of polynomial.ms) result = Math.max(result, monomial.totalDegree);
532
+ return result;
533
+ }
534
+
535
+ // eq: the same monomials with the same coefficients, in any order.
536
+ eq(first: Polynomial, second: Polynomial) {
537
+ if (first === second) return true;
538
+ if (first.size !== second.size) return false;
539
+ if (first.size === 0) return true;
540
+ if (this.maxVar(first) !== this.maxVar(second)) return false;
541
+ const coeffs = new Map<number, bigint>();
542
+ for (let index = 0; index < first.size; index++)
543
+ coeffs.set(first.ms[index].id, first.as[index]);
544
+ for (let index = 0; index < second.size; index++)
545
+ if (coeffs.get(second.ms[index].id) !== second.as[index]) return false;
546
+ return true;
547
+ }
548
+
549
+ // The key of the hash-consing table. It lexicographically sorts the polynomial in place, as Z3's
550
+ // hash does.
551
+ getKey(polynomial: Polynomial) {
552
+ polynomial.lexSort();
553
+ let key = "";
554
+ for (let index = 0; index < polynomial.size; index++)
555
+ key += `${polynomial.as[index]}:${polynomial.ms[index].id};`;
556
+ return key;
557
+ }
558
+
559
+ // Arithmetic.
560
+
561
+ private addmul(firstCoeff: bigint, first: Polynomial, secondCoeff: bigint, second: Polynomial) {
562
+ this.som.reset();
563
+ this.som.addmul(firstCoeff, this.unit, first);
564
+ this.som.addmul(secondCoeff, this.unit, second);
565
+ return this.som.mk();
566
+ }
567
+
568
+ add(first: Polynomial, second: Polynomial) {
569
+ return this.addmul(1n, first, 1n, second);
570
+ }
571
+
572
+ sub(first: Polynomial, second: Polynomial) {
573
+ return this.addmul(1n, first, -1n, second);
574
+ }
575
+
576
+ mul(first: Polynomial, second: Polynomial) {
577
+ if (first.size === 0 || second.size === 0) return this.zero;
578
+ this.som.reset();
579
+ for (let index = 0; index < first.size; index++)
580
+ this.som.addmul(first.as[index], first.ms[index], second);
581
+ return this.som.mk();
582
+ }
583
+
584
+ // mul(a, m, p): a*m*p.
585
+ mulTerm(coeff: bigint, monomial: Monomial, polynomial: Polynomial) {
586
+ if (coeff === 0n) return this.zero;
587
+ if (coeff === 1n && monomial === this.unit) return polynomial;
588
+ this.cheap.addmul(coeff, monomial, polynomial);
589
+ return this.cheap.mk();
590
+ }
591
+
592
+ mulConst(coeff: bigint, polynomial: Polynomial) {
593
+ return this.mulTerm(coeff, this.unit, polynomial);
594
+ }
595
+
596
+ neg(polynomial: Polynomial) {
597
+ for (let index = 0; index < polynomial.size; index++)
598
+ this.cheap.add(-polynomial.as[index], polynomial.ms[index]);
599
+ return this.cheap.mk();
600
+ }
601
+
602
+ pw(polynomial: Polynomial, power: number) {
603
+ if (power === 0) return this.one;
604
+ let result = polynomial;
605
+ for (let index = 1; index < power; index++) result = this.mul(result, polynomial);
606
+ return result;
607
+ }
608
+
609
+ // coeff: the coefficient of x^k, a polynomial in the other variables.
610
+ coeff(polynomial: Polynomial, variable: number, power: number) {
611
+ for (let index = 0; index < polynomial.size; index++) {
612
+ const monomial = polynomial.ms[index];
613
+ if (monomial.degreeOf(variable) === power)
614
+ this.cheap.add(polynomial.as[index], this.divX(monomial, variable));
615
+ }
616
+ return this.cheap.mk();
617
+ }
618
+
619
+ // const_coeff: the coefficient of x^k when it is a number, else null.
620
+ getConstCoeff(polynomial: Polynomial, variable: number, power: number) {
621
+ let result = 0n;
622
+ for (let index = 0; index < polynomial.size; index++) {
623
+ const monomial = polynomial.ms[index];
624
+ if (monomial.degreeOf(variable) !== power) continue;
625
+ if ((power > 0 && monomial.size > 1) || (power === 0 && monomial.size > 0)) return null;
626
+ result = polynomial.as[index];
627
+ }
628
+ return result;
629
+ }
630
+
631
+ lc(polynomial: Polynomial, variable: number) {
632
+ return this.coeff(polynomial, variable, this.degree(polynomial, variable));
633
+ }
634
+
635
+ derivative(polynomial: Polynomial, variable: number) {
636
+ for (let index = 0; index < polynomial.size; index++) {
637
+ const monomial = polynomial.ms[index];
638
+ const degree = monomial.degreeOf(variable);
639
+ if (degree > 0)
640
+ this.cheap.add(polynomial.as[index] * BigInt(degree), this.divXk(monomial, variable, 1));
641
+ }
642
+ return this.cheap.mk();
643
+ }
644
+
645
+ // flip_sign_if_lm_neg: negates p when its graded-lex leading coefficient is negative.
646
+ flipSignIfLmNeg(polynomial: Polynomial) {
647
+ if (polynomial.size === 0) return polynomial;
648
+ return polynomial.as[polynomial.getGradedLexMaxPos()] < 0n ? this.neg(polynomial) : polynomial;
649
+ }
650
+
651
+ // ic: the integer content, the gcd of the coefficients.
652
+ private getIc(polynomial: Polynomial) {
653
+ if (polynomial.size === 0) return 0n;
654
+ if (this.isConst(polynomial)) return polynomial.as[0];
655
+ let result = polynomial.as[0];
656
+ for (let index = 1; index < polynomial.size; index++) {
657
+ if (result === 1n) return result;
658
+ result = getGcd(result, polynomial.as[index]);
659
+ }
660
+ return result;
661
+ }
662
+
663
+ // ic(p, a, c): p = a*c, with the coefficients of c coprime.
664
+ private icWithContent(polynomial: Polynomial): [bigint, Polynomial] {
665
+ if (polynomial.size === 0) return [0n, polynomial];
666
+ if (this.isConst(polynomial)) return [polynomial.as[0], this.one];
667
+ let content = 0n;
668
+ for (const coeff of polynomial.as) content = getGcd(content, coeff);
669
+ if (content === 1n) return [1n, polynomial];
670
+ for (let index = 0; index < polynomial.size; index++)
671
+ this.cheap.add(polynomial.as[index] / content, polynomial.ms[index]);
672
+ return [content, this.cheap.mk()];
673
+ }
674
+
675
+ // iccp: the integer content, the content and the primitive part of p with respect to x.
676
+ iccp(polynomial: Polynomial, variable: number): [bigint, Polynomial, Polynomial] {
677
+ if (polynomial.size === 0) return [0n, this.one, polynomial];
678
+ if (this.isConst(polynomial)) return [polynomial.as[0], this.one, this.one];
679
+ const degree = this.degree(polynomial, variable);
680
+ if (degree === 0) {
681
+ const [integer, content] = this.icWithContent(polynomial);
682
+ return [integer, content, this.one];
683
+ }
684
+ // The quick filter: a power of x that occurs only as a pure power means the content is 1.
685
+ const filter = Array.from({ length: degree + 1 }, () => 0);
686
+ const powers: number[] = [];
687
+ for (const monomial of polynomial.ms) {
688
+ const power = monomial.degreeOf(variable);
689
+ if (filter[power] === 0) powers.push(power);
690
+ filter[power] += monomial.size === (power > 0 ? 1 : 0) ? 1 : 2;
691
+ }
692
+ const [integer, primitive] = this.icWithContent(polynomial);
693
+ for (const power of powers) if (filter[power] === 1) return [integer, this.one, primitive];
694
+ let content = this.coeff(primitive, variable, powers[0]);
695
+ for (let index = 1; index < powers.length; index++) {
696
+ content = this.gcd(content, this.coeff(primitive, variable, powers[index]));
697
+ if (this.isConst(content)) return [integer, this.one, primitive];
698
+ }
699
+ content = this.flipSignIfLmNeg(content);
700
+ return [integer, content, this.exactDiv(primitive, content)];
701
+ }
702
+
703
+ pp(polynomial: Polynomial, variable: number) {
704
+ return this.iccp(polynomial, variable)[2];
705
+ }
706
+
707
+ // square_free: the integer content times the square-free parts of the content and the primitive
708
+ // part in the maximal variable, or p itself when it is square-free.
709
+ squareFree(polynomial: Polynomial): Polynomial {
710
+ if (this.isConst(polynomial)) return polynomial;
711
+ const variable = this.maxVar(polynomial);
712
+ const [integer, content, primitive] = this.iccp(polynomial, variable);
713
+ const squareFreeContent = this.squareFree(content);
714
+ const g = this.gcd(primitive, this.derivative(primitive, variable));
715
+ if (this.isConst(g) && this.eq(squareFreeContent, content)) return polynomial;
716
+ const squareFreePrimitive = this.isConst(g) ? primitive : this.exactDiv(primitive, g);
717
+ return this.mul(this.mulConst(integer, squareFreeContent), squareFreePrimitive);
718
+ }
719
+
720
+ // normalize: p divided by the gcd of its coefficients.
721
+ normalize(polynomial: Polynomial) {
722
+ if (polynomial.size === 0) return polynomial;
723
+ let g = 0n;
724
+ for (const coeff of polynomial.as) g = getGcd(g, coeff);
725
+ if (g === 1n) return polynomial;
726
+ for (let index = 0; index < polynomial.size; index++)
727
+ this.cheap.add(polynomial.as[index] / g, polynomial.ms[index]);
728
+ return this.cheap.mk();
729
+ }
730
+
731
+ // nonzero_const_coeff: whether the coefficient of x^k is a nonzero number.
732
+ isNonzeroConstCoeff(polynomial: Polynomial, variable: number, power: number) {
733
+ const coeff = this.getConstCoeff(polynomial, variable, power);
734
+ return coeff !== null && coeff !== 0n;
735
+ }
736
+
737
+ // exact_div: p/q, where q divides p.
738
+ exactDiv(polynomial: Polynomial, divisor: Polynomial) {
739
+ if (polynomial.size === 0) return polynomial;
740
+ const remainder = this.som;
741
+ const quotient = this.som2;
742
+ remainder.reset();
743
+ quotient.reset();
744
+ remainder.add(polynomial);
745
+ const maxPos = divisor.getGradedLexMaxPos();
746
+ const divisorMonomial = divisor.ms[maxPos];
747
+ const divisorCoeff = divisor.as[maxPos];
748
+ while (true) {
749
+ const remainderPos = remainder.getGradedLexMaxPos();
750
+ if (remainderPos === -1) {
751
+ remainder.reset();
752
+ return quotient.mk();
753
+ }
754
+ const monomial = this.divMonomials(remainder.ms[remainderPos], divisorMonomial);
755
+ if (monomial === null) throw new SmtInvariantError("exact_div: the divisor does not divide");
756
+ const coeff = remainder.as[remainderPos] / divisorCoeff;
757
+ quotient.addTerm(coeff, monomial);
758
+ remainder.addmul(-coeff, monomial, divisor);
759
+ }
760
+ }
761
+
762
+ // exact_pseudo_division: Q and R with lc(q)^(deg(p) - deg(q) + 1) * p = Q*q + R. The
763
+ // quotient is only built when asked for, as in pseudo_division_core.
764
+ exactPseudoDivision(
765
+ polynomial: Polynomial,
766
+ divisor: Polynomial,
767
+ variable: number,
768
+ isQuotient = true,
769
+ ) {
770
+ return this.pseudoDivisionCore(polynomial, divisor, variable, true, isQuotient);
771
+ }
772
+
773
+ // pseudo_remainder: R with lc(q)^d * p = Q*q + R, where d counts the division steps.
774
+ pseudoRemainder(polynomial: Polynomial, divisor: Polynomial, variable: number) {
775
+ return this.pseudoDivisionCore(polynomial, divisor, variable, false, false);
776
+ }
777
+
778
+ private pseudoDivisionCore(
779
+ polynomial: Polynomial,
780
+ divisor: Polynomial,
781
+ variable: number,
782
+ isExact: boolean,
783
+ isQuotient: boolean,
784
+ ) {
785
+ const degA = this.degree(polynomial, variable);
786
+ const degB = this.degree(divisor, variable);
787
+ if (degB === 0) {
788
+ const steps = isExact ? degA + 1 : 1;
789
+ if (!isQuotient || !isExact || degA === 0)
790
+ return { quotient: polynomial, remainder: this.zero, steps };
791
+ return {
792
+ quotient: this.mul(polynomial, this.pw(divisor, degA)),
793
+ remainder: this.zero,
794
+ steps,
795
+ };
796
+ }
797
+ const lcB = this.coeff(divisor, variable, degB);
798
+ const reductB = this.reduct(divisor, variable, degB);
799
+ let remainder = polynomial;
800
+ let quotient = this.zero;
801
+ let steps = 0;
802
+ while (true) {
803
+ const degR = this.degree(remainder, variable);
804
+ if (degB > degR) {
805
+ const exactSteps = degA - degB + 1;
806
+ if (isExact && steps < exactSteps) {
807
+ const power = this.pw(lcB, exactSteps - steps);
808
+ if (isQuotient) quotient = this.mul(power, quotient);
809
+ remainder = this.mul(power, remainder);
810
+ }
811
+ return { quotient, remainder, steps };
812
+ }
813
+ this.som.reset();
814
+ this.som2.reset();
815
+ for (let index = 0; index < remainder.size; index++) {
816
+ const monomial = remainder.ms[index];
817
+ const coeff = remainder.as[index];
818
+ if (monomial.degreeOf(variable) === degR) {
819
+ const shifted = this.divXk(monomial, variable, degB);
820
+ if (isQuotient) this.som2.addTerm(coeff, shifted);
821
+ this.som.addmul(-coeff, shifted, reductB);
822
+ } else this.som.addmul(coeff, monomial, lcB);
823
+ }
824
+ remainder = this.som.mk();
825
+ if (isQuotient) {
826
+ for (let index = 0; index < quotient.size; index++)
827
+ this.som2.addmul(quotient.as[index], quotient.ms[index], lcB);
828
+ quotient = this.som2.mk();
829
+ }
830
+ steps++;
831
+ }
832
+ }
833
+
834
+ exactPseudoRemainder(polynomial: Polynomial, divisor: Polynomial, variable: number) {
835
+ return this.exactPseudoDivision(polynomial, divisor, variable, false).remainder;
836
+ }
837
+
838
+ // The reduct of coeff(p, x, k, reduct): p without its x^k monomials.
839
+ reduct(polynomial: Polynomial, variable: number, power: number) {
840
+ for (let index = 0; index < polynomial.size; index++)
841
+ if (polynomial.ms[index].degreeOf(variable) !== power)
842
+ this.cheap.add(polynomial.as[index], polynomial.ms[index]);
843
+ return this.cheap.mk();
844
+ }
845
+
846
+ // var_max_degrees, sorted by variable.
847
+ private getVarMaxDegrees(polynomial: Polynomial) {
848
+ const degrees = new Map<number, number>();
849
+ for (const monomial of polynomial.ms)
850
+ for (let index = 0; index < monomial.size; index++) {
851
+ const variable = monomial.vars[index];
852
+ degrees.set(variable, Math.max(degrees.get(variable) ?? 0, monomial.degrees[index]));
853
+ }
854
+ return [...degrees.entries()].sort((first, second) => first[0] - second[0]);
855
+ }
856
+
857
+ // gcd: the greatest common divisor, with a positive integer content and leading coefficient.
858
+ gcd(first: Polynomial, second: Polynomial): Polynomial {
859
+ if (first.size === 0) return this.flipSignIfLmNeg(second);
860
+ if (second.size === 0) return this.flipSignIfLmNeg(first);
861
+ if (first === second) return this.flipSignIfLmNeg(first);
862
+ if (this.isConst(first) || this.isConst(second))
863
+ return this.mkConst(getGcd(this.getIc(second), this.getIc(first)));
864
+ const firstDegrees = this.getVarMaxDegrees(first);
865
+ const secondDegrees = this.getVarMaxDegrees(second);
866
+ const size = Math.min(firstDegrees.length, secondDegrees.length);
867
+ for (let index = 0; index < size; index++) {
868
+ const firstVar = firstDegrees[index][0];
869
+ const secondVar = secondDegrees[index][0];
870
+ if (firstVar < secondVar) return this.gcdContent(first, firstVar, second);
871
+ if (firstVar > secondVar) return this.gcdContent(second, secondVar, first);
872
+ }
873
+ if (size < firstDegrees.length) return this.gcdContent(first, firstDegrees[size][0], second);
874
+ if (size < secondDegrees.length) return this.gcdContent(second, secondDegrees[size][0], first);
875
+ return this.gcdPrs(first, second, firstDegrees[size - 1][0]);
876
+ }
877
+
878
+ // gcd_content: gcd(content(u, x), v).
879
+ private gcdContent(polynomial: Polynomial, variable: number, other: Polynomial) {
880
+ const [integer, content] = this.iccp(polynomial, variable);
881
+ return this.gcd(this.mulConst(integer, content), other);
882
+ }
883
+
884
+ // gcd_prs: Collins' subresultant polynomial remainder sequence.
885
+ private gcdPrs(first: Polynomial, second: Polynomial, variable: number) {
886
+ const [u, v] =
887
+ this.degree(first, variable) < this.degree(second, variable)
888
+ ? [second, first]
889
+ : [first, second];
890
+ const [integerU, contentU, primitiveU] = this.iccp(u, variable);
891
+ const [integerV, contentV, primitiveV] = this.iccp(v, variable);
892
+ const contentGcd = this.gcd(contentU, contentV);
893
+ const integerGcd = getGcd(integerU, integerV);
894
+ let ppU = primitiveU;
895
+ let ppV = primitiveV;
896
+ let g = this.one;
897
+ let h = this.one;
898
+ while (true) {
899
+ const delta = this.degree(ppU, variable) - this.degree(ppV, variable);
900
+ const remainder = this.exactPseudoRemainder(ppU, ppV, variable);
901
+ if (remainder.size === 0) {
902
+ const result = this.pp(this.flipSignIfLmNeg(ppV), variable);
903
+ return this.mulConst(integerGcd, this.mul(contentGcd, result));
904
+ }
905
+ if (this.isConst(remainder)) return this.mulConst(integerGcd, contentGcd);
906
+ ppU = ppV;
907
+ ppV = this.exactDiv(remainder, g);
908
+ for (let index = 0; index < delta; index++) ppV = this.exactDiv(ppV, h);
909
+ g = this.lc(ppU, variable);
910
+ let newH = this.one;
911
+ for (let index = 0; index < delta; index++) newH = this.mul(newH, g);
912
+ for (let index = 1; index < delta; index++) newH = this.exactDiv(newH, h);
913
+ h = newH;
914
+ }
915
+ }
916
+
917
+ // get_min_degree_var: the first variable, in order of occurrence, of minimal degree.
918
+ private getMinDegreeVar(polynomial: Polynomial) {
919
+ const degrees = new Map<number, number>();
920
+ for (const monomial of polynomial.ms)
921
+ for (let index = 0; index < monomial.size; index++) {
922
+ const variable = monomial.vars[index];
923
+ if (monomial.degrees[index] > (degrees.get(variable) ?? 0))
924
+ degrees.set(variable, monomial.degrees[index]);
925
+ }
926
+ let result = NULL_VAR;
927
+ let minDegree = Infinity;
928
+ for (const [variable, degree] of degrees)
929
+ if (degree < minDegree) {
930
+ result = variable;
931
+ minDegree = degree;
932
+ }
933
+ return result;
934
+ }
935
+
936
+ // factor: the constant and the irreducible factors, each with its multiplicity. A square-free
937
+ // primitive part of degree 2 or more in its variable of minimal degree is out of scope.
938
+ factor(polynomial: Polynomial): Factors {
939
+ const result: Factors = { constant: 1n, factors: [], degrees: [] };
940
+ if (polynomial.size === 0) result.constant = 0n;
941
+ else this.factorCore(polynomial, result);
942
+ return result;
943
+ }
944
+
945
+ private factorCore(polynomial: Polynomial, result: Factors) {
946
+ if (this.isConst(polynomial)) {
947
+ result.constant *= polynomial.as[0];
948
+ return;
949
+ }
950
+ const variable = this.getMinDegreeVar(polynomial);
951
+ const [integer, content, primitive] = this.iccp(polynomial, variable);
952
+ result.constant *= integer;
953
+ this.factorCore(content, result);
954
+ let square = this.gcd(primitive, this.derivative(primitive, variable));
955
+ if (this.isConst(square)) {
956
+ this.factorSqfPp(primitive, variable, 1, result);
957
+ return;
958
+ }
959
+ let product = this.exactDiv(primitive, square);
960
+ for (let multiplicity = 1; !this.isConst(product); multiplicity++) {
961
+ const next = this.gcd(product, square);
962
+ const factor = this.exactDiv(product, next);
963
+ if (!this.isConst(factor)) this.factorSqfPp(factor, variable, multiplicity, result);
964
+ else if (factor.as[0] === -1n && multiplicity % 2 === 1) result.constant = -result.constant;
965
+ square = this.exactDiv(square, next);
966
+ product = next;
967
+ }
968
+ }
969
+
970
+ // factor_sqf_pp: the factors of a primitive square-free p of positive degree in x.
971
+ private factorSqfPp(polynomial: Polynomial, variable: number, k: number, result: Factors) {
972
+ const degree = this.degree(polynomial, variable);
973
+ if (degree === 1) this.pushFactor(result, polynomial, k);
974
+ else if (this.isUnivariate(polynomial)) this.factorSqfPpUniv(polynomial, k, result);
975
+ else if (degree === 2) this.factorQuadratic(polynomial, variable, k, result);
976
+ else if (!this.factorMultivariate(polynomial, variable, k, result))
977
+ this.pushFactor(result, polynomial, k);
978
+ }
979
+
980
+ private pushFactor(result: Factors, polynomial: Polynomial, k: number) {
981
+ result.factors.push(polynomial);
982
+ result.degrees.push(k);
983
+ }
984
+
985
+ // to_numeral_vector: the coefficients of a univariate p by degree. Z3 normalizes p first but
986
+ // reads the coefficients of p itself.
987
+ // to_numeral_vector: a univariate p as its coefficients, low to high.
988
+ toCoeffs(polynomial: Polynomial) {
989
+ const coeffs = Array.from({ length: this.totalDegree(polynomial) + 1 }, () => 0n);
990
+ for (let index = 0; index < polynomial.size; index++)
991
+ coeffs[polynomial.ms[index].totalDegree] = polynomial.as[index];
992
+ return this.um.set(coeffs);
993
+ }
994
+
995
+ // to_polynomial, mk_univariate: the monomials from the highest degree down.
996
+ fromCoeffs(coeffs: readonly bigint[], variable: number) {
997
+ for (let power = coeffs.length - 1; power >= 0; power--)
998
+ this.cheap.add(coeffs[power], this.mkPower(variable, power));
999
+ return this.cheap.mk();
1000
+ }
1001
+
1002
+ // factor_sqf_pp_univ
1003
+ private factorSqfPpUniv(polynomial: Polynomial, k: number, result: Factors) {
1004
+ const variable = this.maxVar(polynomial);
1005
+ const fs: UpolynomialFactors = { constant: 1n, factors: [], degrees: [] };
1006
+ factorSquareFree(this.um, this.toCoeffs(polynomial), fs, 1, DEFAULT_FACTOR_PARAMS);
1007
+ if (fs.factors.length === 1 && fs.degrees[0] === 1) {
1008
+ this.pushFactor(result, polynomial, k);
1009
+ return;
1010
+ }
1011
+ for (let index = 0; index < fs.factors.length; index++)
1012
+ this.pushFactor(result, this.fromCoeffs(fs.factors[index], variable), k * fs.degrees[index]);
1013
+ if (fs.constant === -1n && k % 2 === 1) result.constant = -result.constant;
1014
+ }
1015
+
1016
+ // factor_2_sqf_pp: a*x^2 + b*x + c splits into the primitive parts of 2*a*x + b -/+ sqrt(disc)
1017
+ // when the discriminant b^2 - 4*a*c is a square.
1018
+ private factorQuadratic(polynomial: Polynomial, variable: number, k: number, result: Factors) {
1019
+ let a = this.coeff(polynomial, variable, 2);
1020
+ let b = this.coeff(polynomial, variable, 1);
1021
+ let c = this.coeff(polynomial, variable, 0);
1022
+ const isFlipped = a.as[a.getGradedLexMaxPos()] < 0n;
1023
+ if (isFlipped) {
1024
+ a = this.neg(a);
1025
+ b = this.neg(b);
1026
+ c = this.neg(c);
1027
+ }
1028
+ const root = this.sqrt(this.addmul(1n, this.mul(b, b), -4n, this.mul(a, c)));
1029
+ if (root === null) {
1030
+ this.pushFactor(result, polynomial, k);
1031
+ return;
1032
+ }
1033
+ if (isFlipped && k % 2 === 1) result.constant = -result.constant;
1034
+ const linear = this.add(this.mulTerm(2n, this.mkPower(variable, 1), a), b);
1035
+ this.pushFactor(result, this.pp(this.sub(linear, root), variable), k);
1036
+ this.pushFactor(result, this.pp(this.add(linear, root), variable), k);
1037
+ }
1038
+
1039
+ // is_perfect_square for the monomial at a position: the square root of its coefficient when the
1040
+ // whole term is a square.
1041
+ private getTermSquareRoot(polynomial: Polynomial, position: number) {
1042
+ const monomial = polynomial.ms[position];
1043
+ if (monomial.degrees.some((degree) => degree % 2 === 1)) return null;
1044
+ return getExactSquareRoot(polynomial.as[position]);
1045
+ }
1046
+
1047
+ // sqrt: the square root of p with a positive graded-lex leading coefficient, or null.
1048
+ sqrt(polynomial: Polynomial) {
1049
+ if (polynomial.size === 0) return polynomial;
1050
+ if (this.getTermSquareRoot(polynomial, this.getGradedLexMinPos(polynomial)) === null)
1051
+ return null;
1052
+ const maxPos = polynomial.getGradedLexMaxPos();
1053
+ const a = this.getTermSquareRoot(polynomial, maxPos);
1054
+ if (a === null) return null;
1055
+ const maxMonomial = polynomial.ms[maxPos];
1056
+ const m1 = this.mkMonomial(
1057
+ maxMonomial.vars,
1058
+ maxMonomial.degrees.map((degree) => degree / 2),
1059
+ );
1060
+ const root = this.som;
1061
+ const rest = this.som2;
1062
+ root.reset();
1063
+ rest.reset();
1064
+ const twoA = 2n * a;
1065
+ root.addTerm(a, m1);
1066
+ for (let index = 0; index < polynomial.size; index++)
1067
+ if (index !== maxPos) rest.addTerm(polynomial.as[index], polynomial.ms[index]);
1068
+ while (true) {
1069
+ const restMax = rest.getGradedLexMaxPos();
1070
+ if (restMax === -1) {
1071
+ rest.reset();
1072
+ return root.mk();
1073
+ }
1074
+ const monomial = this.divMonomials(rest.ms[restMax], m1);
1075
+ if (monomial === null || rest.as[restMax] % twoA !== 0n) {
1076
+ root.reset();
1077
+ rest.reset();
1078
+ return null;
1079
+ }
1080
+ const coeff = floorDiv(rest.as[restMax], twoA);
1081
+ const rootSize = root.as.length;
1082
+ for (let index = 0; index < rootSize; index++) {
1083
+ if (root.as[index] === 0n) continue;
1084
+ rest.addTerm(-(root.as[index] * coeff * 2n), this.mulMonomials(root.ms[index], monomial));
1085
+ }
1086
+ rest.addTerm(-(coeff * coeff), this.mulMonomials(monomial, monomial));
1087
+ root.addTerm(coeff, monomial);
1088
+ }
1089
+ }
1090
+
1091
+ // graded_lex_min_pos
1092
+ private getGradedLexMinPos(polynomial: Polynomial) {
1093
+ let minPos = 0;
1094
+ for (let index = 1; index < polynomial.size; index++)
1095
+ if (gradedLexCompare(polynomial.ms[index], polynomial.ms[minPos]) < 0) minPos = index;
1096
+ return minPos;
1097
+ }
1098
+
1099
+ // vars: the variables of p in order of occurrence.
1100
+ // vars: the variables of p in the order they first occur.
1101
+ getVars(polynomial: Polynomial) {
1102
+ const vars: number[] = [];
1103
+ for (const monomial of polynomial.ms)
1104
+ for (const variable of monomial.vars) if (!vars.includes(variable)) vars.push(variable);
1105
+ return vars;
1106
+ }
1107
+
1108
+ // substitute: p with each xs[i] replaced by the integer values[i].
1109
+ substitute(polynomial: Polynomial, vars: readonly number[], values: readonly bigint[]) {
1110
+ this.som.reset();
1111
+ for (let index = 0; index < polynomial.size; index++) {
1112
+ const monomial = polynomial.ms[index];
1113
+ let coeff = polynomial.as[index];
1114
+ const keptVars: number[] = [];
1115
+ const keptDegrees: number[] = [];
1116
+ for (let power = 0; power < monomial.size; power++) {
1117
+ const position = vars.indexOf(monomial.vars[power]);
1118
+ if (position === -1) {
1119
+ keptVars.push(monomial.vars[power]);
1120
+ keptDegrees.push(monomial.degrees[power]);
1121
+ } else coeff *= values[position] ** BigInt(monomial.degrees[power]);
1122
+ }
1123
+ this.som.addTerm(coeff, this.mkMonomial(keptVars, keptDegrees));
1124
+ }
1125
+ return this.som.mk();
1126
+ }
1127
+
1128
+ // translate: p(x + v), by Horner on the coefficients of p in x.
1129
+ translate(polynomial: Polynomial, variable: number, value: bigint) {
1130
+ const degree = this.degree(polynomial, variable);
1131
+ if (degree === 0 || value === 0n) return polynomial;
1132
+ const coeffs = Array.from({ length: degree + 1 }, () => new SomBuffer(this));
1133
+ for (let index = 0; index < polynomial.size; index++) {
1134
+ const monomial = polynomial.ms[index];
1135
+ coeffs[monomial.degreeOf(variable)].addTerm(
1136
+ polynomial.as[index],
1137
+ this.divX(monomial, variable),
1138
+ );
1139
+ }
1140
+ for (let step = 1; step <= degree; step++)
1141
+ for (let power = degree - step; power <= degree - 1; power++)
1142
+ coeffs[power].addmulBuffer(value, this.unit, coeffs[power + 1]);
1143
+ this.som.reset();
1144
+ for (let power = 0; power <= degree; power++)
1145
+ this.som.addmulBuffer(1n, this.mkPower(variable, power), coeffs[power]);
1146
+ return this.som.mk();
1147
+ }
1148
+
1149
+ // substitute(p, x2v): p with the rational values of its assigned variables, each term scaled by
1150
+ // the denominators to the maximal degree of their variable, and the content divided out. p itself
1151
+ // when it has no assigned variable.
1152
+ substituteRational(polynomial: Polynomial, values: readonly (Rational | undefined)[]) {
1153
+ // Map keeps the order in which the variables first occur, as var_max_degree does.
1154
+ const maxDegrees = new Map<number, number>();
1155
+ for (const monomial of polynomial.ms)
1156
+ for (let index = 0; index < monomial.size; index++) {
1157
+ const variable = monomial.vars[index];
1158
+ if (monomial.degrees[index] > (maxDegrees.get(variable) ?? 0))
1159
+ maxDegrees.set(variable, monomial.degrees[index]);
1160
+ }
1161
+ if (![...maxDegrees.keys()].some((variable) => values[variable] !== undefined))
1162
+ return polynomial;
1163
+ this.som.reset();
1164
+ for (let index = 0; index < polynomial.size; index++) {
1165
+ const monomial = polynomial.ms[index];
1166
+ let coeff = polynomial.as[index];
1167
+ const keptVars: number[] = [];
1168
+ const keptDegrees: number[] = [];
1169
+ for (let power = 0; power < monomial.size; power++) {
1170
+ const variable = monomial.vars[power];
1171
+ const degree = monomial.degrees[power];
1172
+ const value = values[variable];
1173
+ if (value === undefined) {
1174
+ keptVars.push(variable);
1175
+ keptDegrees.push(degree);
1176
+ continue;
1177
+ }
1178
+ coeff *= value.num ** BigInt(degree);
1179
+ const maxDegree = maxDegrees.get(variable) ?? 0;
1180
+ if (degree < maxDegree) coeff *= value.den ** BigInt(maxDegree - degree);
1181
+ }
1182
+ for (const [variable, maxDegree] of maxDegrees) {
1183
+ const value = values[variable];
1184
+ if (value !== undefined && monomial.degreeOf(variable) === 0)
1185
+ coeff *= value.den ** BigInt(maxDegree);
1186
+ }
1187
+ this.som.addTerm(coeff, this.mkMonomial(keptVars, keptDegrees));
1188
+ }
1189
+ return this.som.mk(true);
1190
+ }
1191
+
1192
+ // muladd: p*q + a.
1193
+ private muladd(first: Polynomial, second: Polynomial, constant: bigint) {
1194
+ if (first.size === 0 || second.size === 0) return this.mkConst(constant);
1195
+ this.som.reset();
1196
+ for (let index = 0; index < first.size; index++)
1197
+ this.som.addmul(first.as[index], first.ms[index], second);
1198
+ this.som.addTerm(constant, this.unit);
1199
+ return this.som.mk();
1200
+ }
1201
+
1202
+ // compose: p(q) for a univariate p, by Horner.
1203
+ private compose(polynomial: Polynomial, inner: Polynomial) {
1204
+ if (this.isConst(polynomial)) return polynomial;
1205
+ const variable = this.maxVar(polynomial);
1206
+ const degree = this.degree(polynomial, variable);
1207
+ const coeffs = Array.from({ length: degree + 1 }, () => 0n);
1208
+ for (let index = 0; index < polynomial.size; index++)
1209
+ coeffs[polynomial.ms[index].degreeOf(variable)] = polynomial.as[index];
1210
+ let result = this.mkConst(coeffs[degree]);
1211
+ for (let power = degree - 1; power >= 0; power--)
1212
+ result = this.muladd(inner, result, coeffs[power]);
1213
+ return result;
1214
+ }
1215
+
1216
+ // compose_x_minus_y: p(x - y) for a univariate p in x.
1217
+ composeXMinusY(polynomial: Polynomial, variable: number) {
1218
+ const x = this.maxVar(polynomial);
1219
+ if (variable === x) return this.coeff(polynomial, x, 0);
1220
+ return this.compose(polynomial, this.mkLinear([1n, -1n], [x, variable], 0n));
1221
+ }
1222
+
1223
+ // compose_x_div_y: y^n * p(x/y) for a univariate p in x of degree n.
1224
+ composeXDivY(polynomial: Polynomial, variable: number) {
1225
+ if (this.isConst(polynomial)) return polynomial;
1226
+ const x = this.maxVar(polynomial);
1227
+ const degree = this.degree(polynomial, x);
1228
+ for (let index = 0; index < polynomial.size; index++) {
1229
+ const power = polynomial.ms[index].degreeOf(x);
1230
+ const powers: [number, number][] =
1231
+ x < variable
1232
+ ? [
1233
+ [x, power],
1234
+ [variable, degree - power],
1235
+ ]
1236
+ : [
1237
+ [variable, degree - power],
1238
+ [x, power],
1239
+ ];
1240
+ const kept = powers.filter((entry) => entry[1] > 0);
1241
+ this.cheap.add(
1242
+ polynomial.as[index],
1243
+ this.mkMonomial(
1244
+ kept.map((entry) => entry[0]),
1245
+ kept.map((entry) => entry[1]),
1246
+ ),
1247
+ );
1248
+ }
1249
+ return this.cheap.mk();
1250
+ }
1251
+
1252
+ // resultant: Res(p, q) in x, by the subresultant PRS on the primitive parts, times the contents.
1253
+ resultant(first: Polynomial, second: Polynomial, variable: number) {
1254
+ if (first.size === 0 || second.size === 0) return this.zero;
1255
+ if (this.isConst(first))
1256
+ return this.isConst(second) ? this.one : this.pw(first, this.degree(second, variable));
1257
+ if (this.isConst(second)) return this.pw(second, this.degree(first, variable));
1258
+ const [integerA, contentA, ppA] = this.iccp(first, variable);
1259
+ const [integerB, contentB, ppB] = this.iccp(second, variable);
1260
+ const scale = this.mul(
1261
+ this.pw(this.mulConst(integerA, contentA), this.degree(second, variable)),
1262
+ this.pw(this.mulConst(integerB, contentB), this.degree(first, variable)),
1263
+ );
1264
+ let a = ppA;
1265
+ let b = ppB;
1266
+ let sign = 1;
1267
+ if (this.degree(a, variable) < this.degree(b, variable)) {
1268
+ if (this.degree(a, variable) % 2 === 1 && this.degree(b, variable) % 2 === 1) sign = -1;
1269
+ [a, b] = [b, a];
1270
+ }
1271
+ let g = this.one;
1272
+ let h = this.one;
1273
+ while (true) {
1274
+ const degreeA = this.degree(a, variable);
1275
+ const degreeB = this.degree(b, variable);
1276
+ const delta = degreeA - degreeB;
1277
+ if (degreeA % 2 === 1 && degreeB % 2 === 1) sign = -sign;
1278
+ const remainder = this.exactPseudoRemainder(a, b, variable);
1279
+ a = b;
1280
+ b = this.exactDiv(remainder, g);
1281
+ for (let index = 0; index < delta; index++) b = this.exactDiv(b, h);
1282
+ g = this.lc(a, variable);
1283
+ let nextH = this.pw(g, delta);
1284
+ for (let index = 1; index < delta; index++) nextH = this.exactDiv(nextH, h);
1285
+ h = nextH;
1286
+ if (this.degree(b, variable) === 0) {
1287
+ const degree = this.degree(a, variable);
1288
+ let lastH = this.pw(this.lc(b, variable), degree);
1289
+ for (let index = 1; index < degree; index++) lastH = this.exactDiv(lastH, h);
1290
+ const result = this.mul(scale, lastH);
1291
+ return sign < 0 ? this.neg(result) : result;
1292
+ }
1293
+ }
1294
+ }
1295
+
1296
+ private isSquareFreeIn(polynomial: Polynomial, variable: number) {
1297
+ if (this.isConst(polynomial)) return polynomial.size > 0;
1298
+ return this.isConst(this.gcd(polynomial, this.derivative(polynomial, variable)));
1299
+ }
1300
+
1301
+ private isPrimitive(polynomial: Polynomial, variable: number) {
1302
+ return this.eq(polynomial, this.pp(polynomial, variable));
1303
+ }
1304
+
1305
+ // factor_n_sqf_pp, try_multivar_factor: reduces p to two variables by evaluating the others,
1306
+ // factors it at a point of the lifting variable, lifts a split of the univariate factors with
1307
+ // Hensel's lemma and keeps it when the lifted factors multiply back to p. Returns false when no
1308
+ // split lifts, leaving p unfactored.
1309
+ private factorMultivariate(polynomial: Polynomial, x: number, k: number, result: Factors) {
1310
+ const allVars = this.getVars(polynomial);
1311
+ const mainVars = [
1312
+ x,
1313
+ ...allVars
1314
+ .filter((variable) => variable !== x)
1315
+ .map((variable) => [this.degree(polynomial, variable), variable])
1316
+ .sort((first, second) => second[0] - first[0] || second[1] - first[1])
1317
+ .filter((entry) => entry[0] > 1)
1318
+ .map((entry) => entry[1]),
1319
+ ];
1320
+ for (const mainVar of mainVars) {
1321
+ const degMain = this.degree(polynomial, mainVar);
1322
+ if (degMain <= 1) continue;
1323
+ for (const liftVar of allVars) {
1324
+ if (liftVar === mainVar) continue;
1325
+ const evalVars = allVars.filter((variable) => variable !== mainVar && variable !== liftVar);
1326
+ const maxCombos = evalVars.length === 0 ? 1 : 5;
1327
+ for (let combo = 0; combo < maxCombos; combo++) {
1328
+ const bivariate =
1329
+ evalVars.length === 0
1330
+ ? polynomial
1331
+ : this.substitute(
1332
+ polynomial,
1333
+ evalVars,
1334
+ evalVars.map(
1335
+ (_variable, index) =>
1336
+ FACTOR_EVAL_VALUES[
1337
+ Math.floor(combo / FACTOR_EVAL_VALUES.length ** index) %
1338
+ FACTOR_EVAL_VALUES.length
1339
+ ],
1340
+ ),
1341
+ );
1342
+ if (this.degree(bivariate, mainVar) !== degMain) continue;
1343
+ const degLift = this.degree(bivariate, liftVar);
1344
+ if (degLift === 0) continue;
1345
+ for (const point of FACTOR_EVAL_VALUES) {
1346
+ const univariate = this.substitute(bivariate, [liftVar], [point]);
1347
+ if (!this.isUnivariate(univariate)) continue;
1348
+ if (this.degree(univariate, mainVar) !== degMain) continue;
1349
+ if (!this.isSquareFreeIn(univariate, mainVar)) continue;
1350
+ const univariateFs: UpolynomialFactors = { constant: 1n, factors: [], degrees: [] };
1351
+ factorSquareFree(
1352
+ this.um,
1353
+ this.um.getPrimitive(this.toCoeffs(univariate)),
1354
+ univariateFs,
1355
+ 1,
1356
+ DEFAULT_FACTOR_PARAMS,
1357
+ );
1358
+ const factorCount = univariateFs.factors.length;
1359
+ if (factorCount <= 1) continue;
1360
+ const translated = this.translate(bivariate, liftVar, point);
1361
+ const lcPolynomial = this.coeff(translated, mainVar, degMain);
1362
+ const lcAtZero = this.isConst(lcPolynomial)
1363
+ ? (lcPolynomial.as[0] ?? 0n)
1364
+ : this.getConstValue(this.substitute(lcPolynomial, [liftVar], [0n]));
1365
+ if (lcAtZero === null) continue;
1366
+ for (const prime of FACTOR_PRIMES) {
1367
+ if (getGcd(prime, lcAtZero) !== 1n) continue;
1368
+ for (let split = 1; split <= Math.floor(factorCount / 2); split++) {
1369
+ let h1 = univariateFs.factors[0];
1370
+ for (let index = 1; index < split; index++)
1371
+ h1 = this.um.mul(h1, univariateFs.factors[index]);
1372
+ let h2 = univariateFs.factors[split];
1373
+ for (let index = split + 1; index < factorCount; index++)
1374
+ h2 = this.um.mul(h2, univariateFs.factors[index]);
1375
+ const lifted = this.liftBivariate(
1376
+ translated,
1377
+ mainVar,
1378
+ liftVar,
1379
+ degLift,
1380
+ this.um.flipSignIfLmNeg(h1),
1381
+ this.um.flipSignIfLmNeg(h2),
1382
+ lcAtZero,
1383
+ prime,
1384
+ );
1385
+ if (lifted === null) continue;
1386
+ const candidates = lifted.map((factor) => this.translate(factor, liftVar, -point));
1387
+ if (evalVars.length === 0) {
1388
+ for (const candidate of candidates) {
1389
+ if (this.isConst(candidate) || this.degree(candidate, x) === 0) continue;
1390
+ this.pushSmallFactor(candidate, x, k, result);
1391
+ }
1392
+ return true;
1393
+ }
1394
+ for (const candidate of candidates) {
1395
+ if (this.isConst(candidate)) continue;
1396
+ const division = this.exactPseudoDivision(
1397
+ polynomial,
1398
+ candidate,
1399
+ this.maxVar(candidate),
1400
+ );
1401
+ if (division.remainder.size !== 0) continue;
1402
+ if (!this.eq(this.mul(candidate, division.quotient), polynomial)) continue;
1403
+ for (const part of [candidate, division.quotient]) {
1404
+ if (this.isConst(part)) result.constant *= part.as[0];
1405
+ else if (this.degree(part, x) !== 0) this.pushSmallFactor(part, x, k, result);
1406
+ }
1407
+ return true;
1408
+ }
1409
+ }
1410
+ }
1411
+ }
1412
+ }
1413
+ }
1414
+ }
1415
+ return false;
1416
+ }
1417
+
1418
+ // The factors of a lifted part, splitting only linear and quadratic ones further.
1419
+ private pushSmallFactor(polynomial: Polynomial, x: number, k: number, result: Factors) {
1420
+ const degree = this.degree(polynomial, x);
1421
+ if (degree === 2 && this.isPrimitive(polynomial, x) && this.isSquareFreeIn(polynomial, x))
1422
+ this.factorQuadratic(polynomial, x, k, result);
1423
+ else this.pushFactor(result, polynomial, k);
1424
+ }
1425
+
1426
+ private getConstValue(polynomial: Polynomial) {
1427
+ if (!this.isConst(polynomial)) return null;
1428
+ return polynomial.as[0] ?? 0n;
1429
+ }
1430
+
1431
+ // try_bivar_hensel_lift: lifts q(x, 0) = lc * h1 * h2 to q = F1 * F2 in Z_p[x][y] by linear
1432
+ // Hensel lifting on the coefficients of y, then reads F1 and F2 back over Z. Null when h1 and h2
1433
+ // are not coprime in Z_p, q is not bivariate, or the product of the lifted factors is not q.
1434
+ private liftBivariate(
1435
+ q: Polynomial,
1436
+ x: number,
1437
+ y: number,
1438
+ degY: number,
1439
+ h1: readonly bigint[],
1440
+ h2: readonly bigint[],
1441
+ lc: bigint,
1442
+ prime: bigint,
1443
+ ) {
1444
+ const zp = new UpolynomialManager(prime);
1445
+ const f1 = zp.mkMonic(zp.set(h1));
1446
+ const f2 = zp.mkMonic(zp.set(h2));
1447
+ const ext = zp.extGcd(f1, f2);
1448
+ if (ext.d.length !== 1 || ext.d[0] !== 1n) return null;
1449
+ const qCoeffs: bigint[][] = [];
1450
+ for (let power = 0; power <= degY; power++) {
1451
+ const coeff = this.coeff(q, y, power);
1452
+ if (coeff.size !== 0 && !this.isUnivariate(coeff) && !this.isConst(coeff)) return null;
1453
+ qCoeffs.push(zp.set(coeff.size === 0 ? [] : this.toCoeffs(coeff)));
1454
+ }
1455
+ const f1Coeffs: bigint[][] = Array.from({ length: degY + 1 }, () => []);
1456
+ const f2Coeffs: bigint[][] = Array.from({ length: degY + 1 }, () => []);
1457
+ f1Coeffs[0] = zp.set(f1);
1458
+ f2Coeffs[0] = zp.mulConst(f2, zp.normalizeNumeral(lc));
1459
+ const lcInv = zp.inv(lc);
1460
+ for (let power = 1; power <= degY; power++) {
1461
+ let error = zp.set(qCoeffs[power]);
1462
+ for (let first = 0; first <= power; first++) {
1463
+ const second = power - first;
1464
+ if (second > degY || second === 0 || first === 0) continue;
1465
+ if (f1Coeffs[first].length === 0 || f2Coeffs[second].length === 0) continue;
1466
+ error = zp.sub(error, zp.mul(f1Coeffs[first], f2Coeffs[second]));
1467
+ }
1468
+ if (error.length === 0) continue;
1469
+ const a = zp.divRem(zp.mul(error, ext.v), f1).remainder;
1470
+ const b = zp.divRem(zp.mul(error, ext.u), f2).remainder;
1471
+ f1Coeffs[power] = zp.mulConst(a, lcInv);
1472
+ f2Coeffs[power] = zp.set(b);
1473
+ }
1474
+ const toPolynomial = (coeffs: readonly bigint[][]) => {
1475
+ let result = this.zero;
1476
+ for (let power = 0; power <= degY; power++) {
1477
+ if (coeffs[power].length === 0) continue;
1478
+ const univariate = this.fromCoeffs(coeffs[power], x);
1479
+ if (univariate.size === 0) continue;
1480
+ result = this.add(result, this.mulTerm(1n, this.mkPower(y, power), univariate));
1481
+ }
1482
+ return result;
1483
+ };
1484
+ const first = toPolynomial(f1Coeffs);
1485
+ const second = toPolynomial(f2Coeffs);
1486
+ return this.eq(this.mul(first, second), q) ? [first, second] : null;
1487
+ }
1488
+
1489
+ // psc_chain: the nonzero principal subresultant coefficients of p and q in x, the resultant
1490
+ // first, or [0] when there are none. psc_chain_optimized: Ducos's subresultant chain with
1491
+ // Lazard's dichotomous S_e.
1492
+ pscChain(first: Polynomial, second: Polynomial, variable: number) {
1493
+ const chain =
1494
+ this.degree(first, variable) >= this.degree(second, variable)
1495
+ ? this.pscChainCore(first, second, variable)
1496
+ : this.pscChainCore(second, first, variable);
1497
+ return chain.length === 0 ? [this.zero] : chain.reverse();
1498
+ }
1499
+
1500
+ private pscChainCore(p: Polynomial, q: Polynomial, x: number) {
1501
+ const chain: Polynomial[] = [];
1502
+ let s = this.pw(this.lc(q, x), this.degree(p, x) - this.degree(q, x));
1503
+ let a = q;
1504
+ let b = this.exactPseudoRemainder(p, this.neg(q), x);
1505
+ while (b.size > 0) {
1506
+ const d = this.degree(a, x);
1507
+ const e = this.degree(b, x);
1508
+ // b is S_{d-1}.
1509
+ const principal = this.coeff(b, x, d - 1);
1510
+ if (principal.size > 0) chain.push(principal);
1511
+ let c = b;
1512
+ if (d - e > 1) {
1513
+ c = this.getSeLazard(d, s, b, x);
1514
+ const principalE = this.coeff(c, x, e);
1515
+ if (principalE.size > 0) chain.push(principalE);
1516
+ }
1517
+ if (e === 0) break;
1518
+ b = this.getOptimizedSe1(d, e, a, b, c, s, x);
1519
+ a = c;
1520
+ s = this.lc(a, x);
1521
+ }
1522
+ return chain;
1523
+ }
1524
+
1525
+ // Se_Lazard: S_e from S_{d-1} and lc(S_d) by dichotomous Lazard.
1526
+ private getSeLazard(d: number, lcSd: Polynomial, sd1: Polynomial, x: number) {
1527
+ let n = d - this.degree(sd1, x) - 1;
1528
+ if (n === 0) return sd1;
1529
+ const lcSd1 = this.lc(sd1, x);
1530
+ let a = 1 << (31 - Math.clz32(n));
1531
+ let c = lcSd1;
1532
+ n -= a;
1533
+ while (a !== 1) {
1534
+ a /= 2;
1535
+ c = this.exactDiv(this.mul(c, c), lcSd);
1536
+ if (n >= a) {
1537
+ c = this.exactDiv(this.mul(c, lcSd1), lcSd);
1538
+ n -= a;
1539
+ }
1540
+ }
1541
+ return this.exactDiv(this.mul(c, sd1), lcSd);
1542
+ }
1543
+
1544
+ // optimized_S_e_1: S_{e-1} from A = S_{d+1}, S_{d-1}, S_e and s = lc(S_d).
1545
+ private getOptimizedSe1(
1546
+ d: number,
1547
+ e: number,
1548
+ a: Polynomial,
1549
+ sd1: Polynomial,
1550
+ se: Polynomial,
1551
+ s: Polynomial,
1552
+ x: number,
1553
+ ) {
1554
+ const cd1 = this.lc(sd1, x);
1555
+ const lcSe = this.lc(se, x);
1556
+ const getPower = (power: number) => (power === 0 ? this.one : this.mkVar(x, power));
1557
+ const h: Polynomial[] = [];
1558
+ for (let j = 0; j < e; j++) h.push(this.mul(lcSe, getPower(j)));
1559
+ h.push(this.sub(this.mul(lcSe, getPower(e)), se));
1560
+ const xPolynomial = this.mkVar(x);
1561
+ for (let j = e + 1; j < d; j++) {
1562
+ const xh = this.mul(xPolynomial, h[j - 1]);
1563
+ h.push(this.sub(xh, this.exactDiv(this.mul(this.coeff(xh, x, e), sd1), cd1)));
1564
+ }
1565
+ let sum = this.zero;
1566
+ for (let j = 0; j < d; j++) sum = this.add(sum, this.mul(this.coeff(a, x, j), h[j]));
1567
+ const dPolynomial = this.exactDiv(sum, this.lc(a, x));
1568
+ const xh = this.mul(xPolynomial, h[d - 1]);
1569
+ const result = this.exactDiv(
1570
+ this.sub(this.mul(cd1, this.add(xh, dPolynomial)), this.mul(this.coeff(xh, x, e), sd1)),
1571
+ s,
1572
+ );
1573
+ return (d - e + 1) % 2 === 1 ? this.neg(result) : result;
1574
+ }
1575
+
1576
+ // Evaluation.
1577
+
1578
+ // t_eval: p at the values of its variables, by Horner on the lexicographically sorted monomials,
1579
+ // which sorts p in place as Z3 does.
1580
+ evaluateWith<T>(polynomial: Polynomial, ops: ValueOps<T>, getValue: (variable: number) => T) {
1581
+ if (polynomial.size === 0) return ops.fromInteger(0n);
1582
+ if (this.isConst(polynomial)) return ops.fromInteger(polynomial.as[0]);
1583
+ polynomial.lexSort();
1584
+ return this.evaluateCore(
1585
+ polynomial,
1586
+ ops,
1587
+ getValue,
1588
+ 0,
1589
+ polynomial.size,
1590
+ this.maxVar(polynomial),
1591
+ );
1592
+ }
1593
+
1594
+ // t_eval_core: the monomials in [start, end), ignoring the variables above x.
1595
+ private evaluateCore<T>(
1596
+ polynomial: Polynomial,
1597
+ ops: ValueOps<T>,
1598
+ getValue: (variable: number) => T,
1599
+ start: number,
1600
+ end: number,
1601
+ x: number,
1602
+ ): T {
1603
+ if (end === start + 1) {
1604
+ let result = ops.fromInteger(polynomial.as[start]);
1605
+ const monomial = polynomial.ms[start];
1606
+ for (let index = 0; index < monomial.size; index++) {
1607
+ const variable = monomial.vars[index];
1608
+ if (variable > x) break;
1609
+ result = ops.mul(result, ops.power(getValue(variable), monomial.degrees[index]));
1610
+ }
1611
+ return result;
1612
+ }
1613
+ const value = getValue(x);
1614
+ let result = ops.fromInteger(0n);
1615
+ let index = start;
1616
+ while (index < end) {
1617
+ const degree = polynomial.ms[index].degreeOf(x);
1618
+ if (degree === 0) {
1619
+ const below = this.maxSmallerThan(polynomial, index, end, x);
1620
+ result = ops.add(
1621
+ result,
1622
+ below === NULL_VAR
1623
+ ? ops.fromInteger(polynomial.as[index])
1624
+ : this.evaluateCore(polynomial, ops, getValue, index, end, below),
1625
+ );
1626
+ break;
1627
+ }
1628
+ let next = index + 1;
1629
+ let nextDegree = 0;
1630
+ for (; next < end; next++) {
1631
+ const current = polynomial.ms[next].degreeOf(x);
1632
+ if (current < degree) {
1633
+ nextDegree = current;
1634
+ break;
1635
+ }
1636
+ }
1637
+ const below = this.maxSmallerThan(polynomial, index, next, x);
1638
+ result = ops.add(
1639
+ result,
1640
+ below === NULL_VAR
1641
+ ? ops.fromInteger(polynomial.as[index])
1642
+ : this.evaluateCore(polynomial, ops, getValue, index, next, below),
1643
+ );
1644
+ result = ops.mul(result, ops.power(value, degree - nextDegree));
1645
+ index = next;
1646
+ }
1647
+ return result;
1648
+ }
1649
+
1650
+ // max_smaller_than: the largest variable below x in the monomials in [start, end).
1651
+ private maxSmallerThan(polynomial: Polynomial, start: number, end: number, x: number) {
1652
+ let max = NULL_VAR;
1653
+ for (let index = start; index < end; index++)
1654
+ max = Math.max(max, polynomial.ms[index].maxSmallerThan(x));
1655
+ return max;
1656
+ }
1657
+
1658
+ evaluate(polynomial: Polynomial, values: readonly (Rational | undefined)[]) {
1659
+ return this.evaluateWith(polynomial, RATIONAL_OPS, (variable) => {
1660
+ const value = values[variable];
1661
+ if (value === undefined) throw new SmtInvariantError(`x${variable} is unassigned`);
1662
+ return value;
1663
+ });
1664
+ }
1665
+
1666
+ getSign(polynomial: Polynomial, values: readonly (Rational | undefined)[]) {
1667
+ const value = this.evaluate(polynomial, values);
1668
+ return value.isZero() ? 0 : value.isPositive() ? 1 : -1;
1669
+ }
1670
+ }
1671
+
1672
+ // polynomial::cache: hash-conses polynomials and memoizes their subresultants and factors.
1673
+ export class PolynomialCache {
1674
+ private table = new Map<string, Polynomial>();
1675
+ private inCache = new Set<number>();
1676
+ private pscChains = new Map<string, Polynomial[]>();
1677
+ private factorizations = new Map<number, Polynomial[]>();
1678
+
1679
+ constructor(readonly pm: PolynomialManager) {}
1680
+
1681
+ reset() {
1682
+ this.table.clear();
1683
+ this.inCache.clear();
1684
+ this.pscChains.clear();
1685
+ this.factorizations.clear();
1686
+ }
1687
+
1688
+ mkUnique(polynomial: Polynomial) {
1689
+ if (this.inCache.has(polynomial.id)) return polynomial;
1690
+ const key = this.pm.getKey(polynomial);
1691
+ const existing = this.table.get(key);
1692
+ if (existing !== undefined) return existing;
1693
+ this.table.set(key, polynomial);
1694
+ this.inCache.add(polynomial.id);
1695
+ return polynomial;
1696
+ }
1697
+
1698
+ contains(polynomial: Polynomial) {
1699
+ return this.inCache.has(polynomial.id);
1700
+ }
1701
+
1702
+ pscChain(first: Polynomial, second: Polynomial, variable: number) {
1703
+ const p = this.mkUnique(first);
1704
+ const q = this.mkUnique(second);
1705
+ const key = `${p.id},${q.id},${variable}`;
1706
+ const cached = this.pscChains.get(key);
1707
+ if (cached !== undefined) return cached;
1708
+ const chain = this.pm.pscChain(p, q, variable).map((element) => this.mkUnique(element));
1709
+ this.pscChains.set(key, chain);
1710
+ return chain;
1711
+ }
1712
+
1713
+ // factor: the distinct factors, without the constant.
1714
+ factor(polynomial: Polynomial) {
1715
+ const unique = this.mkUnique(polynomial);
1716
+ const cached = this.factorizations.get(unique.id);
1717
+ if (cached !== undefined) return cached;
1718
+ const factors = this.pm.factor(unique).factors.map((factor) => this.mkUnique(factor));
1719
+ this.factorizations.set(unique.id, factors);
1720
+ return factors;
1721
+ }
1722
+ }