def _standard_libs_libdirs_incdirs_aliases(): r""" Return the list of libraries and library directories. EXAMPLES:: sage: from sage.misc.cython import _standard_libs_libdirs_incdirs_aliases sage: _standard_libs_libdirs_incdirs_aliases() (['mpfr', 'gmp', 'gmpxx', 'pari', ...], [...], [...], {...}) """ aliases = cython_aliases() standard_libs = [ 'mpfr', 'gmp', 'gmpxx', 'pari', 'm', 'ec', 'gsl', ] + aliases["CBLAS_LIBRARIES"] + [ 'ntl'] standard_libdirs = [] if SAGE_LOCAL: standard_libdirs.append(os.path.join(SAGE_LOCAL, "lib")) standard_libdirs.extend(aliases["CBLAS_LIBDIR"] + aliases["NTL_LIBDIR"]) standard_incdirs = sage_include_directories() + aliases["CBLAS_INCDIR"] + aliases["NTL_INCDIR"] return standard_libs, standard_libdirs, standard_incdirs, aliases
def run(self): """ Call ``cythonize()`` to replace the ``ext_modules`` with the extensions containing Cython-generated C code. """ from sage.env import (cython_aliases, sage_include_directories) # Set variables used in self.create_extension from ..library_order import library_order self.library_order = library_order # Search for dependencies in the source tree and add to the list of include directories self.sage_include_dirs = sage_include_directories(use_sources=True) from Cython.Build import cythonize import Cython.Compiler.Options Cython.Compiler.Options.embed_pos_in_docstring = True log.info("Updating Cython code....") t = time.time() extensions = cythonize( self.extensions, nthreads=self.parallel, build_dir=self.build_dir, force=self.force, aliases=cython_aliases(), compiler_directives=self.cython_directives, compile_time_env=self.compile_time_env, create_extension=self.create_extension, # Debugging gdb_debug=self.debug, output_dir=os.path.join(self.build_lib, "sage"), # Disable Cython caching, which is currently too broken to # use reliably: http://trac.sagemath.org/ticket/17851 cache=False, ) # Filter out extensions with skip_build=True extensions = [ ext for ext in extensions if not getattr(ext, "skip_build", False) ] # We use [:] to change the list in-place because the same list # object is pointed to from different places. self.extensions[:] = extensions log.info("Finished Cythonizing, time: %.2f seconds." % (time.time() - t)) with open(self._version_file, 'w') as f: f.write(self._version_stamp) # Finally, copy relevant cythonized files from build/cythonized # tree into the build-lib tree for (dst_dir, src_files) in self.get_cythonized_package_files(): dst = os.path.join(self.build_lib, dst_dir) self.mkpath(dst) for src in src_files: self.copy_file(src, dst, preserve_mode=False)
def create_extension(template, kwds): from Cython.Build.Dependencies import default_create_extension from sage.env import sage_include_directories # Add numpy and source folder to the include search path used by the compiler # This is a workaround for https://github.com/cython/cython/issues/1480 include_dirs = kwds.get('include_dirs', []) + sage_include_directories(use_sources=True) kwds['include_dirs'] = include_dirs return default_create_extension(template, kwds)
if any(fnmatch(file, 'libcplex[0-9]*[0-9].' + ext) for ext in exts): cplex_libs = [os.path.splitext(file)[0][3:]] if not cplex_libs: print("CPLEX_HOME is not set, or it does not point to a directory with a " "Cplex installation. Trying to link against -lcplex", file=sys.stderr) cplex_libs = ['cplex'] else: print("Using cplex_include_directories={}, libraries={}, library_dirs={}".format( cplex_include_directories, cplex_libs, cplex_lib_directories), file=sys.stderr) # Cython modules ext_modules = [Extension('sage_numerical_backends_cplex.cplex_backend', sources = [os.path.join('sage_numerical_backends_cplex', 'cplex_backend.pyx')], include_dirs=sage_include_directories() + cplex_include_directories, libraries=cplex_libs, library_dirs=cplex_lib_directories, extra_link_args=['-Wl,-rpath,' + dir for dir in cplex_lib_directories]) ] ## SageMath 8.1 (included in Ubuntu bionic 18.04 LTS) does not have sage.cpython.string; ## it was introduced in 8.2. compile_time_env = {'HAVE_SAGE_CPYTHON_STRING': False, 'HAVE_ADD_COL_UNTYPED_ARGS': False} print("Checking whether HAVE_SAGE_CPYTHON_STRING...", file=sys.stderr) try: import sage.cpython.string compile_time_env['HAVE_SAGE_CPYTHON_STRING'] = True
def _pyx_preparse(s): r""" Preparse a pyx file: * parse ``clang`` pragma (c or c++) * parse ``clib`` pragma (additional libraries to link in) * parse ``cinclude`` (additional include directories) * parse ``cfile`` (additional files to be included) * parse ``cargs`` (additional parameters passed to the compiler) The pragmas: - ``clang`` - may be either ``'c'`` or ``'c++'`` indicating whether a C or C++ compiler should be used - ``clib`` - additional libraries to be linked in, the space separated list is split and passed to distutils. - ``cinclude`` - additional directories to search for header files. The space separated list is split and passed to distutils. - ``cfile`` - additional C or C++ files to be compiled. Also, :envvar:`$SAGE_SRC` and :envvar:`$SAGE_LOCAL` are expanded, but other environment variables are not. - ``cargs`` - additional parameters passed to the compiler OUTPUT: preamble, libs, includes, language, files, args EXAMPLES:: sage: from sage.misc.cython import _pyx_preparse sage: _pyx_preparse("") ('', ['mpfr', 'gmp', 'gmpxx', 'stdc++', 'pari', 'm', 'ec', 'gsl', ..., 'ntl'], ['.../include', '.../include/python...', '.../python.../numpy/core/include', '...', '.../sage/ext', '.../cysignals'], 'c', [], ['-w', '-O2'],...) sage: s, libs, inc, lang, f, args, libdirs = _pyx_preparse("# clang c++\n #clib foo\n # cinclude bar\n") doctest:...: DeprecationWarning: the Sage-specific Cython pragma '#clang' is deprecated; use '# distutils: language' instead See http://trac.sagemath.org/24105 for details. doctest:...: DeprecationWarning: the Sage-specific Cython pragma '#clib' is deprecated; use '# distutils: libraries' instead See http://trac.sagemath.org/24105 for details. doctest:...: DeprecationWarning: the Sage-specific Cython pragma '#cinclude' is deprecated; use '# distutils: include_dirs' instead See http://trac.sagemath.org/24105 for details. sage: lang 'c++' sage: libs ['foo', 'mpfr', 'gmp', 'gmpxx', 'stdc++', 'pari', 'm', 'ec', 'gsl', ..., 'ntl'] sage: libs[1:] == sage.misc.cython.standard_libs True sage: inc ['bar', '.../include', '.../include/python...', '.../python.../numpy/core/include', '...', '.../sage/ext', '.../cysignals'] sage: s, libs, inc, lang, f, args, libdirs = _pyx_preparse("# cargs -O3 -ggdb\n") doctest:...: DeprecationWarning: the Sage-specific Cython pragma '#cargs' is deprecated; use '# distutils: extra_compile_args' instead See http://trac.sagemath.org/24105 for details. sage: args ['-w', '-O2', '-O3', '-ggdb'] TESTS:: sage: from sage.misc.cython import pyx_preparse sage: _ = pyx_preparse("") doctest:...: DeprecationWarning: pyx_preparse is deprecated. Please use sage.misc.cython._pyx_preparse instead. See http://trac.sagemath.org/24105 for details. """ lang, s = _parse_keywords('clang', s) if lang: lang = lang[0].lower() # this allows both C++ and c++ else: lang = "c" v, s = _parse_keywords('clib', s) libs = v + standard_libs additional_source_files, s = _parse_keywords('cfile', s) v, s = _parse_keywords('cinclude', s) inc = [_environ_parse(x.replace('"','').replace("'","")) for x in v] + sage_include_directories() args, s = _parse_keywords('cargs', s) args = ['-w','-O2'] + args libdirs = cblas_library_dirs # Add cysignals directory to includes for path in sys.path: cysignals_path = os.path.join(path, "cysignals") if os.path.isdir(cysignals_path): inc.append(cysignals_path) return s, libs, inc, lang, additional_source_files, args, libdirs
def cython(filename, verbose=0, compile_message=False, use_cache=False, create_local_c_file=False, annotate=True, sage_namespace=True, create_local_so_file=False): r""" Compile a Cython file. This converts a Cython file to a C (or C++ file), and then compiles that. The .c file and the .so file are created in a temporary directory. INPUT: - ``filename`` -- the name of the file to be compiled. Should end with 'pyx'. - ``verbose`` (integer, default 0) -- level of verbosity. A negative value ensures complete silence. - ``compile_message`` (bool, default False) -- if True, print ``'Compiling <filename>...'`` to the standard error. - ``use_cache`` (bool, default False) -- if True, check the temporary build directory to see if there is already a corresponding .so file. If so, and if the .so file is newer than the Cython file, don't recompile, just reuse the .so file. - ``create_local_c_file`` (bool, default False) -- if True, save a copy of the ``.c`` or ``.cpp`` file in the current directory. - ``annotate`` (bool, default True) -- if True, create an html file which annotates the conversion from .pyx to .c. By default this is only created in the temporary directory, but if ``create_local_c_file`` is also True, then save a copy of the .html file in the current directory. - ``sage_namespace`` (bool, default True) -- if True, import ``sage.all``. - ``create_local_so_file`` (bool, default False) -- if True, save a copy of the compiled .so file in the current directory. OUTPUT: a tuple ``(name, dir)`` where ``name`` is the name of the compiled module and ``dir`` is the directory containing the generated files. TESTS: Before :trac:`12975`, it would have been needed to write ``#clang c++``, but upper case ``C++`` has resulted in an error. Using pkgconfig to find the libraries, headers and macros. This is a work around while waiting for :trac:`22461` which will offer a better solution:: sage: code = [ ....: "#clang C++", ....: "from sage.rings.polynomial.multi_polynomial_libsingular cimport MPolynomial_libsingular", ....: "from sage.libs.singular.polynomial cimport singular_polynomial_pow", ....: "def test(MPolynomial_libsingular p):", ....: " singular_polynomial_pow(&p._poly, p._poly, 2, p._parent_ring)"] sage: cython(os.linesep.join(code)) The function ``test`` now manipulates internal C data of polynomials, squaring them:: sage: P.<x,y>=QQ[] sage: test(x) sage: x x^2 Check that compiling C++ code works:: sage: cython("# distutils: language = c++\n"+ ....: "from libcpp.vector cimport vector\n" ....: "cdef vector[int] * v = new vector[int](4)\n") Check that compiling C++ code works when creating a local C file, first moving to a tempdir to avoid clutter. Before :trac:`22113`, the create_local_c_file argument was not tested for C++ code:: sage: d = sage.misc.temporary_file.tmp_dir() sage: os.chdir(d) sage: with open("test.pyx", 'w') as f: ....: _ = f.write("# distutils: language = c++\n" ....: "from libcpp.vector cimport vector\n" ....: "cdef vector[int] * v = new vector[int](4)\n") sage: output = sage.misc.cython.cython("test.pyx", create_local_c_file=True) Accessing a ``.pxd`` file from the current directory works:: sage: d = sage.misc.temporary_file.tmp_dir() sage: os.chdir(d) sage: with open("helper.pxd", 'w') as f: ....: _ = f.write("cdef inline int the_answer(): return 42") sage: cython(''' ....: from helper cimport the_answer ....: print(the_answer()) ....: ''') 42 Warning and error messages generated by Cython are properly handled. Warnings are only shown if verbose >= 0:: sage: code = ''' ....: def test_unreachable(): ....: raise Exception ....: return 42 ....: ''' sage: cython(code, verbose=-1) sage: cython(code, verbose=0) warning: ...:4:4: Unreachable code sage: cython("foo = bar\n") Traceback (most recent call last): ... RuntimeError: Error compiling Cython file: ------------------------------------------------------------ ... foo = bar ^ ------------------------------------------------------------ <BLANKLINE> ...:1:6: undeclared name not builtin: bar sage: cython("cdef extern from 'no_such_header_file': pass") Traceback (most recent call last): ... RuntimeError: ... """ if not filename.endswith('pyx'): print( "Warning: file (={}) should have extension .pyx".format(filename), file=sys.stderr) # base is the name of the .so module that we create. If we are # creating a local shared object file, we use a more natural # naming convention. If we are not creating a local shared object # file, the main constraint is that it is unique and determined by # the file that we're running Cython on, so that in some cases we # can cache the result (e.g., recompiling the same pyx file during # the same session). if create_local_so_file: base, ext = os.path.splitext(os.path.basename(filename)) else: base = os.path.abspath(filename) base = sanitize(base) # This is the *temporary* directory where we store the pyx file. # This is deleted when Sage exits, which means pyx files must be # rebuilt every time Sage is restarted at present. target_dir = os.path.join(SPYX_TMP, base) # Build directory for Cython/distutils build_dir = os.path.join(target_dir, "build") if os.path.exists(target_dir): # There is already a module here. Maybe we do not have to rebuild? # Find the name. if use_cache: from sage.misc.sageinspect import loadable_module_extension prev_so = [ F for F in os.listdir(target_dir) if F.endswith(loadable_module_extension()) ] if len(prev_so) > 0: prev_so = prev_so[ 0] # should have length 1 because of deletes below if os.path.getmtime(filename) <= os.path.getmtime( '%s/%s' % (target_dir, prev_so)): # We do not have to rebuild. return prev_so[:-len(loadable_module_extension() )], target_dir # Delete all ordinary files in target_dir for F in os.listdir(target_dir): G = os.path.join(target_dir, F) if os.path.isdir(G): continue try: os.unlink(G) except OSError: pass else: sage_makedirs(target_dir) if create_local_so_file: name = base else: global sequence_number if base not in sequence_number: sequence_number[base] = 0 name = '%s_%s' % (base, sequence_number[base]) # increment the sequence number so will use a different one next time. sequence_number[base] += 1 if compile_message: sys.stderr.write("Compiling {}...\n".format(filename)) sys.stderr.flush() # Copy original file to the target directory. pyxfile = os.path.join(target_dir, name + ".pyx") shutil.copy(filename, pyxfile) # Add current working directory to includes. This is needed because # we cythonize from a different directory. See Trac #24764. includes = [os.getcwd()] + sage_include_directories() # Now do the actual build, directly calling Cython and distutils from Cython.Build import cythonize from Cython.Compiler.Errors import CompileError import Cython.Compiler.Options from distutils.dist import Distribution from distutils.core import Extension from distutils.log import set_verbosity set_verbosity(verbose) Cython.Compiler.Options.annotate = annotate Cython.Compiler.Options.embed_pos_in_docstring = True Cython.Compiler.Options.pre_import = "sage.all" if sage_namespace else None ext = Extension( name, sources=[pyxfile], extra_compile_args=["-w"], # no warnings libraries=standard_libs, library_dirs=standard_libdirs) directives = dict(language_level=sys.version_info[0]) try: # Change directories to target_dir so that Cython produces the correct # relative path; https://trac.sagemath.org/ticket/24097 with restore_cwd(target_dir): try: ext, = cythonize([ext], aliases=cython_aliases(), include_path=includes, compiler_directives=directives, quiet=(verbose <= 0), errors_to_stderr=False, use_listing_file=True) finally: # Read the "listing file" which is the file containing # warning and error messages generated by Cython. try: with open(name + ".lis") as f: cython_messages = f.read() except IOError: cython_messages = "Error compiling Cython file" except CompileError: raise RuntimeError(cython_messages.strip()) if verbose >= 0: sys.stderr.write(cython_messages) sys.stderr.flush() if create_local_c_file: shutil.copy(os.path.join(target_dir, ext.sources[0]), os.curdir) if annotate: shutil.copy(os.path.join(target_dir, name + ".html"), os.curdir) # This emulates running "setup.py build" with the correct options dist = Distribution() dist.ext_modules = [ext] dist.include_dirs = includes buildcmd = dist.get_command_obj("build") buildcmd.build_base = build_dir buildcmd.build_lib = target_dir try: # Capture errors from distutils and its child processes with open(os.path.join(target_dir, name + ".err"), 'w+') as errfile: try: # Redirect stderr to errfile. We use the file descriptor # number "2" instead of "sys.stderr" because we really # want to redirect the messages from GCC. These are sent # to the actual stderr, regardless of what sys.stderr is. sys.stderr.flush() with redirection(2, errfile, close=False): dist.run_command("build") finally: errfile.seek(0) distutils_messages = errfile.read() except Exception as msg: msg = str(msg) + "\n" + distutils_messages raise RuntimeError(msg.strip()) if verbose >= 0: sys.stderr.write(distutils_messages) sys.stderr.flush() if create_local_so_file: # Copy module to current directory from sage.misc.sageinspect import loadable_module_extension shutil.copy( os.path.join(target_dir, name + loadable_module_extension()), os.curdir) return name, target_dir
log.info( f"Discovered Python/Cython sources, time: {(time.time() - t):.2f} seconds." ) # from sage_build_cython: import Cython.Compiler.Options Cython.Compiler.Options.embed_pos_in_docstring = True gdb_debug = os.environ.get('SAGE_DEBUG', None) != 'no' try: from Cython.Build import cythonize from sage.env import cython_aliases, sage_include_directories extensions = cythonize( ["sage/**/*.pyx"], exclude=files_to_exclude, include_path=sage_include_directories(use_sources=True) + ['.'], compile_time_env=compile_time_env_variables(), compiler_directives=compiler_directives(False), aliases=cython_aliases(), create_extension=create_extension, gdb_debug=gdb_debug, nthreads=4) except Exception as exception: log.warn( f"Exception while cythonizing source files: {repr(exception)}") raise # ######################################################## # ## Distutils # ######################################################## code = setup(
from setuptools import setup, Extension from codecs import open # To use a consistent encoding from os import path from Cython.Build import cythonize import Cython.Compiler.Options from sage.env import sage_include_directories ext_modules = [ Extension('slabbe.kolakoski_word_pyx', sources = [path.join('slabbe','kolakoski_word_pyx.pyx')],), Extension('slabbe.mult_cont_frac_pyx', sources = [path.join('slabbe','mult_cont_frac_pyx.pyx')], include_dirs=sage_include_directories()), Extension('slabbe.diophantine_approx_pyx', sources = [path.join('slabbe','diophantine_approx_pyx.pyx')], include_dirs=sage_include_directories())] # Get the long description from the README file here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup(name='slabbe', version=open("VERSION").read().strip(), description="Sebastien Labbe's Research code", long_description=long_description, classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable
def pyx_preparse(s): r""" Preparse a pyx file: * include ``cdefs.pxi``, ``signals.pxi`` from ``cysignals``, ``stdsage.pxi`` * parse ``clang`` pragma (c or c++) * parse ``clib`` pragma (additional libraries to link in) * parse ``cinclude`` (additional include directories) * parse ``cfile`` (additional files to be included) * parse ``cargs`` (additional parameters passed to the compiler) The pragmas: - ``clang`` - may be either ``'c'`` or ``'c++'`` indicating whether a C or C++ compiler should be used - ``clib`` - additional libraries to be linked in, the space separated list is split and passed to distutils. - ``cinclude`` - additional directories to search for header files. The space separated list is split and passed to distutils. - ``cfile`` - additional C or C++ files to be compiled. Also, :envvar:`$SAGE_SRC` and :envvar:`$SAGE_LOCAL` are expanded, but other environment variables are not. - ``cargs`` - additional parameters passed to the compiler OUTPUT: preamble, libs, includes, language, files, args EXAMPLES:: sage: from sage.misc.cython import pyx_preparse sage: pyx_preparse("") ('\ninclude "cysignals/signals.pxi" # ctrl-c interrupt block support\ninclude "stdsage.pxi"\n\ninclude "cdefs.pxi"\n', ['mpfr', 'gmp', 'gmpxx', 'stdc++', 'pari', 'm', 'ec', 'gsl', ..., 'ntl'], ['.../include', '.../include/python...', '.../lib/python.../site-packages/numpy/core/include', '...', '.../sage/ext', '.../cysignals'], 'c', [], ['-w', '-O2'],...) sage: s, libs, inc, lang, f, args, libdirs = pyx_preparse("# clang c++\n #clib foo\n # cinclude bar\n") sage: lang 'c++' sage: libs ['foo', 'mpfr', 'gmp', 'gmpxx', 'stdc++', 'pari', 'm', 'ec', 'gsl', ..., 'ntl'] sage: libs[1:] == sage.misc.cython.standard_libs True sage: inc ['bar', '.../include', '.../include/python...', '.../lib/python.../site-packages/numpy/core/include', '...', '.../sage/ext', '.../cysignals'] sage: s, libs, inc, lang, f, args, libdirs = pyx_preparse("# cargs -O3 -ggdb\n") sage: args ['-w', '-O2', '-O3', '-ggdb'] TESTS:: sage: module = sage.misc.cython.import_test("trac11680") # long time (7s on sage.math, 2012) sage: R.<x> = QQ[] sage: module.evaluate_at_power_of_gen(x^3 + x - 7, 5) # long time x^15 + x^5 - 7 """ from sage.env import sage_include_directories lang, s = parse_keywords('clang', s) if lang: lang = lang[0].lower() # this allows both C++ and c++ else: lang = "c" v, s = parse_keywords('clib', s) libs = v + standard_libs additional_source_files, s = parse_keywords('cfile', s) v, s = parse_keywords('cinclude', s) inc = [environ_parse(x.replace('"','').replace("'","")) for x in v] + sage_include_directories() s = """\ninclude "cdefs.pxi"\n""" + s s = """\ninclude "cysignals/signals.pxi" # ctrl-c interrupt block support\ninclude "stdsage.pxi"\n""" + s args, s = parse_keywords('cargs', s) args = ['-w','-O2'] + args libdirs = cblas_library_dirs # Add cysignals directory to includes for path in sys.path: cysignals_path = os.path.join(path, "cysignals") if os.path.isdir(cysignals_path): inc.append(cysignals_path) return s, libs, inc, lang, additional_source_files, args, libdirs
else: print("Using gurobi_include_directories={}, libraries={}, library_dirs={}".format( gurobi_include_directories, gurobi_libs, gurobi_lib_directories), file=sys.stderr) if use_rpath: lib_args = dict(libraries=gurobi_libs, library_dirs=gurobi_lib_directories, runtime_library_dirs=gurobi_lib_directories) else: lib_args = dict(extra_link_args=gurobi_lib_files) # Cython modules ext_modules = [Extension('sage_numerical_backends_gurobi.gurobi_backend', sources = [os.path.join('sage_numerical_backends_gurobi', 'gurobi_backend.pyx')], include_dirs=sage_include_directories() + gurobi_include_directories, **lib_args) ] ## SageMath 8.1 (included in Ubuntu bionic 18.04 LTS) does not have sage.cpython.string; ## it was introduced in 8.2. compile_time_env = {'HAVE_SAGE_CPYTHON_STRING': False, 'HAVE_ADD_COL_UNTYPED_ARGS': False} print("Checking whether HAVE_SAGE_CPYTHON_STRING...", file=sys.stderr) try: import sage.cpython.string compile_time_env['HAVE_SAGE_CPYTHON_STRING'] = True except ImportError: pass
if not os.path.exists(pyx_dst): log.error("Failed to generate %s" % pyx_dst) sys.exit(1) # This is a workaround for Ubuntu on Travis where update=True results in empty # files if os.path.getsize(pyx_dst) == 0: log.warn("Using fallback since target is empty: %s" % pyx_dst) copy_file(pyx_src, pyx_dst, update=False) if not os.path.exists(pyx_dst) or os.path.getsize(pyx_dst) == 0: log.error("Failed to generate %s" % pyx_dst) sys.exit(1) ext_modules = [ cythonize([ Extension("fgb_sage." + name, include_dirs=["local/include"] + sage_include_directories(), library_dirs=["local/lib"], libraries=[ "fgb", "fgbexp", "gb", "gbexp", "minpoly", "minpolyvgf", "gmp", "m" ], extra_compile_args=["-std=c++11", "-fopenmp"], extra_link_args=["-fopenmp"], define_macros=[("LIBMODE", libmode), ("FGB_MAC", 1 if UNAME == 'Darwin' else 0), ("FGB_MAC_MAX_INPUT", 100000)], sources=[os.path.join(SRC, name + ".pyx")]) ], compile_time_env=dict(PY_LIBMODE=libmode, PY_FGB_MAC=(UNAME == 'Darwin')), compiler_directives=dict(language_level=2),
if cbc_pc: print("Using pkgconfig: {}".format(sorted(cbc_pc.items())), file=sys.stderr) cbc_libs = cbc_pc['libraries'] cbc_library_dirs = cbc_pc['library_dirs'] cbc_include_dirs = cbc_pc['include_dirs'] ext_modules = [ Extension('sage_numerical_backends_coin.coin_backend', sources=[ os.path.join('sage_numerical_backends_coin', 'coin_backend.pyx') ], libraries=cbc_libs, include_dirs=sage_include_directories() + cbc_include_dirs, library_dirs=cbc_library_dirs, extra_compile_args=['-std=c++11']) ] ## SageMath 8.1 (included in Ubuntu bionic 18.04 LTS) does not have sage.cpython.string; ## it was introduced in 8.2. compile_time_env = { 'HAVE_SAGE_CPYTHON_STRING': False, 'HAVE_ADD_COL_UNTYPED_ARGS': False } print("Checking whether HAVE_SAGE_CPYTHON_STRING...", file=sys.stderr) try: import sage.cpython.string compile_time_env['HAVE_SAGE_CPYTHON_STRING'] = True
def _pyx_preparse(s): r""" Preparse a pyx file: * parse ``clang`` pragma (c or c++) * parse ``clib`` pragma (additional libraries to link in) * parse ``cinclude`` (additional include directories) * parse ``cfile`` (additional files to be included) * parse ``cargs`` (additional parameters passed to the compiler) The pragmas: - ``clang`` - may be either ``'c'`` or ``'c++'`` indicating whether a C or C++ compiler should be used - ``clib`` - additional libraries to be linked in, the space separated list is split and passed to distutils. - ``cinclude`` - additional directories to search for header files. The space separated list is split and passed to distutils. - ``cfile`` - additional C or C++ files to be compiled. Also, :envvar:`$SAGE_SRC` and :envvar:`$SAGE_LOCAL` are expanded, but other environment variables are not. - ``cargs`` - additional parameters passed to the compiler OUTPUT: preamble, libs, includes, language, files, args EXAMPLES:: sage: from sage.misc.cython import _pyx_preparse sage: _pyx_preparse("") ('', ['mpfr', 'gmp', 'gmpxx', 'stdc++', 'pari', 'm', 'ec', 'gsl', ..., 'ntl'], ['.../include', '.../include/python...', '.../python.../numpy/core/include', '...', '.../sage/ext', '.../cysignals'], 'c', [], ['-w', '-O2'],...) sage: s, libs, inc, lang, f, args, libdirs = _pyx_preparse("# clang c++\n #clib foo\n # cinclude bar\n") doctest:...: DeprecationWarning: the Sage-specific Cython pragma '#clang' is deprecated; use '# distutils: language' instead See http://trac.sagemath.org/24105 for details. doctest:...: DeprecationWarning: the Sage-specific Cython pragma '#clib' is deprecated; use '# distutils: libraries' instead See http://trac.sagemath.org/24105 for details. doctest:...: DeprecationWarning: the Sage-specific Cython pragma '#cinclude' is deprecated; use '# distutils: include_dirs' instead See http://trac.sagemath.org/24105 for details. sage: lang 'c++' sage: libs ['foo', 'mpfr', 'gmp', 'gmpxx', 'stdc++', 'pari', 'm', 'ec', 'gsl', ..., 'ntl'] sage: libs[1:] == sage.misc.cython.standard_libs True sage: inc ['bar', '.../include', '.../include/python...', '.../python.../numpy/core/include', '...', '.../sage/ext', '.../cysignals'] sage: s, libs, inc, lang, f, args, libdirs = _pyx_preparse("# cargs -O3 -ggdb\n") doctest:...: DeprecationWarning: the Sage-specific Cython pragma '#cargs' is deprecated; use '# distutils: extra_compile_args' instead See http://trac.sagemath.org/24105 for details. sage: args ['-w', '-O2', '-O3', '-ggdb'] TESTS:: sage: module = sage.misc.cython.import_test("trac11680") # long time (7s on sage.math, 2012) sage: R.<x> = QQ[] sage: module.evaluate_at_power_of_gen(x^3 + x - 7, 5) # long time x^15 + x^5 - 7 :: sage: from sage.misc.cython import pyx_preparse sage: _ = pyx_preparse("") doctest:...: DeprecationWarning: pyx_preparse is deprecated. Please use sage.misc.cython._pyx_preparse instead. See http://trac.sagemath.org/24105 for details. """ lang, s = _parse_keywords('clang', s) if lang: lang = lang[0].lower() # this allows both C++ and c++ else: lang = "c" v, s = _parse_keywords('clib', s) libs = v + standard_libs additional_source_files, s = _parse_keywords('cfile', s) v, s = _parse_keywords('cinclude', s) inc = [_environ_parse(x.replace('"', '').replace("'", "")) for x in v] + sage_include_directories() args, s = _parse_keywords('cargs', s) args = ['-w', '-O2'] + args libdirs = cblas_library_dirs # Add cysignals directory to includes for path in sys.path: cysignals_path = os.path.join(path, "cysignals") if os.path.isdir(cysignals_path): inc.append(cysignals_path) return s, libs, inc, lang, additional_source_files, args, libdirs
# For the tests class SageTest(TestCommand): def run_tests(self): errno = os.system("sage -t --force-lib pydeformation") if errno != 0: sys.exit(1) if not os.path.isfile( os.path.join(SAGE_LOCAL, "include", "deformation", "deformation.h")): print("The deformation library is not installed.") sys.exit(1) cythonize_dir = "build" kwds = {"include_dirs": sage_include_directories()} extensions = [ Extension("pydeformation.deformation", ["pydeformation/deformation.pyx"], **kwds) ] setup( name="pydeformation", author="Jean-Pierre Flori", author_email="*****@*****.**", url="https://github.com/jpflori/pydeformation", license="GNU General Public License, version 3 or later", description="Wrapper for deformation library by Sebastian Pancratz", long_description=readfile( "README.rst"), # get the long description from the README
DEVEL = False if DEVEL: extra_compile_args.append('-ggdb') import subprocess # Work around GCC-4.8 bug which miscompiles some sig_on() statements: # * http://trac.sagemath.org/sage_trac/ticket/14460 # * http://trac.sagemath.org/sage_trac/ticket/20226 # * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56982 if subprocess.call("""$CC --version | grep -i 'gcc.* 4[.]8' >/dev/null """, shell=True) == 0: extra_compile_args.append('-fno-tree-copyrename') # Search for dependencies in the source tree and add to the list of include directories include_dirs = sage_include_directories(use_sources=True) # Look for libraries only in what is configured already through distutils # and environment variables library_dirs = [] class sage_build_cython(Command): name = 'build_cython' description = "compile Cython extensions into C/C++ extensions" user_options = [ # TODO: Temporarily disabled since the value for this option is # hard-coded; change as part of work on #21525 #('build-dir=', 'd', # "directory for compiled C/C++ sources and header files"),
sys.exit(1) if __name__ == "__main__": # The next block is if there are some cython files from setuptools import Extension from Cython.Build import cythonize import Cython.Compiler.Options from sage.env import sage_include_directories # Cython modules ext_modules = [ Extension( 'darmonpoints.mixed_extension', sources=[os.path.join('darmonpoints', 'mixed_extension.pyx')], include_dirs=sage_include_directories()) ] # Specify the required Sage version sage_required_version = u'>=7.4' REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()] setup( name="darmonpoints", version=readfile( "VERSION"), # the VERSION file is shared with the documentation description='Compute non-archimedean Darmon points', long_description=readfile( "README.rst"), # get the long description from the README url='https://github.com/mmasdeu/darmonpoints', author='Marc Masdeu',
extra_compile_args = ['-std=c99'], ), Extension('abelfunctions.riemann_theta.riemann_theta', sources=[os.path.join('abelfunctions','riemann_theta', 'finite_sum.c'), os.path.join('abelfunctions','riemann_theta', 'riemann_theta.pyx')], extra_compile_args = ['-std=c99'], ), ] # parameters for all extension modules: # # * most modules depend on Sage and Numpy. Provide include directories. # * disable warnings in gcc step INCLUDES = sage_include_directories() INCLUDES_NUMPY = get_numpy_include_dirs() for mod in ext_modules: mod.include_dirs.extend(INCLUDES) mod.include_dirs.extend(INCLUDES_NUMPY) mod.extra_compile_args.append('-w') packages = [ 'abelfunctions', 'abelfunctions.riemann_theta', 'abelfunctions.utilities' ] class clean(Command): """Cleans files so you should get the same copy as in git.""" description = 'remove build files'
'integer_points.pyx') ]), Extension('abelfunctions.riemann_theta.riemann_theta', sources=[ os.path.join('abelfunctions', 'riemann_theta', 'finite_sum.c'), os.path.join('abelfunctions', 'riemann_theta', 'riemann_theta.pyx') ]), ] # parameters for all extension modules: # # * most modules depend on Sage and Numpy. Provide include directories. # * disable warnings in gcc step INCLUDES = sage_include_directories() INCLUDES_NUMPY = get_numpy_include_dirs() for mod in ext_modules: mod.include_dirs.extend(INCLUDES) mod.include_dirs.extend(INCLUDES_NUMPY) mod.extra_compile_args.append('-w') mod.extra_compile_args.append('-std=c99') packages = [ 'abelfunctions', 'abelfunctions.riemann_theta', 'abelfunctions.utilities' ] class clean(Command): """Cleans files so you should get the same copy as in git.""" description = 'remove build files'
if '-np' in sys.argv: print 'Not including psage in build' sys.argv.remove('-np') INSTALL_PSAGE = False else: INSTALL_PSAGE = True print 'Also installing psage dependencies...' #pt = tarfile.open('psage.tar.bz2', mode='r:bz2') #pt.extractall() package_dir = {'psage': 'psage/psage'} print package_dir #from module_list import ext_modules,aliases include_dirs = sage_include_directories(use_sources=True) include_dirs = include_dirs + [os.path.join(SAGE_LIB,"cysignals")] include_dirs = include_dirs + [os.path.join(SAGE_LIB,"sage/ext/")] extra_compile_args = [ "-fno-strict-aliasing" ] extra_link_args = [ ] DEVEL = False if DEVEL: extra_compile_args.append('-ggdb') # Work around GCC-4.8.0 bug which miscompiles some sig_on() statements, # as witnessed by a doctest in sage/libs/gap/element.pyx if the # compiler flag -Og is used. See also # * http://trac.sagemath.org/sage_trac/ticket/14460 # * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56982