Read about our upcoming Code of Conduct on this issue

purepymake.py 15.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
"""Maker for fluidfft
=====================

The compilation process of the normal build_ext is not adapted for this project
since many files are common to different extensions but can be computed only
once.

All files are compiled manually and we launch the compilations asynchronously.

Notes
-----

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
- compilation:

  $CC $OPT $BASECFLAGS $CONFIGURE_CFLAGS $CCSHARED \
    $(sys.prefix)/include/python$('.'.join(sys.version_info[:2])) \
    -c path/source.cpp -o build/temp.linux-x86_64-2.7/path/source.o

- linker:

  $CXX -shared \
    -Wl,-rpath=$(sys.prefix)/lib/python$('.'.join(sys.version_info[:2])) \
    $(list object files) -L/opt/python/2.7.9/lib -lpython2.7 \
    -o build/temp.linux-x86_64-2.7/path/to/mod.so

  $CXX -shared ~$(LDSHARED) $(CONFIGURE_LDFLAGS) $(CONFIGURE_CFLAGS) \
  $(list object files)

"""

from __future__ import print_function

import sys
import platform
from time import sleep
import os
from datetime import datetime
from distutils import sysconfig
import subprocess
from copy import copy
41
import importlib
42
import multiprocessing
43
import warnings
44

45
46
47
48
49
from distutils.ccompiler import CCompiler
from setuptools.command.build_ext import build_ext

import numpy as np

Pierre Augier's avatar
Pierre Augier committed
50
51
config_vars = sysconfig.get_config_vars()

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

def can_import(pkg_name, check_version=None):
    try:
        pkg = importlib.import_module(pkg_name)
    except ImportError:
        return False
    else:
        if check_version is not None:
            if pkg.__version__ < check_version:
                raise ValueError('Please upgrade to {} >= {}'.format(
                    pkg_name, check_version))
        return True


can_import_cython = can_import('cython')
can_import_mpi4py = can_import('mpi4py', '2.0.0')
can_import_pythran = can_import('pythran')

if can_import_cython:
71
72
73
74
75
    from Cython.Compiler.Main import \
        CompilationOptions, \
        default_options as cython_default_options, \
        compile_single as cython_compile

76

77
78
79
80
try:
    from concurrent.futures import ThreadPoolExecutor as Pool
    PARALLEL_COMPILE = True
except ImportError:
81
82
83
    #  pip install futures  # to use concurrent.futures Python 2.7 backport
    from multiprocessing.pool import ThreadPool as Pool
    PARALLEL_COMPILE = True
84

85
86
short_version = '.'.join([str(i) for i in sys.version_info[:2]])

87
88
path_lib_python = os.path.join(
    sys.prefix, 'lib', 'python' + short_version, 'site-packages')
89
90
91
92

path_tmp = 'build/temp.' + '-'.join(
    [platform.system().lower(), platform.machine(), short_version])

93
94
95
path_lib = 'build/lib.' + '-'.join(
    [platform.system().lower(), platform.machine(), short_version])

96

97
98
99
100
101
102
103
def check_deps():
    def check_and_print(pkg='', result=None):
        if result is None:
            result = can_import(pkg)

        print('{} installed: '.format(pkg).rjust(25) + repr(result))

104
    print('*' * 50)
105
106
107
    check_and_print('numpy')
    check_and_print('mpi4py', can_import_mpi4py)
    check_and_print('cython', can_import_cython)
108
    check_and_print('pythran', can_import_pythran)
109
    check_and_print('mako')
110
    print('*' * 50)
111
112
113
114
115


check_deps()


116
117
118
119
120
def modification_date(filename):
    t = os.path.getmtime(filename)
    return datetime.fromtimestamp(t)


121
class CompilationError(Exception):
paugier's avatar
paugier committed
122
123
124
    def __init__(self, command, out, err):
        self.message = '\ncommand:\n{}\nstdout:\n {}\nstderr:\n{}'.format(
            command, out.decode(), err.decode())
125
126
127
128
129
130
        super(CompilationError, self). __init__()

    def __str__(self):
        return super(CompilationError, self).__str__() + self.message


131
class Extension(object):
132
    def __init__(self, name, sources=None, libraries=None, language=None):
133
134
        self.name = name
        self.sources = sources
135
        self.libraries = libraries
136
137
        self.language = language

Ashwin Vishnu's avatar
Ashwin Vishnu committed
138
139
140
    def __repr__(self):
        return 'purepymake.Extension<{}>'.format(self.name)

