xref: /petsc/setup.py (revision 7d0a6c19129e7069c8a40e210b34ed62989173db) !
1#!/usr/bin/env python
2
3"""
4PETSc: Portable, Extensible Toolkit for Scientific Computation
5==============================================================
6
7The Portable, Extensible Toolkit for Scientific Computation (PETSc),
8is a suite of data structures and routines for the scalable (parallel)
9solution of scientific applications modeled by partial differential
10equations. It employs the Message Passing Interface (MPI) standard for
11all message-passing communication.
12"""
13
14import sys, os
15from distutils.core import setup
16from distutils.util import get_platform, split_quoted
17from distutils.spawn import find_executable
18from distutils.command.build import build as _build
19if 'setuptools' in sys.modules:
20    from setuptools.command.install import install as _install
21else:
22    from distutils.command.install import install as _install
23from distutils.command.sdist import sdist as _sdist
24from distutils import log
25
26init_py = """\
27# Author:  PETSc Team
28# Contact: petsc-maint@mcs.anl.gov
29
30def get_petsc_dir():
31    import os
32    return os.path.dirname(__file__)
33
34def get_config():
35    conf = {}
36    conf['PETSC_DIR'] = get_petsc_dir()
37    return conf
38"""
39
40metadata = {
41    'provides' : ['petsc'],
42    'requires' : [],
43}
44
45def bootstrap():
46    # Set PETSC_DIR and PETSC_ARCH
47    PETSC_DIR  = os.path.abspath(os.getcwd())
48    PETSC_ARCH = get_platform() + '-python'
49    os.environ['PETSC_DIR']  = PETSC_DIR
50    os.environ['PETSC_ARCH'] = PETSC_ARCH
51    sys.path.insert(0, os.path.join(PETSC_DIR, 'config'))
52    # Generate package __init__.py file
53    from distutils.dir_util import mkpath
54    pkgdir = os.path.join('config', 'pypi')
55    pkgfile = os.path.join(pkgdir, '__init__.py')
56    if not os.path.exists(pkgdir):
57        mkpath(pkgdir)
58    if not os.path.exists(pkgfile):
59        open(pkgfile, 'wt').write(init_py)
60    # Simple-minded lookup for MPI and mpi4py
61    mpi4py = mpicc = None
62    try:
63        import mpi4py
64        conf = mpi4py.get_config()
65        mpicc = conf.get('mpicc')
66    except ImportError: # mpi4py is not installed
67        mpicc = os.environ.get('MPICC') or find_executable('mpicc')
68    except AttributeError: # mpi4py is too old
69        pass
70    if not mpi4py and mpicc:
71        if (('distribute' in sys.modules) or
72            ('setuptools' in sys.modules)):
73            metadata['install_requires']= ['mpi4py>=1.2.2']
74    if 'setuptools' in sys.modules:
75        metadata['zip_safe'] = False
76
77def config(dry_run=False):
78    log.info('PETSc: configure')
79    options = [
80        'PETSC_ARCH='+os.environ['PETSC_ARCH'],
81        '--with-shared-libraries=1',
82        '--with-debugging=0',
83        '--with-cmake=0', # not needed
84        ]
85    # MPI
86    try:
87        import mpi4py
88        conf = mpi4py.get_config()
89        mpicc  = conf.get('mpicc')
90        mpicxx = conf.get('mpicxx')
91        mpif90 = conf.get('mpif90')
92    except (ImportError, AttributeError):
93        mpicc  = os.environ.get('MPICC')  or find_executable('mpicc')
94        mpicxx = os.environ.get('MPICXX') or find_executable('mpicxx')
95        mpif90 = os.environ.get('MPIF90') or find_executable('mpif90')
96    if mpicc:
97        options.append('--with-cc='+mpicc)
98        if mpicxx:
99            options.append('--with-cxx='+mpicxx)
100        if mpif90:
101            options.append('--with-fc='+mpif90)
102    else:
103        options.append('--with-mpi=0')
104    # Extra configure options
105    config_opts = os.environ.get('PETSC_CONFIGURE_OPTIONS', '')
106    config_opts = split_quoted(config_opts)
107    options.extend(config_opts)
108    log.info('configure options:')
109    for opt in options:
110        log.info(' '*4 + opt)
111    # Run PETSc configure
112    if dry_run: return
113    import configure
114    configure.petsc_configure(options)
115    import logger
116    logger.Logger.defaultLog = None
117
118def build(dry_run=False):
119    log.info('PETSc: build')
120    # Run PETSc builder
121    if dry_run: return
122    import builder
123    builder.PETScMaker().run()
124    import logger
125    logger.Logger.defaultLog = None
126
127def install(dest_dir, prefix=None, dry_run=False):
128    log.info('PETSc: install')
129    if prefix is None:
130        prefix = dest_dir
131    options = [
132        '--destDir=' + dest_dir,
133        '--prefix='  + prefix,
134        ]
135    log.info('install options:')
136    for opt in options:
137        log.info(' '*4 + opt)
138    # Run PETSc installer
139    if dry_run: return
140    import install
141    install.Installer(options).run()
142    import logger
143    logger.Logger.defaultLog = None
144
145class context:
146    def __init__(self):
147        self.sys_argv = sys.argv[:]
148        self.wdir = os.getcwd()
149    def enter(self):
150        del sys.argv[1:]
151        pdir = os.environ['PETSC_DIR']
152        os.chdir(pdir)
153        return self
154    def exit(self):
155        sys.argv[:] = self.sys_argv
156        os.chdir(self.wdir)
157
158class cmd_build(_build):
159
160    def initialize_options(self):
161        _build.initialize_options(self)
162        PETSC_ARCH = os.environ.get('PETSC_ARCH', '')
163        self.build_base = os.path.join(PETSC_ARCH, 'build-python')
164
165    def run(self):
166        _build.run(self)
167        ctx = context().enter()
168        try:
169            config(self.dry_run)
170            build(self.dry_run)
171        finally:
172            ctx.exit()
173
174class cmd_install(_install):
175
176    def initialize_options(self):
177        _install.initialize_options(self)
178        self.optimize = 1
179
180    def run(self):
181        root_dir = self.install_platlib
182        dest_dir = os.path.join(root_dir, 'petsc')
183        bdist_base = self.get_finalized_command('bdist').bdist_base
184        if dest_dir.startswith(bdist_base):
185            prefix = dest_dir[len(bdist_base)+1:]
186            prefix = prefix[prefix.index(os.path.sep):]
187        else:
188            prefix = dest_dir
189        dest_dir = os.path.abspath(dest_dir)
190        prefix   = os.path.abspath(prefix)
191        #
192        _install.run(self)
193        ctx = context().enter()
194        try:
195            install(dest_dir, prefix, self.dry_run)
196        finally:
197            ctx.exit()
198
199class cmd_sdist(_sdist):
200
201    def initialize_options(self):
202        _sdist.initialize_options(self)
203        self.force_manifest = 1
204        self.template = os.path.join('config', 'manifest.in')
205
206def version():
207    import re
208    version_re = {
209        'major'  : re.compile(r"#define\s+PETSC_VERSION_MAJOR\s+(\d+)"),
210        'minor'  : re.compile(r"#define\s+PETSC_VERSION_MINOR\s+(\d+)"),
211        'micro'  : re.compile(r"#define\s+PETSC_VERSION_SUBMINOR\s+(\d+)"),
212        'patch'  : re.compile(r"#define\s+PETSC_VERSION_PATCH\s+(\d+)"),
213        'release': re.compile(r"#define\s+PETSC_VERSION_RELEASE\s+(\d+)"),
214        }
215    petscversion_h = os.path.join('include','petscversion.h')
216    data = open(petscversion_h, 'rt').read()
217    major = int(version_re['major'].search(data).groups()[0])
218    minor = int(version_re['minor'].search(data).groups()[0])
219    micro = int(version_re['micro'].search(data).groups()[0])
220    patch = int(version_re['patch'].search(data).groups()[0])
221    release = int(version_re['release'].search(data).groups()[0])
222    if release:
223        v = "%d.%d" % (major, minor)
224        if micro > 0:
225            v += ".%d" % micro
226        if patch > 0:
227            v += ".post%d" % patch
228    else:
229        v = "%d.%d.dev%d" % (major, minor+1, 0)
230    return v
231
232def tarball():
233    VERSION = version()
234    if '.dev' in VERSION:
235        return None
236    if '.post' not in VERSION:
237        VERSION = VERSION + '.post0'
238    VERSION = VERSION.replace('.post', '-p')
239    return ('http://ftp.mcs.anl.gov/pub/petsc/release-snapshots/'
240            'petsc-lite-%s.tar.gz' % VERSION)
241
242description = __doc__.split('\n')[1:-1]; del description[1:3]
243classifiers = """
244License :: Public Domain
245Operating System :: POSIX
246Intended Audience :: Developers
247Intended Audience :: Science/Research
248Programming Language :: C
249Programming Language :: C++
250Programming Language :: Fortran
251Programming Language :: Python
252Topic :: Scientific/Engineering
253Topic :: Software Development :: Libraries
254"""
255
256bootstrap()
257setup(name='petsc',
258      version=version(),
259      description=description.pop(0),
260      long_description='\n'.join(description),
261      classifiers= classifiers.split('\n')[1:-1],
262      keywords = ['PETSc', 'MPI'],
263      platforms=['POSIX'],
264      license='PETSc',
265
266      url='http://www.mcs.anl.gov/petsc/',
267      download_url=tarball(),
268
269      author='PETSc Team',
270      author_email='petsc-maint@mcs.anl.gov',
271      maintainer='Lisandro Dalcin',
272      maintainer_email='dalcinl@gmail.com',
273
274      packages = ['petsc'],
275      package_dir = {'petsc': 'config/pypi'},
276      cmdclass={
277        'build': cmd_build,
278        'install': cmd_install,
279        'sdist': cmd_sdist,
280        },
281      **metadata)
282