IpythonMagic.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. # -*- coding: utf-8 -*-
  2. """
  3. =====================
  4. Cython related magics
  5. =====================
  6. Magic command interface for interactive work with Cython
  7. .. note::
  8. The ``Cython`` package needs to be installed separately. It
  9. can be obtained using ``easy_install`` or ``pip``.
  10. Usage
  11. =====
  12. To enable the magics below, execute ``%load_ext cython``.
  13. ``%%cython``
  14. {CYTHON_DOC}
  15. ``%%cython_inline``
  16. {CYTHON_INLINE_DOC}
  17. ``%%cython_pyximport``
  18. {CYTHON_PYXIMPORT_DOC}
  19. Author:
  20. * Brian Granger
  21. Code moved from IPython and adapted by:
  22. * Martín Gaitán
  23. Parts of this code were taken from Cython.inline.
  24. """
  25. #-----------------------------------------------------------------------------
  26. # Copyright (C) 2010-2011, IPython Development Team.
  27. #
  28. # Distributed under the terms of the Modified BSD License.
  29. #
  30. # The full license is in the file ipython-COPYING.rst, distributed with this software.
  31. #-----------------------------------------------------------------------------
  32. from __future__ import absolute_import, print_function
  33. import imp
  34. import io
  35. import os
  36. import re
  37. import sys
  38. import time
  39. import copy
  40. import distutils.log
  41. import textwrap
  42. try:
  43. reload
  44. except NameError: # Python 3
  45. from imp import reload
  46. try:
  47. import hashlib
  48. except ImportError:
  49. import md5 as hashlib
  50. from distutils.core import Distribution, Extension
  51. from distutils.command.build_ext import build_ext
  52. from IPython.core import display
  53. from IPython.core import magic_arguments
  54. from IPython.core.magic import Magics, magics_class, cell_magic
  55. from IPython.utils import py3compat
  56. try:
  57. from IPython.paths import get_ipython_cache_dir
  58. except ImportError:
  59. # older IPython version
  60. from IPython.utils.path import get_ipython_cache_dir
  61. from IPython.utils.text import dedent
  62. from ..Shadow import __version__ as cython_version
  63. from ..Compiler.Errors import CompileError
  64. from .Inline import cython_inline
  65. from .Dependencies import cythonize
  66. PGO_CONFIG = {
  67. 'gcc': {
  68. 'gen': ['-fprofile-generate', '-fprofile-dir={TEMPDIR}'],
  69. 'use': ['-fprofile-use', '-fprofile-correction', '-fprofile-dir={TEMPDIR}'],
  70. },
  71. # blind copy from 'configure' script in CPython 3.7
  72. 'icc': {
  73. 'gen': ['-prof-gen'],
  74. 'use': ['-prof-use'],
  75. }
  76. }
  77. PGO_CONFIG['mingw32'] = PGO_CONFIG['gcc']
  78. @magics_class
  79. class CythonMagics(Magics):
  80. def __init__(self, shell):
  81. super(CythonMagics, self).__init__(shell)
  82. self._reloads = {}
  83. self._code_cache = {}
  84. self._pyximport_installed = False
  85. def _import_all(self, module):
  86. mdict = module.__dict__
  87. if '__all__' in mdict:
  88. keys = mdict['__all__']
  89. else:
  90. keys = [k for k in mdict if not k.startswith('_')]
  91. for k in keys:
  92. try:
  93. self.shell.push({k: mdict[k]})
  94. except KeyError:
  95. msg = "'module' object has no attribute '%s'" % k
  96. raise AttributeError(msg)
  97. @cell_magic
  98. def cython_inline(self, line, cell):
  99. """Compile and run a Cython code cell using Cython.inline.
  100. This magic simply passes the body of the cell to Cython.inline
  101. and returns the result. If the variables `a` and `b` are defined
  102. in the user's namespace, here is a simple example that returns
  103. their sum::
  104. %%cython_inline
  105. return a+b
  106. For most purposes, we recommend the usage of the `%%cython` magic.
  107. """
  108. locs = self.shell.user_global_ns
  109. globs = self.shell.user_ns
  110. return cython_inline(cell, locals=locs, globals=globs)
  111. @cell_magic
  112. def cython_pyximport(self, line, cell):
  113. """Compile and import a Cython code cell using pyximport.
  114. The contents of the cell are written to a `.pyx` file in the current
  115. working directory, which is then imported using `pyximport`. This
  116. magic requires a module name to be passed::
  117. %%cython_pyximport modulename
  118. def f(x):
  119. return 2.0*x
  120. The compiled module is then imported and all of its symbols are
  121. injected into the user's namespace. For most purposes, we recommend
  122. the usage of the `%%cython` magic.
  123. """
  124. module_name = line.strip()
  125. if not module_name:
  126. raise ValueError('module name must be given')
  127. fname = module_name + '.pyx'
  128. with io.open(fname, 'w', encoding='utf-8') as f:
  129. f.write(cell)
  130. if 'pyximport' not in sys.modules or not self._pyximport_installed:
  131. import pyximport
  132. pyximport.install(reload_support=True)
  133. self._pyximport_installed = True
  134. if module_name in self._reloads:
  135. module = self._reloads[module_name]
  136. reload(module)
  137. else:
  138. __import__(module_name)
  139. module = sys.modules[module_name]
  140. self._reloads[module_name] = module
  141. self._import_all(module)
  142. @magic_arguments.magic_arguments()
  143. @magic_arguments.argument(
  144. '-a', '--annotate', action='store_true', default=False,
  145. help="Produce a colorized HTML version of the source."
  146. )
  147. @magic_arguments.argument(
  148. '-+', '--cplus', action='store_true', default=False,
  149. help="Output a C++ rather than C file."
  150. )
  151. @magic_arguments.argument(
  152. '-3', dest='language_level', action='store_const', const=3, default=None,
  153. help="Select Python 3 syntax."
  154. )
  155. @magic_arguments.argument(
  156. '-2', dest='language_level', action='store_const', const=2, default=None,
  157. help="Select Python 2 syntax."
  158. )
  159. @magic_arguments.argument(
  160. '-f', '--force', action='store_true', default=False,
  161. help="Force the compilation of a new module, even if the source has been "
  162. "previously compiled."
  163. )
  164. @magic_arguments.argument(
  165. '-c', '--compile-args', action='append', default=[],
  166. help="Extra flags to pass to compiler via the `extra_compile_args` "
  167. "Extension flag (can be specified multiple times)."
  168. )
  169. @magic_arguments.argument(
  170. '--link-args', action='append', default=[],
  171. help="Extra flags to pass to linker via the `extra_link_args` "
  172. "Extension flag (can be specified multiple times)."
  173. )
  174. @magic_arguments.argument(
  175. '-l', '--lib', action='append', default=[],
  176. help="Add a library to link the extension against (can be specified "
  177. "multiple times)."
  178. )
  179. @magic_arguments.argument(
  180. '-n', '--name',
  181. help="Specify a name for the Cython module."
  182. )
  183. @magic_arguments.argument(
  184. '-L', dest='library_dirs', metavar='dir', action='append', default=[],
  185. help="Add a path to the list of library directories (can be specified "
  186. "multiple times)."
  187. )
  188. @magic_arguments.argument(
  189. '-I', '--include', action='append', default=[],
  190. help="Add a path to the list of include directories (can be specified "
  191. "multiple times)."
  192. )
  193. @magic_arguments.argument(
  194. '-S', '--src', action='append', default=[],
  195. help="Add a path to the list of src files (can be specified "
  196. "multiple times)."
  197. )
  198. @magic_arguments.argument(
  199. '--pgo', dest='pgo', action='store_true', default=False,
  200. help=("Enable profile guided optimisation in the C compiler. "
  201. "Compiles the cell twice and executes it in between to generate a runtime profile.")
  202. )
  203. @magic_arguments.argument(
  204. '--verbose', dest='quiet', action='store_false', default=True,
  205. help=("Print debug information like generated .c/.cpp file location "
  206. "and exact gcc/g++ command invoked.")
  207. )
  208. @cell_magic
  209. def cython(self, line, cell):
  210. """Compile and import everything from a Cython code cell.
  211. The contents of the cell are written to a `.pyx` file in the
  212. directory `IPYTHONDIR/cython` using a filename with the hash of the
  213. code. This file is then cythonized and compiled. The resulting module
  214. is imported and all of its symbols are injected into the user's
  215. namespace. The usage is similar to that of `%%cython_pyximport` but
  216. you don't have to pass a module name::
  217. %%cython
  218. def f(x):
  219. return 2.0*x
  220. To compile OpenMP codes, pass the required `--compile-args`
  221. and `--link-args`. For example with gcc::
  222. %%cython --compile-args=-fopenmp --link-args=-fopenmp
  223. ...
  224. To enable profile guided optimisation, pass the ``--pgo`` option.
  225. Note that the cell itself needs to take care of establishing a suitable
  226. profile when executed. This can be done by implementing the functions to
  227. optimise, and then calling them directly in the same cell on some realistic
  228. training data like this::
  229. %%cython --pgo
  230. def critical_function(data):
  231. for item in data:
  232. ...
  233. # execute function several times to build profile
  234. from somewhere import some_typical_data
  235. for _ in range(100):
  236. critical_function(some_typical_data)
  237. In Python 3.5 and later, you can distinguish between the profile and
  238. non-profile runs as follows::
  239. if "_pgo_" in __name__:
  240. ... # execute critical code here
  241. """
  242. args = magic_arguments.parse_argstring(self.cython, line)
  243. code = cell if cell.endswith('\n') else cell + '\n'
  244. lib_dir = os.path.join(get_ipython_cache_dir(), 'cython')
  245. key = (code, line, sys.version_info, sys.executable, cython_version)
  246. if not os.path.exists(lib_dir):
  247. os.makedirs(lib_dir)
  248. if args.pgo:
  249. key += ('pgo',)
  250. if args.force:
  251. # Force a new module name by adding the current time to the
  252. # key which is hashed to determine the module name.
  253. key += (time.time(),)
  254. if args.name:
  255. module_name = py3compat.unicode_to_str(args.name)
  256. else:
  257. module_name = "_cython_magic_" + hashlib.md5(str(key).encode('utf-8')).hexdigest()
  258. html_file = os.path.join(lib_dir, module_name + '.html')
  259. module_path = os.path.join(lib_dir, module_name + self.so_ext)
  260. have_module = os.path.isfile(module_path)
  261. need_cythonize = args.pgo or not have_module
  262. if args.annotate:
  263. if not os.path.isfile(html_file):
  264. need_cythonize = True
  265. extension = None
  266. if need_cythonize:
  267. extensions = self._cythonize(module_name, code, lib_dir, args, quiet=args.quiet)
  268. assert len(extensions) == 1
  269. extension = extensions[0]
  270. self._code_cache[key] = module_name
  271. if args.pgo:
  272. self._profile_pgo_wrapper(extension, lib_dir)
  273. self._build_extension(extension, lib_dir, pgo_step_name='use' if args.pgo else None,
  274. quiet=args.quiet)
  275. module = imp.load_dynamic(module_name, module_path)
  276. self._import_all(module)
  277. if args.annotate:
  278. try:
  279. with io.open(html_file, encoding='utf-8') as f:
  280. annotated_html = f.read()
  281. except IOError as e:
  282. # File could not be opened. Most likely the user has a version
  283. # of Cython before 0.15.1 (when `cythonize` learned the
  284. # `force` keyword argument) and has already compiled this
  285. # exact source without annotation.
  286. print('Cython completed successfully but the annotated '
  287. 'source could not be read.', file=sys.stderr)
  288. print(e, file=sys.stderr)
  289. else:
  290. return display.HTML(self.clean_annotated_html(annotated_html))
  291. def _profile_pgo_wrapper(self, extension, lib_dir):
  292. """
  293. Generate a .c file for a separate extension module that calls the
  294. module init function of the original module. This makes sure that the
  295. PGO profiler sees the correct .o file of the final module, but it still
  296. allows us to import the module under a different name for profiling,
  297. before recompiling it into the PGO optimised module. Overwriting and
  298. reimporting the same shared library is not portable.
  299. """
  300. extension = copy.copy(extension) # shallow copy, do not modify sources in place!
  301. module_name = extension.name
  302. pgo_module_name = '_pgo_' + module_name
  303. pgo_wrapper_c_file = os.path.join(lib_dir, pgo_module_name + '.c')
  304. with io.open(pgo_wrapper_c_file, 'w', encoding='utf-8') as f:
  305. f.write(textwrap.dedent(u"""
  306. #include "Python.h"
  307. #if PY_MAJOR_VERSION < 3
  308. extern PyMODINIT_FUNC init%(module_name)s(void);
  309. PyMODINIT_FUNC init%(pgo_module_name)s(void); /*proto*/
  310. PyMODINIT_FUNC init%(pgo_module_name)s(void) {
  311. PyObject *sys_modules;
  312. init%(module_name)s(); if (PyErr_Occurred()) return;
  313. sys_modules = PyImport_GetModuleDict(); /* borrowed, no exception, "never" fails */
  314. if (sys_modules) {
  315. PyObject *module = PyDict_GetItemString(sys_modules, "%(module_name)s"); if (!module) return;
  316. PyDict_SetItemString(sys_modules, "%(pgo_module_name)s", module);
  317. Py_DECREF(module);
  318. }
  319. }
  320. #else
  321. extern PyMODINIT_FUNC PyInit_%(module_name)s(void);
  322. PyMODINIT_FUNC PyInit_%(pgo_module_name)s(void); /*proto*/
  323. PyMODINIT_FUNC PyInit_%(pgo_module_name)s(void) {
  324. return PyInit_%(module_name)s();
  325. }
  326. #endif
  327. """ % {'module_name': module_name, 'pgo_module_name': pgo_module_name}))
  328. extension.sources = extension.sources + [pgo_wrapper_c_file] # do not modify in place!
  329. extension.name = pgo_module_name
  330. self._build_extension(extension, lib_dir, pgo_step_name='gen')
  331. # import and execute module code to generate profile
  332. so_module_path = os.path.join(lib_dir, pgo_module_name + self.so_ext)
  333. imp.load_dynamic(pgo_module_name, so_module_path)
  334. def _cythonize(self, module_name, code, lib_dir, args, quiet=True):
  335. pyx_file = os.path.join(lib_dir, module_name + '.pyx')
  336. pyx_file = py3compat.cast_bytes_py2(pyx_file, encoding=sys.getfilesystemencoding())
  337. c_include_dirs = args.include
  338. c_src_files = list(map(str, args.src))
  339. if 'numpy' in code:
  340. import numpy
  341. c_include_dirs.append(numpy.get_include())
  342. with io.open(pyx_file, 'w', encoding='utf-8') as f:
  343. f.write(code)
  344. extension = Extension(
  345. name=module_name,
  346. sources=[pyx_file] + c_src_files,
  347. include_dirs=c_include_dirs,
  348. library_dirs=args.library_dirs,
  349. extra_compile_args=args.compile_args,
  350. extra_link_args=args.link_args,
  351. libraries=args.lib,
  352. language='c++' if args.cplus else 'c',
  353. )
  354. try:
  355. opts = dict(
  356. quiet=quiet,
  357. annotate=args.annotate,
  358. force=True,
  359. )
  360. if args.language_level is not None:
  361. assert args.language_level in (2, 3)
  362. opts['language_level'] = args.language_level
  363. elif sys.version_info[0] >= 3:
  364. opts['language_level'] = 3
  365. return cythonize([extension], **opts)
  366. except CompileError:
  367. return None
  368. def _build_extension(self, extension, lib_dir, temp_dir=None, pgo_step_name=None, quiet=True):
  369. build_extension = self._get_build_extension(
  370. extension, lib_dir=lib_dir, temp_dir=temp_dir, pgo_step_name=pgo_step_name)
  371. old_threshold = None
  372. try:
  373. if not quiet:
  374. old_threshold = distutils.log.set_threshold(distutils.log.DEBUG)
  375. build_extension.run()
  376. finally:
  377. if not quiet and old_threshold is not None:
  378. distutils.log.set_threshold(old_threshold)
  379. def _add_pgo_flags(self, build_extension, step_name, temp_dir):
  380. compiler_type = build_extension.compiler.compiler_type
  381. if compiler_type == 'unix':
  382. compiler_cmd = build_extension.compiler.compiler_so
  383. # TODO: we could try to call "[cmd] --version" for better insights
  384. if not compiler_cmd:
  385. pass
  386. elif 'clang' in compiler_cmd or 'clang' in compiler_cmd[0]:
  387. compiler_type = 'clang'
  388. elif 'icc' in compiler_cmd or 'icc' in compiler_cmd[0]:
  389. compiler_type = 'icc'
  390. elif 'gcc' in compiler_cmd or 'gcc' in compiler_cmd[0]:
  391. compiler_type = 'gcc'
  392. elif 'g++' in compiler_cmd or 'g++' in compiler_cmd[0]:
  393. compiler_type = 'gcc'
  394. config = PGO_CONFIG.get(compiler_type)
  395. orig_flags = []
  396. if config and step_name in config:
  397. flags = [f.format(TEMPDIR=temp_dir) for f in config[step_name]]
  398. for extension in build_extension.extensions:
  399. orig_flags.append((extension.extra_compile_args, extension.extra_link_args))
  400. extension.extra_compile_args = extension.extra_compile_args + flags
  401. extension.extra_link_args = extension.extra_link_args + flags
  402. else:
  403. print("No PGO %s configuration known for C compiler type '%s'" % (step_name, compiler_type),
  404. file=sys.stderr)
  405. return orig_flags
  406. @property
  407. def so_ext(self):
  408. """The extension suffix for compiled modules."""
  409. try:
  410. return self._so_ext
  411. except AttributeError:
  412. self._so_ext = self._get_build_extension().get_ext_filename('')
  413. return self._so_ext
  414. def _clear_distutils_mkpath_cache(self):
  415. """clear distutils mkpath cache
  416. prevents distutils from skipping re-creation of dirs that have been removed
  417. """
  418. try:
  419. from distutils.dir_util import _path_created
  420. except ImportError:
  421. pass
  422. else:
  423. _path_created.clear()
  424. def _get_build_extension(self, extension=None, lib_dir=None, temp_dir=None,
  425. pgo_step_name=None, _build_ext=build_ext):
  426. self._clear_distutils_mkpath_cache()
  427. dist = Distribution()
  428. config_files = dist.find_config_files()
  429. try:
  430. config_files.remove('setup.cfg')
  431. except ValueError:
  432. pass
  433. dist.parse_config_files(config_files)
  434. if not temp_dir:
  435. temp_dir = lib_dir
  436. add_pgo_flags = self._add_pgo_flags
  437. if pgo_step_name:
  438. base_build_ext = _build_ext
  439. class _build_ext(_build_ext):
  440. def build_extensions(self):
  441. add_pgo_flags(self, pgo_step_name, temp_dir)
  442. base_build_ext.build_extensions(self)
  443. build_extension = _build_ext(dist)
  444. build_extension.finalize_options()
  445. if temp_dir:
  446. temp_dir = py3compat.cast_bytes_py2(temp_dir, encoding=sys.getfilesystemencoding())
  447. build_extension.build_temp = temp_dir
  448. if lib_dir:
  449. lib_dir = py3compat.cast_bytes_py2(lib_dir, encoding=sys.getfilesystemencoding())
  450. build_extension.build_lib = lib_dir
  451. if extension is not None:
  452. build_extension.extensions = [extension]
  453. return build_extension
  454. @staticmethod
  455. def clean_annotated_html(html):
  456. """Clean up the annotated HTML source.
  457. Strips the link to the generated C or C++ file, which we do not
  458. present to the user.
  459. """
  460. r = re.compile('<p>Raw output: <a href="(.*)">(.*)</a>')
  461. html = '\n'.join(l for l in html.splitlines() if not r.match(l))
  462. return html
  463. __doc__ = __doc__.format(
  464. # rST doesn't see the -+ flag as part of an option list, so we
  465. # hide it from the module-level docstring.
  466. CYTHON_DOC=dedent(CythonMagics.cython.__doc__\
  467. .replace('-+, --cplus', '--cplus ')),
  468. CYTHON_INLINE_DOC=dedent(CythonMagics.cython_inline.__doc__),
  469. CYTHON_PYXIMPORT_DOC=dedent(CythonMagics.cython_pyximport.__doc__),
  470. )