141

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def has_to_build(output_file, input_files):
    if not os.path.exists(output_file):
        return True
    mod_date_output = modification_date(output_file)
    for input_file in input_files:
        if mod_date_output < modification_date(input_file):
            return True
    return False


class CommandsRunner(object):
    nb_proc = 4

    def __init__(self, commands):
        self.commands = commands
        self._processes = []

    def run(self):
        while len(self.commands) != 0:
            if len(self._processes) < self.nb_proc:
                command = self.commands.pop()
                self._launch_process(command)

            sleep(0.1)
            self._check_processes()

        while len(self._processes) != 0:
            sleep(0.1)
            self._check_processes()

    def _launch_process(self, command):
        print('launching command:\n' + ' '.join(command))
        process = subprocess.Popen(
            command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process.command = ' '.join(command)
        self._processes.append(process)

    def _check_processes(self):
180
        for process in copy(self._processes):
181
182
183
184
185
186
187
188
189
190
            if process.poll() is not None:
                self._processes.remove(process)
                if process.returncode != 0:
                    out, err = process.communicate()
                    raise CompilationError(process.command, out, err)


class FunctionsRunner(CommandsRunner):
    def _launch_process(self, command):
        func, args, kwargs = command
191
192
        print('launching command:\n{}(\n    *args={},\n    **kwargs={})'.format(
            func.__name__, args, kwargs))
193
194
195
196
197
198
199
        process = multiprocessing.Process(
            target=func, args=args, kwargs=kwargs)
        process.start()
        process.command = command
        self._processes.append(process)

    def _check_processes(self):
200
        for process in copy(self._processes):
201
202
203
204
205
            if process.exitcode is not None:
                self._processes.remove(process)


def make_function_cpp_from_pyx(cpp_file, pyx_file,
206
                               include_dirs=None,
207
208
                               compiler_directives={},
                               full_module_name=None, options={}):
209
210
211
212
    path_dir = os.path.split(cpp_file)[0]
    if not os.path.exists(path_dir):
        os.makedirs(path_dir)

213
214
    if not has_to_build(cpp_file, (pyx_file,)):
        return
215

216
217
    if not can_import_cython:
        raise ImportError('Can not import Cython.')
218

219
220
    options = CompilationOptions(
        cython_default_options,
221
        include_path=include_dirs,
222
223
        output_file=cpp_file,
        cplus=True,
224
        compiler_directives=compiler_directives,
225
        compile_time_env={'MPI4PY': can_import_mpi4py})
226

227
228
229
    # return (func, args, kwargs)
    return (cython_compile, (pyx_file,),
            {'options': options, 'full_module_name': full_module_name})
230
231


232
233
def make_command_obj_from_cpp(obj_file, cpp_file, include_dirs=None,
                              options=None):
234
235
236
237
    path_dir = os.path.split(obj_file)[0]
    if not os.path.exists(path_dir):
        os.makedirs(path_dir)

238
239
    if not has_to_build(obj_file, (cpp_file,)):
        return
240

241
    keys = ['CXX', 'OPT', 'BASECFLAGS', 'CFLAGS', 'CCSHARED']
242

243
    conf_vars = copy(config_vars)
244

245
246
    # for k in keys:
    #     print(k, conf_vars[k])
247

248
249
250
251
252
    # problem: it replaces the value (add it better?)
    if options is not None:
        for k, v in options.items():
            if v is not None:
                conf_vars[k] = v
253

254
    command = ' '.join([conf_vars[k] for k in keys])
255

256
257
258
259
260
261
262
263
264
    if cpp_file.endswith('.cu'):
        command = (
            'nvcc -m64 '
            '-gencode arch=compute_20,code=sm_20 '
            '-gencode arch=compute_30,code=sm_30 '
            '-gencode arch=compute_32,code=sm_32 '
            '-gencode arch=compute_35,code=sm_35 '
            '-gencode arch=compute_50,code=sm_50 '
            '-gencode arch=compute_50,code=compute_50 -Xcompiler -fPIC')
265

266
267
    command = [w for w in command.split()
               if w not in ['-g', '-DNDEBUG', '-Wstrict-prototypes']]
268

269
270
    if can_import_mpi4py and not cpp_file.endswith('.cu'):
        command[0] = os.getenv('MPICXX', 'mpicxx')
271

272
    includepy = [conf_vars['INCLUDEPY']]
273

274
275
276
277
    if include_dirs is None:
        include_dirs = includepy
    else:
        include_dirs = includepy + include_dirs
278

279
280
281
282
283
284
285
286
287
288
    # this should not be here! No hard-coded path...
    # if 'cufft' in cpp_file:
    #     include_dirs.extend([
    #         '/opt/cuda/NVIDIA_CUDA-6.0_Samples/common/inc/'])

    # cu + mpi ? No hard-coded path...
    # if cpp_file.endswith('.cu'):
    #     include_dirs.extend([
    #         '/usr/lib/openmpi/include',
    #         '/usr/lib/openmpi/include/openmpi'])
289

290
291
292
    command += ['-I' + incdir for incdir in include_dirs]
    command += ['-c', cpp_file, '-o', obj_file]
    return command
293
294


295
def make_command_ext_from_objs(
296
297
        ext_file, obj_files, lib_flags=None, lib_dirs=None,
        options=None):
298

299
300
301
302
303
304
    if not has_to_build(ext_file, obj_files):
        return

    path_dir = os.path.split(ext_file)[0]
    if not os.path.exists(path_dir):
        os.makedirs(path_dir)
305

306
307
308
309
310
311
312
313
314
315
    cxx = config_vars['CXX']
    ldshared = config_vars['LDSHARED']

    command = [w for w in ldshared.split()
               if w not in ['-g']]

    if can_import_mpi4py:
        command[0] = os.getenv('MPICXX', 'mpicxx')
    else:
        command[0] = cxx.split()[0]
316

317
318
    if 'cufft' in ext_file:
        command = 'nvcc -Xcompiler -pthread -shared'.split()
319

320
321
322
    command += obj_files + ['-o', ext_file]
    if lib_dirs is not None:
        command.extend(['-L' + lib_dir for lib_dir in lib_dirs])
323

324
325
    if lib_flags is not None:
        command.extend(['-l' + lib for lib in lib_flags])
326

327
    return command
328
329


330
331
332
def make_extensions(extensions,
                    include_dirs=None,
                    lib_dirs_dict=None, lib_flags_dict=None,
333
                    **options):
334
335
336
337
338
339
340

    if all(command not in sys.argv for command in [
            'build_ext', 'install', 'develop']):
        return

    if '--inplace' in sys.argv or 'develop' in sys.argv:
        path_base_output = '.'
341
342
    elif ('install' in sys.argv and
          '--single-version-externally-managed' in sys.argv):
343
344
345
346
347
348
        if can_import_pythran:
            # build_ext will take care of copying .so to site-packages
            path_base_output = path_lib
        else:
            # build_ext will not be invoked
            path_base_output = path_lib_python
349
350
351
352
353
    else:
        path_base_output = path_tmp

    sources = set()
    for ext in extensions:
Ashwin Vishnu's avatar
Ashwin Vishnu committed
354
        print('make_extensions: ', ext)
355
356
        sources.update(ext.sources)

357
    # prepare a dictionary listing all files
358
359
360
361
362
363
364
365
366
367
    files = {}
    extension_files = ['pyx', 'cpp']

    for ext in extension_files:
        files[ext] = []

    for source in sources:
        for ext in extension_files:
            if source.endswith('.' + ext):
                files[ext].append(source)
368
369
        if source.endswith('.cu'):
            files['cpp'].append(source)
370
371
    files['o'] = []

372
373
374
375
376
377
378
379
380
381
382
383
384
385
    # Enable linetrace for Cython extensions while using tox
    if can_import_cython and os.getenv('TOXENV') is not None:
        warnings.warn(
            'Enabling linetrace for coverage tests. Extensions can be really '
            'slow. Recompile for practical use.')
        compiler_directives = {'linetrace': True}
        cython_options = {'CFLAGS': ' -DCYTHON_TRACE_NOGIL=1'}
        if 'CFLAGS' in options:
            options['CFLAGS'] += cython_options['CFLAGS']
        else:
            options.update(cython_options)
    else:
        compiler_directives = {}

386
    # cythonize .pyx files if needed
387
    commands = []
388
389
    for pyx_file in files['pyx']:
        cpp_file = os.path.splitext(pyx_file)[0] + '.cpp'
390

391
392
393
394
395
        full_module_name = None
        for ext in extensions:
            if pyx_file in ext.sources:
                full_module_name = ext.name

396
        command = make_function_cpp_from_pyx(
397
            cpp_file, pyx_file,
398
399
            full_module_name=full_module_name,
            include_dirs=include_dirs,
400
            compiler_directives=compiler_directives,
401
            options=options)
402
403
        if command is not None:
            commands.append(command)
404
405

        files['cpp'].append(cpp_file)
406

407
408
    FunctionsRunner(commands).run()

409
    # compile .cpp files if needed
410
    commands = []
411
412
    for path in files['cpp']:
        result = os.path.join(path_tmp, os.path.splitext(path)[0] + '.o')
413
414
        command = make_command_obj_from_cpp(
            result, path, include_dirs, options)
415
416
        if command is not None:
            commands.append(command)
417
418
        files['o'].append(result)

419
    CommandsRunner(commands).run()
420

421
    # link .o files to produce the .so files if needed
422
423
    files['so'] = []
    commands = []
424
    for ext in extensions:
paugier's avatar
paugier committed
425
        suffix = sysconfig.get_config_var('EXT_SUFFIX') or '.so'
426
        result = os.path.join(path_base_output,
paugier's avatar
paugier committed
427
                              ext.name.replace('.', os.path.sep) + suffix)
428
429
430
        objects = [
            os.path.join(path_tmp, os.path.splitext(source)[0] + '.o')
            for source in ext.sources]
431
432
433
434
435
436
437
438
439
440
441

        lib_dirs = []
        lib_flags = []
        for lib in ext.libraries:
            if lib_dirs_dict is not None and lib in lib_dirs_dict:
                lib_dirs.append(lib_dirs_dict[lib])
            if lib_flags_dict is not None and lib in lib_flags_dict:
                lib_flags.extend(lib_flags_dict[lib])
            else:
                lib_flags.append(lib)

442
        command = make_command_ext_from_objs(
443
            result, objects, lib_dirs=lib_dirs, lib_flags=lib_flags)
444
445
        if command is not None:
            commands.append(command)
446
447
448
        files['so'].append(result)

    # wait for linking
449
    CommandsRunner(commands).run()
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494


# building with pythran

try:
    from pythran.dist import PythranExtension
except ImportError:
    pass


def make_pythran_extensions(modules):
    develop = sys.argv[-1] == 'develop'
    extensions = []
    for mod in modules:
        base_file = mod.replace('.', os.path.sep)
        py_file = base_file + '.py'
        # warning: does not work on Windows (?)
        suffix = sysconfig.get_config_var('EXT_SUFFIX') or '.so'
        bin_file = base_file + suffix
        if not develop or not os.path.exists(bin_file) or \
           modification_date(bin_file) < modification_date(py_file):
            pext = PythranExtension(mod, [py_file],)
            pext.include_dirs.append(np.get_include())
            # bug pythran extension...
            pext.extra_compile_args.extend(['-O3', '-march=native'])
            # pext.extra_compile_args.append('-fopenmp')
            # pext.extra_link_args.extend([])
            extensions.append(pext)
    return extensions


def build_extensions(self):
    # monkey-patch as in distutils.command.build_ext (parallel)
    self.check_extensions_list(self.extensions)
    try:
        self.compiler.compiler_so.remove('-Wstrict-prototypes')
    except (AttributeError, ValueError):
        pass

    for ext in self.extensions:
        try:
            ext.sources = self.cython_sources(ext.sources, ext)
        except AttributeError:
            pass

495
496
497
498
499
    try:
        num_jobs = os.cpu_count()
    except AttributeError:
        num_jobs = multiprocessing.cpu_count()

500
501
    pool = Pool(num_jobs)
    pool.map(self.build_extension, self.extensions)
502
503
504
505
506
    try:
        pool.shutdown()
    except AttributeError:
        pool.close()
        pool.join()
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528


def compile(self, sources, output_dir=None, macros=None,
            include_dirs=None, debug=0, extra_preargs=None,
            extra_postargs=None, depends=None):
    macros, objects, extra_postargs, pp_opts, build = \
        self._setup_compile(output_dir, macros, include_dirs, sources,
                            depends, extra_postargs)
    cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)

    for obj in objects:
        try:
            src, ext = build[obj]
        except KeyError:
            continue
        self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)

    # Return *all* object filenames, not just the ones we just built.
    return objects


def monkeypatch_parallel_build():
529
530
531
    if PARALLEL_COMPILE:
        build_ext.build_extensions = build_extensions
        CCompiler.compile = compile