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