xref: /petsc/setup.py (revision efa7d5adb895d317aa1dda4fd2e15e44e89e2133)
1#!/usr/bin/env python
2# Author:  Lisandro Dalcin
3# Contact: dalcinl@gmail.com
4
5"""
6PETSc for Python
7"""
8
9import sys
10import os
11import re
12
13try:
14    import setuptools
15except ImportError:
16    setuptools = None
17
18pyver = sys.version_info[:2]
19if pyver < (2, 6) or (3, 0) <= pyver < (3, 2):
20    raise RuntimeError("Python version 2.6, 2.7 or >= 3.2 required")
21
22# --------------------------------------------------------------------
23# Metadata
24# --------------------------------------------------------------------
25
26topdir = os.path.abspath(os.path.dirname(__file__))
27
28from conf.metadata import metadata
29
30def name():
31    return 'petsc4py'
32
33def version():
34    with open(os.path.join(topdir, 'src', '__init__.py')) as f:
35        m = re.search(r"__version__\s*=\s*'(.*)'", f.read())
36        return m.groups()[0]
37
38def description():
39    with open(os.path.join(topdir, 'DESCRIPTION.rst')) as f:
40        return f.read()
41
42name     = name()
43version  = version()
44
45url      = 'https://bitbucket.org/petsc/%(name)s/' % vars()
46download = url + 'downloads/%(name)s-%(version)s.tar.gz' % vars()
47
48devstat  = ['Development Status :: 5 - Production/Stable']
49keywords = ['PETSc', 'MPI']
50
51metadata['name'] = name
52metadata['version'] = version
53metadata['description'] = __doc__.strip()
54metadata['long_description'] = description()
55metadata['keywords'] += keywords
56metadata['classifiers'] += devstat
57metadata['url'] = url
58metadata['download_url'] = download
59
60metadata['provides'] = ['petsc4py']
61metadata['requires'] = ['numpy']
62
63# --------------------------------------------------------------------
64# Extension modules
65# --------------------------------------------------------------------
66
67def get_ext_modules(Extension):
68    from os   import walk, path
69    from glob import glob
70    depends = []
71    for pth, dirs, files in walk('src'):
72        depends += glob(path.join(pth, '*.h'))
73        depends += glob(path.join(pth, '*.c'))
74    try:
75        import numpy
76        numpy_includes = [numpy.get_include()]
77    except ImportError:
78        numpy_includes = []
79    return [Extension('petsc4py.lib.PETSc',
80                      sources=['src/PETSc.c',
81                               'src/libpetsc4py.c',
82                               ],
83                      include_dirs=['src/include',
84                                    ] + numpy_includes,
85                      depends=depends)]
86
87# --------------------------------------------------------------------
88# Setup
89# --------------------------------------------------------------------
90
91from conf.petscconf import setup, Extension
92from conf.petscconf import config, build, build_src, build_ext
93from conf.petscconf import clean, test, sdist
94
95CYTHON = '0.22'
96
97def run_setup():
98    setup_args = metadata.copy()
99    if setuptools:
100        setup_args['zip_safe'] = False
101        setup_args['install_requires'] = ['numpy']
102        PETSC_DIR = os.environ.get('PETSC_DIR')
103        if not (PETSC_DIR and os.path.isdir(PETSC_DIR)):
104            vstr = setup_args['version'].split('.')[:2]
105            x, y = int(vstr[0]), int(vstr[1])
106            PETSC = ">=%s.%s,<%s.%s" % (x, y, x, y+1)
107            setup_args['install_requires'] += ['petsc'+PETSC]
108        if not os.path.exists(os.path.join('src', 'petsc4py.PETSc.c')):
109            setup_args['setup_requires'] = ['Cython>='+CYTHON]
110    #
111    setup(packages     = ['petsc4py',
112                          'petsc4py.lib',],
113          package_dir  = {'petsc4py'     : 'src',
114                          'petsc4py.lib' : 'src/lib'},
115          package_data = {'petsc4py'     : ['include/petsc4py/*.h',
116                                            'include/petsc4py/*.i',
117                                            'include/petsc4py/*.pxd',
118                                            'include/petsc4py/*.pxi',
119                                            'include/petsc4py/*.pyx',],
120                          'petsc4py.lib' : ['petsc.cfg'],},
121          ext_modules  = get_ext_modules(Extension),
122          cmdclass     = {'config'     : config,
123                          'build'      : build,
124                          'build_src'  : build_src,
125                          'build_ext'  : build_ext,
126                          'clean'      : clean,
127                          'test'       : test,
128                          'sdist'      : sdist,
129                          },
130          **setup_args)
131
132def chk_cython(VERSION):
133    from distutils import log
134    from distutils.version import LooseVersion
135    from distutils.version import StrictVersion
136    warn = lambda msg='': sys.stderr.write(msg+'\n')
137    #
138    try:
139        import Cython
140    except ImportError:
141        warn("*"*80)
142        warn()
143        warn(" You need to generate C source files with Cython!!")
144        warn(" Download and install Cython <http://www.cython.org>")
145        warn()
146        warn("*"*80)
147        return False
148    #
149    try:
150        CYTHON_VERSION = Cython.__version__
151    except AttributeError:
152        from Cython.Compiler.Version import version as CYTHON_VERSION
153    REQUIRED = VERSION
154    m = re.match(r"(\d+\.\d+(?:\.\d+)?).*", CYTHON_VERSION)
155    if m:
156        Version = StrictVersion
157        AVAILABLE = m.groups()[0]
158    else:
159        Version = LooseVersion
160        AVAILABLE = CYTHON_VERSION
161    if (REQUIRED is not None and
162        Version(AVAILABLE) < Version(REQUIRED)):
163        warn("*"*80)
164        warn()
165        warn(" You need to install Cython %s (you have version %s)"
166             % (REQUIRED, CYTHON_VERSION))
167        warn(" Download and install Cython <http://www.cython.org>")
168        warn()
169        warn("*"*80)
170        return False
171    #
172    return True
173
174def run_cython(source, depends=(), includes=(),
175               destdir_c=None, destdir_h=None,
176               wdir=None, force=False, VERSION=None):
177    from glob import glob
178    from distutils import log
179    from distutils import dep_util
180    from distutils.errors import DistutilsError
181    target = os.path.splitext(source)[0]+'.c'
182    cwd = os.getcwd()
183    try:
184        if wdir: os.chdir(wdir)
185        alldeps = [source]
186        for dep in depends:
187            alldeps += glob(dep)
188        if not (force or dep_util.newer_group(alldeps, target)):
189            log.debug("skipping '%s' -> '%s' (up-to-date)",
190                      source, target)
191            return
192    finally:
193        os.chdir(cwd)
194    if not chk_cython(VERSION):
195        raise DistutilsError("requires Cython>=%s" % VERSION)
196    log.info("cythonizing '%s' -> '%s'", source, target)
197    from conf.cythonize import cythonize
198    err = cythonize(source,
199                    includes=includes,
200                    destdir_c=destdir_c,
201                    destdir_h=destdir_h,
202                    wdir=wdir)
203    if err:
204        raise DistutilsError(
205            "Cython failure: '%s' -> '%s'" % (source, target))
206
207def build_sources(cmd):
208    from os.path import exists, isdir, join
209    if (exists(join('src', 'petsc4py.PETSc.c')) and
210        not (isdir('.hg') or isdir('.git')) and
211        not cmd.force): return
212    # petsc4py.PETSc
213    source = 'petsc4py.PETSc.pyx'
214    depends = ('include/*/*.pxd',
215               'PETSc/*.pyx',
216               'PETSc/*.pxi',)
217    includes = ['include']
218    destdir_h = os.path.join('include', 'petsc4py')
219    run_cython(source, depends, includes,
220               destdir_c=None, destdir_h=destdir_h, wdir='src',
221               force=cmd.force, VERSION=CYTHON)
222    # libpetsc4py
223    source = os.path.join('libpetsc4py', 'libpetsc4py.pyx')
224    depends = ['include/petsc4py/*.pxd',
225               'libpetsc4py/*.pyx',
226               'libpetsc4py/*.pxi']
227    includes = ['include']
228    run_cython(source, depends, includes,
229               destdir_c=None, destdir_h=None, wdir='src',
230               force=cmd.force, VERSION=CYTHON)
231
232build_src.run = build_sources
233
234def run_testsuite(cmd):
235    from distutils.errors import DistutilsError
236    sys.path.insert(0, 'test')
237    try:
238        from runtests import main
239    finally:
240        del sys.path[0]
241    if cmd.dry_run:
242        return
243    args = cmd.args[:] or []
244    if cmd.verbose < 1:
245        args.insert(0,'-q')
246    if cmd.verbose > 1:
247        args.insert(0,'-v')
248    err = main(args)
249    if err:
250        raise DistutilsError("test")
251
252test.run = run_testsuite
253
254# --------------------------------------------------------------------
255
256def main():
257    run_setup()
258
259if __name__ == '__main__':
260    main()
261
262# --------------------------------------------------------------------
263