m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

422 lines
13 KiB

6 months ago
  1. import tempfile
  2. from sympy.core.numbers import pi
  3. from sympy.core.power import Pow
  4. from sympy.core.singleton import S
  5. from sympy.core.symbol import Symbol
  6. from sympy.functions.elementary.complexes import Abs
  7. from sympy.functions.elementary.exponential import (exp, log)
  8. from sympy.functions.elementary.trigonometric import (cos, sin, sinc)
  9. from sympy.matrices.expressions.matexpr import MatrixSymbol
  10. from sympy.assumptions import assuming, Q
  11. from sympy.external import import_module
  12. from sympy.printing.codeprinter import ccode
  13. from sympy.codegen.matrix_nodes import MatrixSolve
  14. from sympy.codegen.cfunctions import log2, exp2, expm1, log1p
  15. from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
  16. from sympy.codegen.scipy_nodes import cosm1
  17. from sympy.codegen.rewriting import (
  18. optimize, cosm1_opt, log2_opt, exp2_opt, expm1_opt, log1p_opt, optims_c99,
  19. create_expand_pow_optimization, matinv_opt, logaddexp_opt, logaddexp2_opt,
  20. optims_numpy, sinc_opts, FuncMinusOneOptim
  21. )
  22. from sympy.testing.pytest import XFAIL, skip
  23. from sympy.utilities._compilation import compile_link_import_strings, has_c
  24. from sympy.utilities._compilation.util import may_xfail
  25. cython = import_module('cython')
  26. def test_log2_opt():
  27. x = Symbol('x')
  28. expr1 = 7*log(3*x + 5)/(log(2))
  29. opt1 = optimize(expr1, [log2_opt])
  30. assert opt1 == 7*log2(3*x + 5)
  31. assert opt1.rewrite(log) == expr1
  32. expr2 = 3*log(5*x + 7)/(13*log(2))
  33. opt2 = optimize(expr2, [log2_opt])
  34. assert opt2 == 3*log2(5*x + 7)/13
  35. assert opt2.rewrite(log) == expr2
  36. expr3 = log(x)/log(2)
  37. opt3 = optimize(expr3, [log2_opt])
  38. assert opt3 == log2(x)
  39. assert opt3.rewrite(log) == expr3
  40. expr4 = log(x)/log(2) + log(x+1)
  41. opt4 = optimize(expr4, [log2_opt])
  42. assert opt4 == log2(x) + log(2)*log2(x+1)
  43. assert opt4.rewrite(log) == expr4
  44. expr5 = log(17)
  45. opt5 = optimize(expr5, [log2_opt])
  46. assert opt5 == expr5
  47. expr6 = log(x + 3)/log(2)
  48. opt6 = optimize(expr6, [log2_opt])
  49. assert str(opt6) == 'log2(x + 3)'
  50. assert opt6.rewrite(log) == expr6
  51. def test_exp2_opt():
  52. x = Symbol('x')
  53. expr1 = 1 + 2**x
  54. opt1 = optimize(expr1, [exp2_opt])
  55. assert opt1 == 1 + exp2(x)
  56. assert opt1.rewrite(Pow) == expr1
  57. expr2 = 1 + 3**x
  58. assert expr2 == optimize(expr2, [exp2_opt])
  59. def test_expm1_opt():
  60. x = Symbol('x')
  61. expr1 = exp(x) - 1
  62. opt1 = optimize(expr1, [expm1_opt])
  63. assert expm1(x) - opt1 == 0
  64. assert opt1.rewrite(exp) == expr1
  65. expr2 = 3*exp(x) - 3
  66. opt2 = optimize(expr2, [expm1_opt])
  67. assert 3*expm1(x) == opt2
  68. assert opt2.rewrite(exp) == expr2
  69. expr3 = 3*exp(x) - 5
  70. opt3 = optimize(expr3, [expm1_opt])
  71. assert 3*expm1(x) - 2 == opt3
  72. assert opt3.rewrite(exp) == expr3
  73. expm1_opt_non_opportunistic = FuncMinusOneOptim(exp, expm1, opportunistic=False)
  74. assert expr3 == optimize(expr3, [expm1_opt_non_opportunistic])
  75. assert opt1 == optimize(expr1, [expm1_opt_non_opportunistic])
  76. assert opt2 == optimize(expr2, [expm1_opt_non_opportunistic])
  77. expr4 = 3*exp(x) + log(x) - 3
  78. opt4 = optimize(expr4, [expm1_opt])
  79. assert 3*expm1(x) + log(x) == opt4
  80. assert opt4.rewrite(exp) == expr4
  81. expr5 = 3*exp(2*x) - 3
  82. opt5 = optimize(expr5, [expm1_opt])
  83. assert 3*expm1(2*x) == opt5
  84. assert opt5.rewrite(exp) == expr5
  85. expr6 = (2*exp(x) + 1)/(exp(x) + 1) + 1
  86. opt6 = optimize(expr6, [expm1_opt])
  87. assert opt6.count_ops() <= expr6.count_ops()
  88. def ev(e):
  89. return e.subs(x, 3).evalf()
  90. assert abs(ev(expr6) - ev(opt6)) < 1e-15
  91. y = Symbol('y')
  92. expr7 = (2*exp(x) - 1)/(1 - exp(y)) - 1/(1-exp(y))
  93. opt7 = optimize(expr7, [expm1_opt])
  94. assert -2*expm1(x)/expm1(y) == opt7
  95. assert (opt7.rewrite(exp) - expr7).factor() == 0
  96. expr8 = (1+exp(x))**2 - 4
  97. opt8 = optimize(expr8, [expm1_opt])
  98. tgt8a = (exp(x) + 3)*expm1(x)
  99. tgt8b = 2*expm1(x) + expm1(2*x)
  100. # Both tgt8a & tgt8b seem to give full precision (~16 digits for double)
  101. # for x=1e-7 (compare with expr8 which only achieves ~8 significant digits).
  102. # If we can show that either tgt8a or tgt8b is preferable, we can
  103. # change this test to ensure the preferable version is returned.
  104. assert (tgt8a - tgt8b).rewrite(exp).factor() == 0
  105. assert opt8 in (tgt8a, tgt8b)
  106. assert (opt8.rewrite(exp) - expr8).factor() == 0
  107. expr9 = sin(expr8)
  108. opt9 = optimize(expr9, [expm1_opt])
  109. tgt9a = sin(tgt8a)
  110. tgt9b = sin(tgt8b)
  111. assert opt9 in (tgt9a, tgt9b)
  112. assert (opt9.rewrite(exp) - expr9.rewrite(exp)).factor().is_zero
  113. def test_expm1_two_exp_terms():
  114. x, y = map(Symbol, 'x y'.split())
  115. expr1 = exp(x) + exp(y) - 2
  116. opt1 = optimize(expr1, [expm1_opt])
  117. assert opt1 == expm1(x) + expm1(y)
  118. def test_cosm1_opt():
  119. x = Symbol('x')
  120. expr1 = cos(x) - 1
  121. opt1 = optimize(expr1, [cosm1_opt])
  122. assert cosm1(x) - opt1 == 0
  123. assert opt1.rewrite(cos) == expr1
  124. expr2 = 3*cos(x) - 3
  125. opt2 = optimize(expr2, [cosm1_opt])
  126. assert 3*cosm1(x) == opt2
  127. assert opt2.rewrite(cos) == expr2
  128. expr3 = 3*cos(x) - 5
  129. opt3 = optimize(expr3, [cosm1_opt])
  130. assert 3*cosm1(x) - 2 == opt3
  131. assert opt3.rewrite(cos) == expr3
  132. cosm1_opt_non_opportunistic = FuncMinusOneOptim(cos, cosm1, opportunistic=False)
  133. assert expr3 == optimize(expr3, [cosm1_opt_non_opportunistic])
  134. assert opt1 == optimize(expr1, [cosm1_opt_non_opportunistic])
  135. assert opt2 == optimize(expr2, [cosm1_opt_non_opportunistic])
  136. expr4 = 3*cos(x) + log(x) - 3
  137. opt4 = optimize(expr4, [cosm1_opt])
  138. assert 3*cosm1(x) + log(x) == opt4
  139. assert opt4.rewrite(cos) == expr4
  140. expr5 = 3*cos(2*x) - 3
  141. opt5 = optimize(expr5, [cosm1_opt])
  142. assert 3*cosm1(2*x) == opt5
  143. assert opt5.rewrite(cos) == expr5
  144. expr6 = 2 - 2*cos(x)
  145. opt6 = optimize(expr6, [cosm1_opt])
  146. assert -2*cosm1(x) == opt6
  147. assert opt6.rewrite(cos) == expr6
  148. def test_cosm1_two_cos_terms():
  149. x, y = map(Symbol, 'x y'.split())
  150. expr1 = cos(x) + cos(y) - 2
  151. opt1 = optimize(expr1, [cosm1_opt])
  152. assert opt1 == cosm1(x) + cosm1(y)
  153. def test_expm1_cosm1_mixed():
  154. x = Symbol('x')
  155. expr1 = exp(x) + cos(x) - 2
  156. opt1 = optimize(expr1, [expm1_opt, cosm1_opt])
  157. assert opt1 == cosm1(x) + expm1(x)
  158. def test_log1p_opt():
  159. x = Symbol('x')
  160. expr1 = log(x + 1)
  161. opt1 = optimize(expr1, [log1p_opt])
  162. assert log1p(x) - opt1 == 0
  163. assert opt1.rewrite(log) == expr1
  164. expr2 = log(3*x + 3)
  165. opt2 = optimize(expr2, [log1p_opt])
  166. assert log1p(x) + log(3) == opt2
  167. assert (opt2.rewrite(log) - expr2).simplify() == 0
  168. expr3 = log(2*x + 1)
  169. opt3 = optimize(expr3, [log1p_opt])
  170. assert log1p(2*x) - opt3 == 0
  171. assert opt3.rewrite(log) == expr3
  172. expr4 = log(x+3)
  173. opt4 = optimize(expr4, [log1p_opt])
  174. assert str(opt4) == 'log(x + 3)'
  175. def test_optims_c99():
  176. x = Symbol('x')
  177. expr1 = 2**x + log(x)/log(2) + log(x + 1) + exp(x) - 1
  178. opt1 = optimize(expr1, optims_c99).simplify()
  179. assert opt1 == exp2(x) + log2(x) + log1p(x) + expm1(x)
  180. assert opt1.rewrite(exp).rewrite(log).rewrite(Pow) == expr1
  181. expr2 = log(x)/log(2) + log(x + 1)
  182. opt2 = optimize(expr2, optims_c99)
  183. assert opt2 == log2(x) + log1p(x)
  184. assert opt2.rewrite(log) == expr2
  185. expr3 = log(x)/log(2) + log(17*x + 17)
  186. opt3 = optimize(expr3, optims_c99)
  187. delta3 = opt3 - (log2(x) + log(17) + log1p(x))
  188. assert delta3 == 0
  189. assert (opt3.rewrite(log) - expr3).simplify() == 0
  190. expr4 = 2**x + 3*log(5*x + 7)/(13*log(2)) + 11*exp(x) - 11 + log(17*x + 17)
  191. opt4 = optimize(expr4, optims_c99).simplify()
  192. delta4 = opt4 - (exp2(x) + 3*log2(5*x + 7)/13 + 11*expm1(x) + log(17) + log1p(x))
  193. assert delta4 == 0
  194. assert (opt4.rewrite(exp).rewrite(log).rewrite(Pow) - expr4).simplify() == 0
  195. expr5 = 3*exp(2*x) - 3
  196. opt5 = optimize(expr5, optims_c99)
  197. delta5 = opt5 - 3*expm1(2*x)
  198. assert delta5 == 0
  199. assert opt5.rewrite(exp) == expr5
  200. expr6 = exp(2*x) - 3
  201. opt6 = optimize(expr6, optims_c99)
  202. assert opt6 in (expm1(2*x) - 2, expr6) # expm1(2*x) - 2 is not better or worse
  203. expr7 = log(3*x + 3)
  204. opt7 = optimize(expr7, optims_c99)
  205. delta7 = opt7 - (log(3) + log1p(x))
  206. assert delta7 == 0
  207. assert (opt7.rewrite(log) - expr7).simplify() == 0
  208. expr8 = log(2*x + 3)
  209. opt8 = optimize(expr8, optims_c99)
  210. assert opt8 == expr8
  211. def test_create_expand_pow_optimization():
  212. cc = lambda x: ccode(
  213. optimize(x, [create_expand_pow_optimization(4)]))
  214. x = Symbol('x')
  215. assert cc(x**4) == 'x*x*x*x'
  216. assert cc(x**4 + x**2) == 'x*x + x*x*x*x'
  217. assert cc(x**5 + x**4) == 'pow(x, 5) + x*x*x*x'
  218. assert cc(sin(x)**4) == 'pow(sin(x), 4)'
  219. # gh issue 15335
  220. assert cc(x**(-4)) == '1.0/(x*x*x*x)'
  221. assert cc(x**(-5)) == 'pow(x, -5)'
  222. assert cc(-x**4) == '-(x*x*x*x)'
  223. assert cc(x**4 - x**2) == '-(x*x) + x*x*x*x'
  224. i = Symbol('i', integer=True)
  225. assert cc(x**i - x**2) == 'pow(x, i) - (x*x)'
  226. y = Symbol('y', real=True)
  227. assert cc(Abs(exp(y**4))) == "exp(y*y*y*y)"
  228. # gh issue 20753
  229. cc2 = lambda x: ccode(optimize(x, [create_expand_pow_optimization(
  230. 4, base_req=lambda b: b.is_Function)]))
  231. assert cc2(x**3 + sin(x)**3) == "pow(x, 3) + sin(x)*sin(x)*sin(x)"
  232. def test_matsolve():
  233. n = Symbol('n', integer=True)
  234. A = MatrixSymbol('A', n, n)
  235. x = MatrixSymbol('x', n, 1)
  236. with assuming(Q.fullrank(A)):
  237. assert optimize(A**(-1) * x, [matinv_opt]) == MatrixSolve(A, x)
  238. assert optimize(A**(-1) * x + x, [matinv_opt]) == MatrixSolve(A, x) + x
  239. def test_logaddexp_opt():
  240. x, y = map(Symbol, 'x y'.split())
  241. expr1 = log(exp(x) + exp(y))
  242. opt1 = optimize(expr1, [logaddexp_opt])
  243. assert logaddexp(x, y) - opt1 == 0
  244. assert logaddexp(y, x) - opt1 == 0
  245. assert opt1.rewrite(log) == expr1
  246. def test_logaddexp2_opt():
  247. x, y = map(Symbol, 'x y'.split())
  248. expr1 = log(2**x + 2**y)/log(2)
  249. opt1 = optimize(expr1, [logaddexp2_opt])
  250. assert logaddexp2(x, y) - opt1 == 0
  251. assert logaddexp2(y, x) - opt1 == 0
  252. assert opt1.rewrite(log) == expr1
  253. def test_sinc_opts():
  254. def check(d):
  255. for k, v in d.items():
  256. assert optimize(k, sinc_opts) == v
  257. x = Symbol('x')
  258. check({
  259. sin(x)/x : sinc(x),
  260. sin(2*x)/(2*x) : sinc(2*x),
  261. sin(3*x)/x : 3*sinc(3*x),
  262. x*sin(x) : x*sin(x)
  263. })
  264. y = Symbol('y')
  265. check({
  266. sin(x*y)/(x*y) : sinc(x*y),
  267. y*sin(x/y)/x : sinc(x/y),
  268. sin(sin(x))/sin(x) : sinc(sin(x)),
  269. sin(3*sin(x))/sin(x) : 3*sinc(3*sin(x)),
  270. sin(x)/y : sin(x)/y
  271. })
  272. def test_optims_numpy():
  273. def check(d):
  274. for k, v in d.items():
  275. assert optimize(k, optims_numpy) == v
  276. x = Symbol('x')
  277. check({
  278. sin(2*x)/(2*x) + exp(2*x) - 1: sinc(2*x) + expm1(2*x),
  279. log(x+3)/log(2) + log(x**2 + 1): log1p(x**2) + log2(x+3)
  280. })
  281. @XFAIL # room for improvement, ideally this test case should pass.
  282. def test_optims_numpy_TODO():
  283. def check(d):
  284. for k, v in d.items():
  285. assert optimize(k, optims_numpy) == v
  286. x, y = map(Symbol, 'x y'.split())
  287. check({
  288. log(x*y)*sin(x*y)*log(x*y+1)/(log(2)*x*y): log2(x*y)*sinc(x*y)*log1p(x*y),
  289. exp(x*sin(y)/y) - 1: expm1(x*sinc(y))
  290. })
  291. @may_xfail
  292. def test_compiled_ccode_with_rewriting():
  293. if not cython:
  294. skip("cython not installed.")
  295. if not has_c():
  296. skip("No C compiler found.")
  297. x = Symbol('x')
  298. about_two = 2**(58/S(117))*3**(97/S(117))*5**(4/S(39))*7**(92/S(117))/S(30)*pi
  299. # about_two: 1.999999999999581826
  300. unchanged = 2*exp(x) - about_two
  301. xval = S(10)**-11
  302. ref = unchanged.subs(x, xval).n(19) # 2.0418173913673213e-11
  303. rewritten = optimize(2*exp(x) - about_two, [expm1_opt])
  304. # Unfortunately, we need to call ``.n()`` on our expressions before we hand them
  305. # to ``ccode``, and we need to request a large number of significant digits.
  306. # In this test, results converged for double precision when the following number
  307. # of significant digits were chosen:
  308. NUMBER_OF_DIGITS = 25 # TODO: this should ideally be automatically handled.
  309. func_c = '''
  310. #include <math.h>
  311. double func_unchanged(double x) {
  312. return %(unchanged)s;
  313. }
  314. double func_rewritten(double x) {
  315. return %(rewritten)s;
  316. }
  317. ''' % dict(unchanged=ccode(unchanged.n(NUMBER_OF_DIGITS)),
  318. rewritten=ccode(rewritten.n(NUMBER_OF_DIGITS)))
  319. func_pyx = '''
  320. #cython: language_level=3
  321. cdef extern double func_unchanged(double)
  322. cdef extern double func_rewritten(double)
  323. def py_unchanged(x):
  324. return func_unchanged(x)
  325. def py_rewritten(x):
  326. return func_rewritten(x)
  327. '''
  328. with tempfile.TemporaryDirectory() as folder:
  329. mod, info = compile_link_import_strings(
  330. [('func.c', func_c), ('_func.pyx', func_pyx)],
  331. build_dir=folder, compile_kwargs=dict(std='c99')
  332. )
  333. err_rewritten = abs(mod.py_rewritten(1e-11) - ref)
  334. err_unchanged = abs(mod.py_unchanged(1e-11) - ref)
  335. assert 1e-27 < err_rewritten < 1e-25 # highly accurate.
  336. assert 1e-19 < err_unchanged < 1e-16 # quite poor.
  337. # Tolerances used above were determined as follows:
  338. # >>> no_opt = unchanged.subs(x, xval.evalf()).evalf()
  339. # >>> with_opt = rewritten.n(25).subs(x, 1e-11).evalf()
  340. # >>> with_opt - ref, no_opt - ref
  341. # (1.1536301877952077e-26, 1.6547074214222335e-18)