IpythonMagic.py 21 KB

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