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