xref: /petsc/setup.py (revision 1af0834683a77e7dac83d8bbabb5a5ffcd55c6d1)
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, install
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 setuptools:
109        src = os.path.join('src', 'petsc4py.PETSc.c')
110        has_src = os.path.exists(os.path.join(topdir, src))
111        has_git = os.path.isdir(os.path.join(topdir, '.git'))
112        has_hg  = os.path.isdir(os.path.join(topdir, '.hg'))
113        if not has_src or has_git or has_hg:
114            setup_args['setup_requires'] = ['Cython>='+CYTHON]
115    #
116    setup(packages     = ['petsc4py',
117                          'petsc4py.lib',],
118          package_dir  = {'petsc4py'     : 'src',
119                          'petsc4py.lib' : 'src/lib'},
120          package_data = {'petsc4py'     : ['include/petsc4py/*.h',
121                                            'include/petsc4py/*.i',
122                                            'include/petsc4py/*.pxd',
123                                            'include/petsc4py/*.pxi',
124                                            'include/petsc4py/*.pyx',
125                                            'PETSc.pxd',],
126                          'petsc4py.lib' : ['petsc.cfg'],},
127          ext_modules  = get_ext_modules(Extension),
128          cmdclass     = {'config'     : config,
129                          'build'      : build,
130                          'build_src'  : build_src,
131                          'build_ext'  : build_ext,
132                          'install'    : install,
133                          'clean'      : clean,
134                          'test'       : test,
135                          'sdist'      : sdist,
136                          },
137          **setup_args)
138
139def chk_cython(VERSION):
140    from distutils import log
141    from distutils.version import LooseVersion
142    from distutils.version import StrictVersion
143    warn = lambda msg='': sys.stderr.write(msg+'\n')
144    #
145    try:
146        import Cython
147    except ImportError:
148        warn("*"*80)
149        warn()
150        warn(" You need to generate C source files with Cython!!")
151        warn(" Download and install Cython <http://www.cython.org>")
152        warn()
153        warn("*"*80)
154        return False
155    #
156    try:
157        CYTHON_VERSION = Cython.__version__
158    except AttributeError:
159        from Cython.Compiler.Version import version as CYTHON_VERSION
160    REQUIRED = VERSION
161    m = re.match(r"(\d+\.\d+(?:\.\d+)?).*", CYTHON_VERSION)
162    if m:
163        Version = StrictVersion
164        AVAILABLE = m.groups()[0]
165    else:
166        Version = LooseVersion
167        AVAILABLE = CYTHON_VERSION
168    if (REQUIRED is not None and
169        Version(AVAILABLE) < Version(REQUIRED)):
170        warn("*"*80)
171        warn()
172        warn(" You need to install Cython %s (you have version %s)"
173             % (REQUIRED, CYTHON_VERSION))
174        warn(" Download and install Cython <http://www.cython.org>")
175        warn()
176        warn("*"*80)
177        return False
178    #
179    return True
180
181def run_cython(source, depends=(), includes=(),
182               destdir_c=None, destdir_h=None,
183               wdir=None, force=False, VERSION=None):
184    from glob import glob
185    from distutils import log
186    from distutils import dep_util
187    from distutils.errors import DistutilsError
188    target = os.path.splitext(source)[0]+'.c'
189    cwd = os.getcwd()
190    try:
191        if wdir: os.chdir(wdir)
192        alldeps = [source]
193        for dep in depends:
194            alldeps += glob(dep)
195        if not (force or dep_util.newer_group(alldeps, target)):
196            log.debug("skipping '%s' -> '%s' (up-to-date)",
197                      source, target)
198            return
199    finally:
200        os.chdir(cwd)
201    if not chk_cython(VERSION):
202        raise DistutilsError("requires Cython>=%s" % VERSION)
203    log.info("cythonizing '%s' -> '%s'", source, target)
204    from conf.cythonize import cythonize
205    err = cythonize(source,
206                    includes=includes,
207                    destdir_c=destdir_c,
208                    destdir_h=destdir_h,
209                    wdir=wdir)
210    if err:
211        raise DistutilsError(
212            "Cython failure: '%s' -> '%s'" % (source, target))
213
214def build_sources(cmd):
215    from os.path import exists, isdir, join
216    if (exists(join('src', 'petsc4py.PETSc.c')) and
217        not (isdir('.hg') or isdir('.git')) and
218        not cmd.force): return
219    # petsc4py.PETSc
220    source = 'petsc4py.PETSc.pyx'
221    depends = ('include/*/*.pxd',
222               'PETSc/*.pyx',
223               'PETSc/*.pxi',)
224    includes = ['include']
225    destdir_h = os.path.join('include', 'petsc4py')
226    run_cython(source, depends, includes,
227               destdir_c=None, destdir_h=destdir_h, wdir='src',
228               force=cmd.force, VERSION=CYTHON)
229    # libpetsc4py
230    source = os.path.join('libpetsc4py', 'libpetsc4py.pyx')
231    depends = ['include/petsc4py/*.pxd',
232               'libpetsc4py/*.pyx',
233               'libpetsc4py/*.pxi']
234    includes = ['include']
235    run_cython(source, depends, includes,
236               destdir_c=None, destdir_h=None, wdir='src',
237               force=cmd.force, VERSION=CYTHON)
238
239build_src.run = build_sources
240
241def run_testsuite(cmd):
242    from distutils.errors import DistutilsError
243    sys.path.insert(0, 'test')
244    try:
245        from runtests import main
246    finally:
247        del sys.path[0]
248    if cmd.dry_run:
249        return
250    args = cmd.args[:] or []
251    if cmd.verbose < 1:
252        args.insert(0,'-q')
253    if cmd.verbose > 1:
254        args.insert(0,'-v')
255    err = main(args)
256    if err:
257        raise DistutilsError("test")
258
259test.run = run_testsuite
260
261# --------------------------------------------------------------------
262
263def main():
264    run_setup()
265
266if __name__ == '__main__':
267    main()
268
269# --------------------------------------------------------------------
270