test_codegen.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. # This tests the compilation and execution of the source code generated with
  2. # utilities.codegen. The compilation takes place in a temporary directory that
  3. # is removed after the test. By default the test directory is always removed,
  4. # but this behavior can be changed by setting the environment variable
  5. # SYMPY_TEST_CLEAN_TEMP to:
  6. # export SYMPY_TEST_CLEAN_TEMP=always : the default behavior.
  7. # export SYMPY_TEST_CLEAN_TEMP=success : only remove the directories of working tests.
  8. # export SYMPY_TEST_CLEAN_TEMP=never : never remove the directories with the test code.
  9. # When a directory is not removed, the necessary information is printed on
  10. # screen to find the files that belong to the (failed) tests. If a test does
  11. # not fail, py.test captures all the output and you will not see the directories
  12. # corresponding to the successful tests. Use the --nocapture option to see all
  13. # the output.
  14. # All tests below have a counterpart in utilities/test/test_codegen.py. In the
  15. # latter file, the resulting code is compared with predefined strings, without
  16. # compilation or execution.
  17. # All the generated Fortran code should conform with the Fortran 95 standard,
  18. # and all the generated C code should be ANSI C, which facilitates the
  19. # incorporation in various projects. The tests below assume that the binary cc
  20. # is somewhere in the path and that it can compile ANSI C code.
  21. from sympy.abc import x, y, z
  22. from sympy.external import import_module
  23. from sympy.testing.pytest import skip
  24. from sympy.utilities.codegen import codegen, make_routine, get_code_generator
  25. import sys
  26. import os
  27. import tempfile
  28. import subprocess
  29. pyodide_js = import_module('pyodide_js')
  30. # templates for the main program that will test the generated code.
  31. main_template = {}
  32. main_template['F95'] = """
  33. program main
  34. include "codegen.h"
  35. integer :: result;
  36. result = 0
  37. %(statements)s
  38. call exit(result)
  39. end program
  40. """
  41. main_template['C89'] = """
  42. #include "codegen.h"
  43. #include <stdio.h>
  44. #include <math.h>
  45. int main() {
  46. int result = 0;
  47. %(statements)s
  48. return result;
  49. }
  50. """
  51. main_template['C99'] = main_template['C89']
  52. # templates for the numerical tests
  53. numerical_test_template = {}
  54. numerical_test_template['C89'] = """
  55. if (fabs(%(call)s)>%(threshold)s) {
  56. printf("Numerical validation failed: %(call)s=%%e threshold=%(threshold)s\\n", %(call)s);
  57. result = -1;
  58. }
  59. """
  60. numerical_test_template['C99'] = numerical_test_template['C89']
  61. numerical_test_template['F95'] = """
  62. if (abs(%(call)s)>%(threshold)s) then
  63. write(6,"('Numerical validation failed:')")
  64. write(6,"('%(call)s=',e15.5,'threshold=',e15.5)") %(call)s, %(threshold)s
  65. result = -1;
  66. end if
  67. """
  68. # command sequences for supported compilers
  69. compile_commands = {}
  70. compile_commands['cc'] = [
  71. "cc -c codegen.c -o codegen.o",
  72. "cc -c main.c -o main.o",
  73. "cc main.o codegen.o -lm -o test.exe"
  74. ]
  75. compile_commands['gfortran'] = [
  76. "gfortran -c codegen.f90 -o codegen.o",
  77. "gfortran -ffree-line-length-none -c main.f90 -o main.o",
  78. "gfortran main.o codegen.o -o test.exe"
  79. ]
  80. compile_commands['g95'] = [
  81. "g95 -c codegen.f90 -o codegen.o",
  82. "g95 -ffree-line-length-huge -c main.f90 -o main.o",
  83. "g95 main.o codegen.o -o test.exe"
  84. ]
  85. compile_commands['ifort'] = [
  86. "ifort -c codegen.f90 -o codegen.o",
  87. "ifort -c main.f90 -o main.o",
  88. "ifort main.o codegen.o -o test.exe"
  89. ]
  90. combinations_lang_compiler = [
  91. ('C89', 'cc'),
  92. ('C99', 'cc'),
  93. ('F95', 'ifort'),
  94. ('F95', 'gfortran'),
  95. ('F95', 'g95')
  96. ]
  97. def try_run(commands):
  98. """Run a series of commands and only return True if all ran fine."""
  99. if pyodide_js:
  100. return False
  101. with open(os.devnull, 'w') as null:
  102. for command in commands:
  103. retcode = subprocess.call(command, stdout=null, shell=True,
  104. stderr=subprocess.STDOUT)
  105. if retcode != 0:
  106. return False
  107. return True
  108. def run_test(label, routines, numerical_tests, language, commands, friendly=True):
  109. """A driver for the codegen tests.
  110. This driver assumes that a compiler ifort is present in the PATH and that
  111. ifort is (at least) a Fortran 90 compiler. The generated code is written in
  112. a temporary directory, together with a main program that validates the
  113. generated code. The test passes when the compilation and the validation
  114. run correctly.
  115. """
  116. # Check input arguments before touching the file system
  117. language = language.upper()
  118. assert language in main_template
  119. assert language in numerical_test_template
  120. # Check that environment variable makes sense
  121. clean = os.getenv('SYMPY_TEST_CLEAN_TEMP', 'always').lower()
  122. if clean not in ('always', 'success', 'never'):
  123. raise ValueError("SYMPY_TEST_CLEAN_TEMP must be one of the following: 'always', 'success' or 'never'.")
  124. # Do all the magic to compile, run and validate the test code
  125. # 1) prepare the temporary working directory, switch to that dir
  126. work = tempfile.mkdtemp("_sympy_%s_test" % language, "%s_" % label)
  127. oldwork = os.getcwd()
  128. os.chdir(work)
  129. # 2) write the generated code
  130. if friendly:
  131. # interpret the routines as a name_expr list and call the friendly
  132. # function codegen
  133. codegen(routines, language, "codegen", to_files=True)
  134. else:
  135. code_gen = get_code_generator(language, "codegen")
  136. code_gen.write(routines, "codegen", to_files=True)
  137. # 3) write a simple main program that links to the generated code, and that
  138. # includes the numerical tests
  139. test_strings = []
  140. for fn_name, args, expected, threshold in numerical_tests:
  141. call_string = "%s(%s)-(%s)" % (
  142. fn_name, ",".join(str(arg) for arg in args), expected)
  143. if language == "F95":
  144. call_string = fortranize_double_constants(call_string)
  145. threshold = fortranize_double_constants(str(threshold))
  146. test_strings.append(numerical_test_template[language] % {
  147. "call": call_string,
  148. "threshold": threshold,
  149. })
  150. if language == "F95":
  151. f_name = "main.f90"
  152. elif language.startswith("C"):
  153. f_name = "main.c"
  154. else:
  155. raise NotImplementedError(
  156. "FIXME: filename extension unknown for language: %s" % language)
  157. with open(f_name, "w") as f:
  158. f.write(
  159. main_template[language] % {'statements': "".join(test_strings)})
  160. # 4) Compile and link
  161. compiled = try_run(commands)
  162. # 5) Run if compiled
  163. if compiled:
  164. executed = try_run(["./test.exe"])
  165. else:
  166. executed = False
  167. # 6) Clean up stuff
  168. if clean == 'always' or (clean == 'success' and compiled and executed):
  169. def safe_remove(filename):
  170. if os.path.isfile(filename):
  171. os.remove(filename)
  172. safe_remove("codegen.f90")
  173. safe_remove("codegen.c")
  174. safe_remove("codegen.h")
  175. safe_remove("codegen.o")
  176. safe_remove("main.f90")
  177. safe_remove("main.c")
  178. safe_remove("main.o")
  179. safe_remove("test.exe")
  180. os.chdir(oldwork)
  181. os.rmdir(work)
  182. else:
  183. print("TEST NOT REMOVED: %s" % work, file=sys.stderr)
  184. os.chdir(oldwork)
  185. # 7) Do the assertions in the end
  186. assert compiled, "failed to compile %s code with:\n%s" % (
  187. language, "\n".join(commands))
  188. assert executed, "failed to execute %s code from:\n%s" % (
  189. language, "\n".join(commands))
  190. def fortranize_double_constants(code_string):
  191. """
  192. Replaces every literal float with literal doubles
  193. """
  194. import re
  195. pattern_exp = re.compile(r'\d+(\.)?\d*[eE]-?\d+')
  196. pattern_float = re.compile(r'\d+\.\d*(?!\d*d)')
  197. def subs_exp(matchobj):
  198. return re.sub('[eE]', 'd', matchobj.group(0))
  199. def subs_float(matchobj):
  200. return "%sd0" % matchobj.group(0)
  201. code_string = pattern_exp.sub(subs_exp, code_string)
  202. code_string = pattern_float.sub(subs_float, code_string)
  203. return code_string
  204. def is_feasible(language, commands):
  205. # This test should always work, otherwise the compiler is not present.
  206. routine = make_routine("test", x)
  207. numerical_tests = [
  208. ("test", ( 1.0,), 1.0, 1e-15),
  209. ("test", (-1.0,), -1.0, 1e-15),
  210. ]
  211. try:
  212. run_test("is_feasible", [routine], numerical_tests, language, commands,
  213. friendly=False)
  214. return True
  215. except AssertionError:
  216. return False
  217. valid_lang_commands = []
  218. invalid_lang_compilers = []
  219. for lang, compiler in combinations_lang_compiler:
  220. commands = compile_commands[compiler]
  221. if is_feasible(lang, commands):
  222. valid_lang_commands.append((lang, commands))
  223. else:
  224. invalid_lang_compilers.append((lang, compiler))
  225. # We test all language-compiler combinations, just to report what is skipped
  226. def test_C89_cc():
  227. if ("C89", 'cc') in invalid_lang_compilers:
  228. skip("`cc' command didn't work as expected (C89)")
  229. def test_C99_cc():
  230. if ("C99", 'cc') in invalid_lang_compilers:
  231. skip("`cc' command didn't work as expected (C99)")
  232. def test_F95_ifort():
  233. if ("F95", 'ifort') in invalid_lang_compilers:
  234. skip("`ifort' command didn't work as expected")
  235. def test_F95_gfortran():
  236. if ("F95", 'gfortran') in invalid_lang_compilers:
  237. skip("`gfortran' command didn't work as expected")
  238. def test_F95_g95():
  239. if ("F95", 'g95') in invalid_lang_compilers:
  240. skip("`g95' command didn't work as expected")
  241. # Here comes the actual tests
  242. def test_basic_codegen():
  243. numerical_tests = [
  244. ("test", (1.0, 6.0, 3.0), 21.0, 1e-15),
  245. ("test", (-1.0, 2.0, -2.5), -2.5, 1e-15),
  246. ]
  247. name_expr = [("test", (x + y)*z)]
  248. for lang, commands in valid_lang_commands:
  249. run_test("basic_codegen", name_expr, numerical_tests, lang, commands)
  250. def test_intrinsic_math1_codegen():
  251. # not included: log10
  252. from sympy.core.evalf import N
  253. from sympy.functions import ln
  254. from sympy.functions.elementary.exponential import log
  255. from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh)
  256. from sympy.functions.elementary.integers import (ceiling, floor)
  257. from sympy.functions.elementary.miscellaneous import sqrt
  258. from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan)
  259. name_expr = [
  260. ("test_fabs", abs(x)),
  261. ("test_acos", acos(x)),
  262. ("test_asin", asin(x)),
  263. ("test_atan", atan(x)),
  264. ("test_cos", cos(x)),
  265. ("test_cosh", cosh(x)),
  266. ("test_log", log(x)),
  267. ("test_ln", ln(x)),
  268. ("test_sin", sin(x)),
  269. ("test_sinh", sinh(x)),
  270. ("test_sqrt", sqrt(x)),
  271. ("test_tan", tan(x)),
  272. ("test_tanh", tanh(x)),
  273. ]
  274. numerical_tests = []
  275. for name, expr in name_expr:
  276. for xval in 0.2, 0.5, 0.8:
  277. expected = N(expr.subs(x, xval))
  278. numerical_tests.append((name, (xval,), expected, 1e-14))
  279. for lang, commands in valid_lang_commands:
  280. if lang.startswith("C"):
  281. name_expr_C = [("test_floor", floor(x)), ("test_ceil", ceiling(x))]
  282. else:
  283. name_expr_C = []
  284. run_test("intrinsic_math1", name_expr + name_expr_C,
  285. numerical_tests, lang, commands)
  286. def test_instrinsic_math2_codegen():
  287. # not included: frexp, ldexp, modf, fmod
  288. from sympy.core.evalf import N
  289. from sympy.functions.elementary.trigonometric import atan2
  290. name_expr = [
  291. ("test_atan2", atan2(x, y)),
  292. ("test_pow", x**y),
  293. ]
  294. numerical_tests = []
  295. for name, expr in name_expr:
  296. for xval, yval in (0.2, 1.3), (0.5, -0.2), (0.8, 0.8):
  297. expected = N(expr.subs(x, xval).subs(y, yval))
  298. numerical_tests.append((name, (xval, yval), expected, 1e-14))
  299. for lang, commands in valid_lang_commands:
  300. run_test("intrinsic_math2", name_expr, numerical_tests, lang, commands)
  301. def test_complicated_codegen():
  302. from sympy.core.evalf import N
  303. from sympy.functions.elementary.trigonometric import (cos, sin, tan)
  304. name_expr = [
  305. ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()),
  306. ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),
  307. ]
  308. numerical_tests = []
  309. for name, expr in name_expr:
  310. for xval, yval, zval in (0.2, 1.3, -0.3), (0.5, -0.2, 0.0), (0.8, 2.1, 0.8):
  311. expected = N(expr.subs(x, xval).subs(y, yval).subs(z, zval))
  312. numerical_tests.append((name, (xval, yval, zval), expected, 1e-12))
  313. for lang, commands in valid_lang_commands:
  314. run_test(
  315. "complicated_codegen", name_expr, numerical_tests, lang, commands)