test_applications.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # This file contains tests that exercise multiple AST nodes
  2. import tempfile
  3. from sympy.external import import_module
  4. from sympy.printing.codeprinter import ccode
  5. from sympy.utilities._compilation import compile_link_import_strings, has_c
  6. from sympy.utilities._compilation.util import may_xfail
  7. from sympy.testing.pytest import skip, skip_under_pyodide
  8. from sympy.codegen.ast import (
  9. FunctionDefinition, FunctionPrototype, Variable, Pointer, real, Assignment,
  10. integer, CodeBlock, While
  11. )
  12. from sympy.codegen.cnodes import void, PreIncrement
  13. from sympy.codegen.cutils import render_as_source_file
  14. cython = import_module('cython')
  15. np = import_module('numpy')
  16. def _mk_func1():
  17. declars = n, inp, out = Variable('n', integer), Pointer('inp', real), Pointer('out', real)
  18. i = Variable('i', integer)
  19. whl = While(i<n, [Assignment(out[i], inp[i]), PreIncrement(i)])
  20. body = CodeBlock(i.as_Declaration(value=0), whl)
  21. return FunctionDefinition(void, 'our_test_function', declars, body)
  22. def _render_compile_import(funcdef, build_dir):
  23. code_str = render_as_source_file(funcdef, settings={"contract": False})
  24. declar = ccode(FunctionPrototype.from_FunctionDefinition(funcdef))
  25. return compile_link_import_strings([
  26. ('our_test_func.c', code_str),
  27. ('_our_test_func.pyx', ("#cython: language_level={}\n".format("3") +
  28. "cdef extern {declar}\n"
  29. "def _{fname}({typ}[:] inp, {typ}[:] out):\n"
  30. " {fname}(inp.size, &inp[0], &out[0])").format(
  31. declar=declar, fname=funcdef.name, typ='double'
  32. ))
  33. ], build_dir=build_dir)
  34. @may_xfail
  35. @skip_under_pyodide("Emscripten does not support process spawning")
  36. def test_copying_function():
  37. if not np:
  38. skip("numpy not installed.")
  39. if not has_c():
  40. skip("No C compiler found.")
  41. if not cython:
  42. skip("Cython not found.")
  43. info = None
  44. with tempfile.TemporaryDirectory() as folder:
  45. mod, info = _render_compile_import(_mk_func1(), build_dir=folder)
  46. inp = np.arange(10.0)
  47. out = np.empty_like(inp)
  48. mod._our_test_function(inp, out)
  49. assert np.allclose(inp, out)