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